# Question
Title: Insert/create user in database using login form
I know its dump question, using login form and insert user in database.

Actually, I have an API that includes users of company/organization and these users already have registered on other applications. So, using such API I can get user info using username and password.

Of course, we need to logged in users directly (without registration) who already have account on other applications.

For logging in, I need to, first, insert the user info in data (before insertion, I can fetch username and password from API) so user can get in the site as logged in user.

* **After fetching from API, how to create user in the database with username and password field only?**
* **It should be done without email info.**

# Answer
According to my question requirements, it can be done by using the user\_external\_login\_register and user\_external\_load Drupal APIs. See the custom module below for more understanding. I hope this will help someone who needs the same requirement(s).

```
<?php
/**
* Implementation of hook_form_FORM_ID_alter
*/
function hook_form_user_login_alter(&$form, &$form_state) {
    _subscribe_user_login_form_alter($form, $form_state);
}
function _subscribe_user_login_form_alter(&$form, &$form_state) {
    $saveForm = $form;
    $form = array();
    // overrides the default validator
    foreach( $saveForm as $key => $value ) {
        if( $key == '#validate' ) {
            $form[ $key ] = array();
            foreach( $value as $validator ) {
                if( $validator == 'user_login_authenticate_validate' ) {
                    $validator = 'MODULENAME_authenticate_validate';
                }
            $form[ $key ][] = $validator;
            }
        } else {
            $form[ $key ] = $value;
        }
    }
}

function MODULENAME_authenticate_validate( $form, &$form_state ) {
    $name = $form_state[ 'values' ][ 'name' ];
    $pass = $form_state[ 'values' ][ 'pass' ];
    // use Drupal authentication for this user
    if ($name == 'admin'){
        return user_login_authenticate_validate($form, $form_state);
    }
    $authenticated = api_check_user($name, $pass);
    if ($authenticated == TRUE){
        //save external user if don't exist
        user_external_login_register($name, "MODULENAME");
        // we must set the 'uid' to pass back.  this looks up the logged in user and sets the Drupal UID
        $account = user_external_load($name);
        $form_state['uid'] = $account->uid;
        drupal_set_message(t('an error has occured'));
    }else{
        drupal_set_message('Error displayed'); // do nothing, Drupal will handle the errors
    }
}
function api_check_user($name, $pass){
    //write code to authenticate user from API
    //if username and password match then API returns true/false
    //if we get true
    return TRUE;
}

```
> 0 votes

# Answer
It is not possible to create a user account in Drupal without writing an email account.

An example of how you can create a user programmatically is:

```
 $new_user = array(
  'name' => 'name',
  'mail' => 'name@email.com',
  'pass' => 'password', // note: do not md5 the password
  'status' => 1
 );

 //custom fields
 $new_user->field_name_lasname['und'][0]['value'] = 'Name and Last Name';
 //custom fields ( custom fields)
 $new_user->field_referenced_field_['und'][0]['target_id'] = 0;

 user_save(null, $new_user);

```

Please excuse me my English is not good
> 0 votes

---
Tags: 7, users
---


title: How to render a weight element?

text:
# Question
Title: How to render a weight element?
I'm trying to render a weight element but it doesn't works I just have as output an empty string. But when I try to render a checkbox I get the correct output.

For the **weight** element:

```
$weight = array(
  '#type' => 'weight',
  '#title' => t('Weight'),
  '#default_value' => 1,
  '#delta' => 10,
);

// For Drupal 7.
dpm(drupal_render($weight));
// For Drupal 8.
kint(\Drupal::service('renderer')->render($weight));

```

***Output:*** An empty string.

For the **checkbox** element.

```
$check = array(
  '#type' => 'checkbox',
  '#title' => t('Dry run'),
  '#description' => t('Test run without deleting revisions but seeing the output results.'),
);
// For Drupal 7.
dpm(drupal_render($check));
// For Drupal 8.
kint(\Drupal::service('renderer')->render($check));

```

**Output:**

```
<div class="form-item form-type-checkbox">
 <input type="checkbox" value="1" class="form-checkbox" />  <label class="option">Dry run </label>

<div class="description">Test run without deleting revisions but seeing the output results.</div>
</div>

```

So, I think that the `drupal_render()` function and renderer service are working fine because the checkbox is rendered, but the weight element not, I'm missing something here?

# Answer
> 4 votes
The select element is built in Weight::processWeight():

```
  /**
   * Expands a weight element into a select element.
   */
  public static function processWeight(&$element, FormStateInterface $form_state, &$complete_form) {
    $element['#is_weight'] = TRUE;

    $element_info_manager = \Drupal::service('element_info');
    // If the number of options is small enough, use a select field.
    $max_elements = \Drupal::config('system.site')->get('weight_select_max');
    if ($element['#delta'] <= $max_elements) {
      $element['#type'] = 'select';
      $weights = [];
      for ($n = (-1 * $element['#delta']); $n <= $element['#delta']; $n++) {
        $weights[$n] = $n;
      }
      $element['#options'] = $weights;
      $element += $element_info_manager->getInfo('select');
    }
    // Otherwise, use a text field.
    else {
      $element['#type'] = 'number';
      // Use a field big enough to fit most weights.
      $element['#size'] = 10;
      $element += $element_info_manager->getInfo('number');
    }

    return $element;
  }

```

Which is only called in form building, not in normal rendering.

---
Tags: theming
---


# Question
Title: How do I convert the result fro views_get_view_result() to an array?
I am getting an object from `views_get_view_result()`.

```
Array
(
 [0] => Drupal\views\ResultRow Object
    (
        [_entity] => Drupal\node\Entity\Node Object
            (
                [in_preview] =>
                [values:protected] => Array
                    (
                        [vid] => Array
                            (
                                [x-default] => 9
                            )

                        [langcode] => Array
                            (
                                [x-default] => en
                            )

                        [revision_uid] => Array
                            (
                                [x-default] => 1
                            )

                        [revision_timestamp] => Array
                            (
                                [x-default] => 1508904645
                            )

                        [revision_log] => Array
                            (
                                [x-default] =>
                            )

```

How do I convert it to an array? My objective is to get the content types fields values. In an entity object there is `toArray()` to achieve this, but it doesn't work for what `views_get_view_result()` returns.

# Answer
> 0 votes
This is the entity you are looking for:

```
$node = $row->_entity;

```

And the field values:

```
$values = $node->toArray();

```

These are all of the values from the node, however if you want the results from the fields configured in the Views UI, see Get result view with formatter programmattically

---
Tags: views, 8, nodes
---


title: How to cache minipanels

text:
# Question
Title: How to cache minipanels
I use minipanels in specific regions of pages (such as the main menu region) and they generally conain content that stays the same. How can I cache these minipanels?

Is the block caching system independent from the minipanels? I am not sure about that, since minipanels also show in the blocks configuration admin page.

# Answer
> 2 votes
You can cache mini panels from mini panels UI settings. Go to the mini panel content edition page.

You have then 2 choices. Above in global mini panel display settings or per panel content piece : in its wheel settings at the bottom...

---
Tags: 7, panels, caching
---


# Question
Title: How to create dependent fields in Entity:baseFieldDefinition?
I have created a select list of content types in baseFieldDefinition

```
$fields['ctype'] = BaseFieldDefinition::create('list_string')
      ->setLabel(t('Content Type'))
      ->setDescription(t('Choose content type '))
      ->setRequired(TRUE)
      ->setSettings(array(
        'allowed_values' => $ctypes,
      ))
      ->setDisplayOptions('view', array(
        'label' => 'above',
        'type' => 'string',
        'weight' => -5,
      ))
      ->setDisplayOptions('form', array(
        'type' => 'options_select',
        'weight' => -5,
      ))
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

```

Does Drupal provides `ajax` feature to use in `baseFieldDefinition` ?

Basically I want to generate **field list** of *selected content type* using entity.

# Answer
> Does Drupal provides `ajax` feature to use in `baseFieldDefinition` ?

Short answer: no

Long answer:

The base field definition method is used to define the entity structure and the database structure.

If you are trying to display different form items when the toe changes then you should do that on the **form object** level. By adding a `#ajax` attribute to the type field.
> 3 votes

# Answer
I think this is the right place for my answer. I´ve also defined a entity with a basefielddefinition and would like to add a ajax handler to a select list. So i´m using the buildForm-function and add the following ajax snippet to the form:

```
$form['formid']['#ajax'] =[
'callback' => '::ajaxHandler',
'event' => 'change',
'wrapper' => 'edit-output',
'progress' => [
  'type' => 'throbber',
  'message' => t('Verifying entry...'),
],

 ];

```

By using the ajax example form in my buildForm everything works fine, but not with my formid-field. thanks for helping me. best regards andy
> 0 votes

---
Tags: 8, entities
---


# Question
Title: Safely change module without losing change at module update
I'm using the Image\_Widget\_Crop module for a Drupal 8 website. In this module there is a .js file setting the default values for Cropper.

```
Drupal.ImageWidgetCropType.prototype.defaultOptions = {
    autoCropArea: 1,
    background: false,
    responsive: false,
    viewMode: 1,
    zoomable: false
  };

```

I want to add a setting without putting it in the module so when updating my change doesn't get lost, how can I do this?

I want it to look like this.

```
Drupal.ImageWidgetCropType.prototype.defaultOptions = {
    autoCropArea: 1,
    background: false,
    responsive: false,
    viewMode: 1,
    zoomable: false,
    toggleDragModeOnDblclick: false
  };

```

# Answer
> 2 votes
Add your own library with a JS file, make sure the file has a weight higher than the image widget crop's JS file, then simply monkey patch the existing object like so:

```
Drupal.ImageWidgetCropType.prototype.defaultOptions.toggleDragModeOnDblclick = false;

```

---
Tags: 8, media
---


# Question
Title: Only allow specific roles to upload specific extension files
How do I restrict users with specific roles to upload files with specific extensions on node edit pages. On my site I have two specific roles editor and animator. Conditions are:

Editors can only upload .docx .doc .pdf files while Animators can upload .mp4 .mp3 .jpg files.

I added a validate function with `hook_form_alter()` and the validate does work but the user has to save the entire form before validation spits out an error about the wrong file extension. I want to get the file extension as soon as the user has finished uploading their file and display the error message before submitting the form but after uploading the file.

# Answer
> 0 votes
I have a quick solution for this using `hook_form_alter`.

So in your `hook_form_alter` you can check the user role and alter the validators key for that field. In my case the field was called `field_material`

```
global $user;
$valid_role = 'animator';

if(in_array($valid, $user->roles)) {
    //Change the extension in the validators key of that upload field
    $form['field_material']['und'][0]['#upload_validators']['file_validate_extensions'][0]  = 'mp4 mp3';
}

```

I am sure there are better solutions but this is quickest one so far for me to get going.

---
Tags: 7, forms, files
---


# Question
Title: One Time Login URL not Received : Looking for a Spare Solution
Some (only a few) of my users do not receive the "one time login url" mail when they want to reset their (forgotten) password (also checked in spam and trash).

The odd thing is that if I personnaly send them a mail from postmaster@... (using thunderbird for instance), they receive it. I find no explanation to that.

So, I envisage to personnaly send them their \[user:one-time-login-url\]. Can I do that ? How ?

# Answer
In the user module function `user_pass_reset_url($account)` is used to generate one time login url. if you know the uid of the user you can load that user object and pass it as the `$account` for that function and send the generated link in your custom email.
> 0 votes

---
Tags: users, emails
---


# Question
Title: How can I filter an index view using REST?
I have a custom content type called 'Regions', which simply has a title field. Example values are: Asia, North America, Ocenia, etc.

I've set up a view for this list and a REST export for it, so `/regions` gives me a simple list:

`[{"title":"Asia"},{"title":"North America"},{"title":"South America"},{"title":"Ocenia"}]`

I want to filter the results, so I added a contextual filter on the title field, making `/regions/Asia` show only Asia:

`[{"title":"Asia"}]`

How do I implement a wildcard search? Something like `as` should match `Asia` and `amer` should match both `North America` and `South America`. I'd like to do something like `/regions?title=Asia`

I referred to this guide on setting up contextual filters, but the following doesn't seem to work for me:

> This query works as a SQL `LIKE` statement so you can send just a piece of the name and Views will try to find all records `LIKE` that argument, example, I have a brand called `Land Rover` but if I just send `Land` as an argument it will work http://dev-cars-api.pantheonsite.io/api/cars/Land

The URL in the quote is no longer online, so I can't check if it actually works. For me, only entering a full, matching item title works. I can't even specify a title with spaces, so `/regions/North+America` is also blank for me.

My Drupal version is 8.4, running on PHP 7.1.

# Answer
The solution is to add a search filter to the view.

In the view settings, under `Filter Criteria`, you'll see `Content: Published (= Yes)` and `Content: Content type (= Regions)` (or whatever your view is for).

1. Click add. In that box that shows all the fields you can add, type `Search: Search Keywords`.
2. Tick `Expose this filter to visitors, to allow them to change it`.
3. (optional) Rename the Filter Identifier from `keys` to `query` or `terms` or whatever you see fit.
4. Save the view.

You'll then be able to make a `GET http://example.com/api/regions/?_format=json&keys=my+search+string`!
> 0 votes

---
Tags: 8
---


# Question
Title: Custom content entity template preprocess doesn't contain any variables
I've created a custom entity and a template for it.

path to template /modules/custom/my\_module/templates.

My theme\_hook()

```
/**
 * Implements hook_theme().
 */
function my_module_theme($existing, $type, $theme, $path) {
  return [
    'my_module' => [
      'path' => $path . '/templates',
      'template' => 'my-module',
      'variables' => [
        '#my_entity' => '',
      ],
    ],
  ];
}

```

My preprocess

```
/**
 * Prepares variables for My Module templates.
 *
 * Default template: my-module.html.twig.
 *
 * @param array $variables
 *   An associative array containing:
 *   - elements: An associative array containing the user information and any
 *   - attributes: HTML attributes for the containing element.
 */
function template_preprocess_my_template(array &$variables) {
  // Fetch my_entity Entity Object.
  $my_entity = $variables['elements']['#my_entity'];

  // Helpful $content variable for templates.
  foreach (Element::children($variables['elements']) as $key) {
    $variables['content'][$key] = $variables['elements'][$key];
  }
}

```

But all I get is the user object nothing else.

Did I miss something?

# Answer
I needed to remove the #

```
/**
 * Implements hook_theme().
 */
function my_module_theme($existing, $type, $theme, $path) {
  return [
    'my_module' => [
      'path' => $path . '/templates',
      'template' => 'my-module',
      'variables' => [
        'my_entity' => '',
      ],
    ],
  ];
}

```

now i have my entity and can work on :)
> 2 votes

---
Tags: theming, 8
---


# Question
Title: Programmatically (via php code) create content of a specified type
In **drupal 8** I have created a **bespoke content type**... I now would like to create content of the bespoke content type via Php through user interaction. For example, the user clicks a button and it triggers a function in my module which I am creating.

I have used the following code:

```
$node = Node::create([
  'type'        => 'article',
  'title'       => 'My title',
   ]);
   $node->save();

```

Which does create content in the content area of the admin panel, but... The **content type column is empty**?

Am sure someone will all ready have done this type of thing before so any help will be most welcomed.

# Answer
> 1 votes
Thanks Ivan Jaros and Kevin ... Once I placed the machine name of the content type (rather than it's human readable title) as the type value the content created successful and was of the required type e.g.

```
$node = Node::create([
    'type'        => 'the machine name associated with the content type',
    'title'       => 'My title',
   ]);
 $node->save();

```

---
Tags: 8, nodes
---


title: Multiple Webforms in one View

text:
# Question
Title: Multiple Webforms in one View
I have 4 webforms on a site and I would like to be able to display the data from each of those in a table using a view. Each of the forms has a "First Name" "Last Name" "Phone Number" and "Email Address" field, along with other fields that are specific to the different forms. Ideally, I would like to have a table that shows those 4 fields from all of the forms along with a column that says what form it came from. Can anyone give me an idea of where to start? My assumption is that the answer is somewhere in relationships and contextual filters, but I'm still learning how all of that stuff works. Any help or advice would be greatly appreciated. Thanks!!

# Answer
Well after a couple of weeks I got it to work. In case anyone else wants to do the same, here is how I did it.

I added a Webform submissions: Data Relationship for each field in each form (16 total for me....4 fields from 4 webforms). Then I added the fields for each one (again 16 total). Then I went into the Table Settings and had each of the 4 types displayed in the same column. Then I just added a Content: Title field to show which Webform the submission came from.

I don't know if that is the best way to do it, but it worked for me.
> 0 votes

# Answer
Just stack into this and found one more solution:

1. Create the view to show webform submissions
2. Set its output format to Rendered Submissions | HTML

Ok, now we have all data from webform, but it looks not so good.

Create in your administration theme file **webform-submission.tpl.php** and theme it!

**In my case** it looks like this:

```
<?php
    print 'Form name: '.$node->title.' <p><b>'.date('d.m.Y h:i', $submission->submitted).'</b></p>';
    print drupal_render_children($renderable);
?>

```

You can output more data from $node, $submission and $renderable variables.
> 0 votes

---
Tags: webforms, views
---


title: Profile2 , change page title

text:
# Question
Title: Profile2 , change page title
With profile2 all the profile page titles is the profile type.

How do I override it with a field from profile2?

I was wondering something like this

```
hook_preprocess_page(&$variables){
if ($page-type == profile2) {
$new_title = field_get_items('profile2', $profile, 'field_new_title');

  drupal_set_title($new_title);
}
}

```

Of course this script does not work.

This needs to happen just on the profile page, not in the profile listing page.

# Answer
> 2 votes
To change the content title (defaults to the username) you can use this snippet in a custom module:

```
<?php
function MYMODULE_custom_menu_alter(&$items) {
 $items['user/%user']['title callback'] = MYMODULE_user_page_title;
}

function MYMODULE_user_page_title() {

if(arg(0) == 'user') {
// Load uid from url
$user = user_load(arg(1));
// Load profile2 entity
$profile2 = profile2_load_by_user($user->uid);
// Load fields
$myfield = field_get_items('profile2', $profile2['main'], 'field_myfield');
$output = $myfield[0]['safe_value'];
}

// Fallback to username if no fields are present
if(empty($output)) {
   $output = $user->name;
 }

return $output;

}
?>

```

Reference : http://drupal.org/node/1262070, Change page title on user-profile using a field value from Profile2

# Answer
> 1 votes
Issue can be addressed using Rules:

```
{ "rules_profile2_page_title_change" : {
    "LABEL" : "Profile2 Page Title Change",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "User" ],
    "REQUIRES" : [ "rules", "profile2" ],
    "ON" : { "profile2_view" : [] },
    "DO" : [
      { "data_set" : {
          "data" : [ "profile2:user:profile-main:label" ],
          "value" : "[profile2:user]"
        }
      }
    ]
  }
}

```
* Note: change "data\_set" \> "data" to the name of your profile type

further details

# Answer
> 1 votes
You can use **HOOK\_page\_alter(&$page)**

```
function HOOK_page_alter(&$page) {

  if (isset($page['content']['system_main']['profile2']) &&  is_array(($page['content']['system_main']['profile2']))) {
  /* To make sure you're in the profile page */

  $pid = array_keys($page['content']['system_main']['profile2']);
  if (count($pid) === 1) {
     $pid = reset($pid);
      if (isset($page['content']['system_main']['profile2'][$pid]['field_name']['#items'][0]['value'])) {
        /*To get Profile Name */
        $title = drupal_get_title();

        $profile_name = $page['content']['system_main']['profile2'][$pid]['field_name']['#items'][0]['value'];

         drupal_set_title($title . ' ' . $profile_name);
       }
     }
   }
 }

```

> So the output of this function is : **Profile Artist ArtisName**

---
Tags: theming, users, 7
---


# Question
Title: How can I add a field to a view that is calculated using other fields?
How can I add a new field to a view that is calculated using other fields?

Is there a way native to Views to accomplish this?

---

**If the original view returns the row:** `X | Y | Z`

**And I have a function calculating new data:** `$new = do_something(X, Y, Z);`

**How can I include $new as a fourth column to resulting in:** `X | Y | Z | $new`

---

I have looked into using a views template to accomplish this, but I'm curious as to whether there is a better way to do this using Views hooks or another module.

What templates, hooks or modules would be best suited to accomplish this?

# Answer
> 3 votes
I think Computed Field module is a good fit for this: http://drupal.org/project/computed\_field

With this, you will be able to add a computed type field to your content type. You can do calculations based on other field's values.

If you set up the field, you just simply have to add that field into your view, like you did with x, y and z.

I used it once for a price field that was given by the user in USD and than I had to make another field with the price converted into EUR, it looked something like this, used from a custom module:

```
function computed_field_field_euro_compute(&$entity_field, $entity_type, $entity, $field, $instance, $langcode, $items) {
  $value = $entity->field_price;
  // do some calculations with the value of field_price
  $entity_field[0]['value'] = $value; //return your modified value to your computed field
}

```

You can input your code in the Drupal admin in your field's settings, or you can put it in a custom module like I did above.

# Answer
> 7 votes
You could create your own views field handler in a custom module. Implement **hook\_views\_api** and **hook\_views\_data\_alter(&$data)** than you can write your own field handler.

# Answer
> 4 votes
You can use `hook_views_data` in a custom module. It takes a little longer to implement but makes for a very modular solution because you get a VIRTUAL views field.

declare views api version in your `MODULE_NAME.module` file

```
function MODULE_NAME_views_api($module = NULL, $api = NULL) {
  return array('api' => '3.0');
}

```

add file `MODULE_NAME.views.inc` with contents

```
function MODULE_NAME_views_data() {
  $data = array();

  $data['node']['virtual_views_field'] = array(
    'title' => t('Virtual views field from X Y Z'),
    'help' => t('Virtual views field from X Y Z fields.'),
    'field' => array(
      'handler' => 'MODULE_NAME_virtual_views_field',
    ),
  );
  return $data;
}

```

add file `MODULE_NAME_handlers.inc` with contents

```
class MODULE_NAME_virtual_views_field extends views_handler_field {

  /**
   * Overrides views_handler_field::render().
   */
  function render($values) {
    //uncomment following to see the actual values available
    //need DEVEL module for this
    //dpm($values);

    $X = $values->field_field_X[0]['raw']['value'];
    $Y = $values->field_field_Y[0]['raw']['value'];
    $Z = $values->field_field_Z[0]['raw']['value'];

    //implement your logic here and get result
    $result = $X . " " . $Y . " " . $Z;
    return $result;
  }

  function query() {
    // do not need to override the parent query.
  }
}

```

Your `MODULE_NAME.info` file should look similar to this

```
name = Custom Virtual Views Field
description = takes X Y Z fields to create virtual field
core = 7.x
package = custom
dependencies[] = views
files[] = MODULE_NAME_handlers.inc
core = "7.x"

```

Enable your module (or clean your `class registry` if modifying existing/enabled module) and you should be able to see/add your virtual field called `Virtual views field from X Y Z`

This can be used and has the advantages of any other regular views field.

# Answer
> 2 votes
I think your best option will be to use the views\_customfield module. This lets you define custom fields (including PHP) for a view, without having to have that field elsewhere (e.g. content type).

If you are using Drupal 7 this is now called Views PHP as some of the functionality is in the more recent Views module

---
Tags: 7, views
---


# Question
Title: JS for views embedded in cached blocks broken.. console.log(Drupal); doesn't even have 'views' array
I've been trying to hunt down the cause of this for a while now..

I have `views_embed_view` in various blocks and with block cache enabled, the pagers etc. are broken..

I thought it might be something do with my block template so reverted it to standard (theme: Framework), and my views templates are normal as well. But when I check the Drupal variable in console on a page with the blocks cached, there isn't even a 'views' in the array.

All of the other answers on Drupal seem to talk about mismatched dom IDs but I don't even have that.

Chosen is also missing and its js isn't loaded on the page.

Any ideas welcome.

# Answer
Use #attached https://montanaprogrammer.com/2012/11/19/drupal-block-add-js-css/

```
$block['subject'] = t('Testing block');
$block['content'] = array(
  '#markup' => mymodule_testblock_content(),
  '#attached' => array(
     'css' => array(
      drupal_get_path('module', 'mymodule') . '/css/mymodule.css',
    ),
    'js' => array(
      drupal_get_path('module', 'mymodule') . '/js/mymodule.js',
    ),
  ),
);

```
> 0 votes

---
Tags: views, caching
---


# Question
Title: Generate file path for created file so it can be downloaded
I'm writing a module based on this Jeff Geerling post that will allow the user to use a form to select some data, and then use the Batch API to generate a large .csv file with the desired data and download it from the browser. I have the form and batch processing working fine, but I can't figure out how to determine the path for the created file, as referenced in this code snippet:

```
/**
 * Interim download step for downloading CSV file.
 */
function MYMODULE_download_csv_file_interim($list_id) {
  global $base_url;

  if (empty($_SESSION['csv_download_filename']) || empty($_SESSION['csv_download_file'])) {
    return t('Please visit your list subscribers page to begin a list download.');
  }

  $list = node_load($list_id);

  // Redirect to the download file.
  $redirect = base_path() . 'path/to/download/csv/' . $list_id;
  drupal_add_js('setTimeout(function() { window.location.href = "' . $redirect . '"; }, 2000);', 'inline');

  $download_link = l(t('click here to download the file'), 'path/to/download/csv/' . $list_id);
  $output = '<p>' . t('Your subscriber list is now ready for download. The download should begin automatically. If it does not begin downloading within 5 seconds, please !download_link.', array('!download_link' => $download_link)) . '</p>';
  $output .= '<p>' . l(t("← Back to %list subscribers", array('%list' => $list->title)), 'node/' . $list_id . '/subscribers', array('html' => TRUE)) . '</p>';
  return $output;
}

```

At this point in the code, `$_SESSION['csv_download_file']` is `tmp/my_file.csv`. I've tried to figure how to make this a valid url for downloading the file, but can't. For instance, I've tried using file\_create\_url(), but it just returns the same path.

What do I need to use to make this a valid URL to pass to the browser?

# Answer
`/tmp` is outside of webroot so apache (or whatever) can't serve files from there.

You have 2 options:

1. Move the file from /tmp to your public files directory. This will mean anyone will have access to it (if they know the url). See `file_unmanaged_move()`.

Eg.

```
$source = '/tmp/my_file.csv';
$destination = 'public://csv/my_file.csv';
file_unmanaged_move($source, $destination);

```
2. Stream the file to the browser via php. This means only people who can access your php script can get access to the file.

Eg.

```
header('Content-type: text/csv');
header('Content-disposition: attachment;filename=my_file.csv');
return readfile('/tmp/my_file.csv');

```
> 1 votes

# Answer
The solution to my problem actually came in modifying this line:

```
$redirect = base_path() . 'path/to/download/csv/' . $list_id;

```

to point to another page instead of a file. I actually was already doing what Felix suggested above, and am using `readfile()` in this function:

```
function mymodule_download_csv_file() {
  // For added security, make sure the beginning of the path is the same as that
  // returned by file_directory_temp() (to prevent users from gaining access to
  // arbitrary files on the server).
  if (strpos($_SESSION['csv_download_file'], file_directory_temp()) !== 0) {
    return 'Access denied.';
  }

  // Add HTTP headers for CSV file download.
  drupal_add_http_header('Content-Type', 'text/csv; utf-8');
  drupal_add_http_header('Content-Disposition', 'attachment; filename=' . $_SESSION['csv_download_filename'], TRUE);

  // Allow caching, otherwise IE users can't dl over SSL (see issue #294).
  drupal_add_http_header('Cache-Control', 'max-age=300; must-revalidate');

  // Read the file to the output buffer and exit.
  readfile($_SESSION['csv_download_file']);
  exit;
}

```

So the trick was simply to add a menu item for this function, and then change the line above to point to the defined URL for this function.
> 1 votes

---
Tags: 7, files
---


# Question
Title: How to create a node and populate its fields with info from a completed goal?
I need to create a node and populate its fields with data from a completed Goal (implemented via the Goals module) using Rules. The completed Goal info is fetched using the method from the question about "How to fetch the completed goal as an entity with the Rules module?".

The tokens are available for message display action and also for the node title, but I can't use them for any other fields for some reason. How can I use these tokens to populate the other node fields?

# Answer
To populate some fields of the node to be created using some of the fields of the completed Goal, you need to make those fields (of the Goal) available as row variables in the Views loop of the rule you're using.

Have a look at this improved version of my rule that was included in my answer to your question about "How to fetch the completed goal as an entity with the Rules module?":

```
{ "rules_create_node_with_details_about_completed_goal" : {
    "LABEL" : "Create a node with details about completed goal",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "goals" ],
    "REQUIRES" : [ "rules", "goals" ],
    "ON" : { "goal_awarded" : [] },
    "DO" : [
      { "VIEW LOOP" : {
          "VIEW" : "goals_info_about_completed_goals",
          "DISPLAY" : "views_rules_1",
          "USING" : { "goal_completed_by_uid" : [ "awarded-user:uid" ] },
          "ROW VARIABLES" : {
            "goal_title" : { "goal_title" : "Title" },
            "goal_id" : { "goal_id" : "Goal ID" },
            "goal_userpoints" : { "goal_userpoints" : "User Points" },
            "field_goal_category" : { "field_goal_category" : "Goal Category" },
            "field_goal_level" : { "field_goal_level" : "Goal Level" }
          },
          "DO" : [
            { "entity_fetch" : {
                "USING" : { "type" : "goal", "id" : [ "goal-id" ] },
                "PROVIDE" : { "entity_fetched" : { "goal_completed" : "Completed goal" } }
              }
            },
            { "drupal_message" : { "message" : "Details about completed goal:\u003Cbr \/\u003E\u003Cbr \/\u003E\r\n- Goal ID: [goal-completed:goal-id]\u003Cbr \/\u003E\r\n- Goal Title: [goal-completed:title]\u003Cbr \/\u003E\r\n- Goal Category: [goal-completed:field_goal_category]\u003Cbr \/\u003E\r\n- Goal Level: [goal-completed:field_goal_level]\u003Cbr \/\u003E" } },
            { "entity_create" : {
                "USING" : {
                  "type" : "node",
                  "param_type" : "article",
                  "param_title" : "[goal-completed:title]",
                  "param_author" : [ "awarded-user" ]
                },
                "PROVIDE" : { "entity_created" : { "node_created" : "Created entity" } }
              }
            },
            { "data_set" : {
                "data" : [ "node-created:field-free-format-text" ],
                "value" : "Goal category = [field-goal-category:value] \/ Goal level = [field-goal-level:value]"
              }
            },
            { "data_set" : {
                "data" : [ "node-created:field-free-format-nr" ],
                "value" : [ "goal-userpoints" ]
              }
            },
            { "entity_save" : { "data" : [ "node-created" ], "immediate" : "1" } }
          ]
        }
      }
    ]
  }
}

```

Some more details about the improvements in the above rule:

* Note these additional row variables I added (in the Views loop), i.e.:

+ User Points (goal\_userpoints), one of the fields that come with the Goals module.
    + Goal Category (field\_goal\_category), a custom field I added to my Goals entity (a single value text field, with values such as **`Contribution`**, **`Participation`**, **`Moderation`**, **`Privilege`**).
    + Goal Level (field\_goal\_level), a custom field I added to my Goals entity (a single value text field, with values such as **`Bronze`**, **`Silver`**, **`Gold`**).
* After I added the extra Rules Action "Create a new entity" (to create the new node), I added these extra Rules Actions to set the values of some of the fields for the node to be created (= `node-created`):

+ `node-created:field-free-format-text` (of type text) is assigned the value of `Goal category = [field-goal-category:value] / Goal level = [field-goal-level:value]` (using 2 of the row variables I added in my view).
    + `node-created:field-free-format-nr` (of type integer) is assigned the value of `goal-userpoints` (using 1 of the row variables I added in my view).

With the above in mind, I think the real answer to your question (= "*... I can't use them for any other fields for some reason*") is that you need to pass the values of the fields you want to use as row variables also (and make sure the data types of those fields you pass along in your view are also matching with the node's field in which you want to use them).

BTW, make sure to understand the difference between:

* "Goal completed by user", which is specific to a single user who completed a goal.
* The actual configuration of a "Goal" itself, with fields such as User Points to be granted, or custom fields such as "Level" and "Category", which is identical for all users (and only changes if you change the configuration of a goal).
> 1 votes

---
Tags: rules, 7
---


# Question
Title: OneAll social login not working with modal
I am working in website in drupal 8. I am using oneall Social login module to allow user to log in with social media.

I am showing login page in popup/modal window but oneall social login not showing in popup.

I have searched on drupal.org and check issue for oneall social login but solution did not work.

Can anyone help me out?

Thanks

# Answer
> 0 votes
I have find a solution with help of their support team.

Add between the tag in your template this javascript code. Replace both XXXXXX by your OneAll subdomain :

```
<script type="text/javascript" async="" src="//XXXXXX.api.oneall.com/socialize/library.js"></script>
<script type="text/javascript">(function()

{ var oa=document.createElement('script'); oa.type='text/javascript'; oa.async=true; oa.src='//XXXXXX.api.oneall.com/socialize/library.js'; var os=document.getElementsByTagName('script')[0]; os.parentNode.insertBefore(oa, os); }
)();</script>

```

---
Tags: 8
---


title: One rule for multiple webforms

text:
# Question
Title: One rule for multiple webforms
I've created several webforms. 5 of them contain a field with same machine-name where 2 different rules check the value of the mentioned field. Depending on that value an e-mail is sent. My problem is that both rules run on all webforms, not just on the 5 I only want them to. As the field it tries to check is not present in the other webforms, I get an error message on all other webforms. How can I limit the rule to run on only these 5 of my webforms?

PS: In my rules under "Condition" I execute an PHP code to check the value.

I guess it could be solved with AND or OR but couldn't figure it out.

# Answer
# Typical approach

The previous answer quite often resolves various situations where some variables appear to not be available in Rules Actions, etc. For example, before using a Rules Action like "Set a data value" for your a field, you have to make sure to add a Rules condition `Entity has field` (related to the field for which you want to set a value). And make sure to add that `Entity has field` condition BEFORE other Rules Conditions in which you might want to refer to this field.

That's also what is mentioned in the Rules UI, e.g. when you're adding a "data comparison" condition: somewhere it says "*The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')*".

For a video tutorial that illustrates the importance of this `Entity has field` condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in it.

# Webform requires another approach

However, for this specific question, which is about using Rules in combination with Webform, things are a very little bit more complicated, as further explained below.

Let's assume I have a webform created with some of its fields with machine names like so:

* `contact_us_first_name`.
* `contact_us_last_name`.
* `contact_us_subject`.

After you add these fields (with identical machine names) to any of your own forms, you should be able to import the *prototype*-rule below (using the Rules UI) in your own environment (without running into an integrity constraint):

```
{ "rules_create_a_node_from_a_submitted_webform" : {
    "LABEL" : "Create a node from a submitted webform",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "webform_rules" ],
    "ON" : { "webform_rules_submit" : [] },
    "IF" : [
      { "user_has_role" : { "account" : [ "user" ], "roles" : { "value" : { "2" : "2" } } } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "The webform component submitted by [data:contact_us_first_name-value] (= [data:contact_us_first_name-title]) [data:contact_us_last_name-value] (= [data:contact_us_last_name-title]) contains a field labeled \u0022[data:contact_us_subject-title]\u0022 which has value \u0022[data:contact_us_subject-value]\u0022." } }
    ]
  }
}

```

In the above rule I included an extra Rules Condition to prevent the Rules Action from being executed for anonymous users (feel free to adapt the role id of it, or just remove that Rules Condition). And the rule is triggered via Rules Event "After a webform has been submitted".

The Rules Action only displays an (informational) message on the site (my recommended way of writing and debugging Rules ...) after a webform gets submitted. Here is what I specified (in the Rules UI) as the message to be shown:

> The webform component submitted by \[data:contact\_us\_first\_name-value\] (= \[data:contact\_us\_first\_name-title\]) \[data:contact\_us\_last\_name-value\] (= \[data:contact\_us\_last\_name-title\]) contains a field labeled "\[data:contact\_us\_subject-title\]" which has value "\[data:contact\_us\_subject-value\]".

Here is a sample of the message shown in my own setup:

> ***The webform component submitted by Dries (= First name:) Buytaert (= Last name:) contains a field labeled "Subject:" which has value " Rumour goes that the Rules module for D8 is making progress! ".***

What the above prototype-rule shows is that the "clue" to answer your question is that you have access to all labels and all values of any field of a webform available, ie:

* `[data:MachineFieldName-title]` contains the **Label** of a field with machine name MachineFieldName.
* `[data:MachineFieldName-value]` contains the **Value** of a field with machine name MachineFieldName

All that's left to fully answer your question now is to correct your Rule using similar tokens.
> 1 votes

---
Tags: rules, webforms
---


# Question
Title: entityform view filtered by current user field (term reference)
I have an entityform type that uses a term reference (department). This term reference was also added to user accounts.

I'd like to make a view that displays the form submission for the same department as the currently logged in user.

I can't seem to make it work because if I go with a user view, I'm not able to retrieve all the entityform fields that I need. If I go with an entityform view, I'm not able to retrieve the current user's department. I can make a relationship only with the form submitter and that field is never empty so I don't think I can default to the 'current logged in user'

Any ideas?

# Answer
Since you want to list entities that use the same term reference as the user account, its best to create a view of terms and add relationships to the user and entityform.

Add the entityform fields that you want, using the entityform submission relationship.

Then add the term reference field two times, one with the user relationship and one with the entityform submission relationship. You may hide these fields.

Then add filter 'field comparison', selecting both term reference fields, and choose 'is equal to'. Also add the filter User (using relationship) is 'currently logged in user'

The result is a view showing entityform submissions that have the same term reference value (department) as the currently logged in user.
> 0 votes

---
Tags: views, entities
---


# Question
Title: Filter views by current user taxonomy profile field
**Entity type: Book**

I have entity type called `"Book"`. It has one field called `"book_id"`.

```
Ex: science book(Book_name) -> 100(Bokk_id)
Maths -> 101
english -> 102

```

**User:**

I have `user`, he has one field attached with user profile called `"book_name"`. `"Book_name"` is a taxonomy reference field.

`"Book_name"` has one field called `"book_id"`

`"Book_id"` is free text field, it has more than one value by comma separator. Like `100,101,102`.

```
Ex: user->book_name(taxonomy reference field)->book_id

```

Using views, I want to filter entity type `"book"` by current logged in user `"book_name->book_id"`.

# Answer
Because this is a comma separated text field, your best bet is with custom module that gives your view the ids in a 2+6+36+98 format.

https://drupal.stackexchange.com/a/222876/53677

In that answer, I described how to pass one value from a user field. For you, you'd need to load the taxonomy entity and work with that.

Then, to do multiple, you just need to add a bit of php to split your text field and turn it into the format above with +. You still only pass one argument and in your view, enable multiple values in the contextual filter's settings.

I can't give a longer answer until tomorrow. Btw, if that text field has node ids for books, you should use the entity reference module.
> 0 votes

# Answer
This can be done in views without creating a custom module.

Since you want to list entities that use the same term reference as the user account, its best to create a view of terms and add relationships to the user and book. For the user you need to add an extra relationship since its a level deeper to reach the term reference field.

Add the book fields that you want, using the book relationship.

Then add the term reference field two times, one with the user relationship and one with the book relationship. You may hide these fields.

Then add filter 'field comparison', selecting both similar term reference fields, and choose 'is equal to'. Also add the filter user (with relationship) is 'currently logged in user'.

The result is a view showing books that have the same term reference (book\_id) value as the currently logged in user.
> 0 votes

---
Tags: views
---


# Question
Title: How to render the content in which the user is mentioned in?
I render the Views page on the user profile page to show the content this user created. Now the scenario changed and I have to render the content in which this user has been mentioned using Entity Reference fields. For just one field there is no problem, since I did it using Contextual Filter ... but when I'm trying to do so using multiple different fields (for different content types), then I do not get any results.

Is it possible to achieve this using UI or is it possible to put a custom query somewhere to get results and benefit from the Views fields?

Thank you all in advance!

# Answer
If you think about writing this as a pure SQL query, what you are trying to do is have multiple WHERE conditions that are separated by OR operators.

Using OR operators with Conextual Filters is not possible out-of-the-box with Views. All Contextual Filters are added as AND filters.

There appears to be a module that adds this option, although I have not tested it. It doesn't have an official release, but appears to be in use by over 2000 sites, so might be worth a try: https://www.drupal.org/project/views\_contextual\_filters\_or

Ultimately, however, this could be solved with a different data architecture. Is there a reason you have multiple different fields for referencing the user? Could these fields be combined into one base field, with instances on various content types? If so, then you can do it with a single Contextual Filter.
> 0 votes

# Answer
It can be done using views only, no need for a contextual filter.

Create a user view instead of a content view. Add the relationship content referencing user using the field entity reference field.

Add the content fields that you want, using the relationship for each of them.

Add the filter user = currently logged in user, using the relationship.

The result is all content of all content types, that reference the currently logged in user.
> 0 votes

---
Tags: views, 8
---


# Question
Title: How to create a contextual filter using a current user multivalue field as the default value
How to create a contextual filter using a current user multivalue field as the default value?

The idea is to filter content in a view, based on a value present in a multivalue field that the currently logged in user account has.

I tried using views php in the default contextual filter:

$user\_profile = user\_load($user-\>uid); $statusvalue= $user\_profile-\>field\_status\['und'\]\[0\]\['value'\]; return $statusvalue;

..but that works for a single value and thus does not work in my case.

# Answer
Answering my own question: I accomplished this without using a contextual filter. The view can be based on entities. (Alternative solution is to use a user view, slightly different config)

I added the field two times, of which one uses the relationship to the user.

Then added the fillter 'global: field comparison' and selected both fields.

As a bonus I added a filter, using OR switch, to allow a specific user field value for showing all content.
> 0 votes

# Answer
In your contextual filter go to bottom and in tab "more" check "allow multiple value" checkbox and return value 1+2+3 (OR) or 1,2,3 (AND).
> 0 votes

---
Tags: 7, views
---


# Question
Title: Add a custom link to the contextual menu of every block
I want to add a custom contextual link on the top of every block. there are many answers available on the site but these answers are about adding a contextual link to a specific block. and I need to add a contextual link which appears in the contextual menu of every block available in the site. I have tried this function.

```
function MYMODULE_contextual_links_view_alter(&$element, &$items) {
  if (isset($element['#element']['#block'])) {
    $element['#links']['animation'] = array(
      'title' => 'change animation',
    );
  }
}

```

I didn't get what I want.

# Answer
> 1 votes
The syntax of the link element is wrong.

This is a sample from the documentation of the `Link` render element.

```
$build['examples_link'] = [
  '#title' => $this->t('Examples'),
  '#type' => 'link',
  '#url' => Url::fromRoute('examples.description')
];

```

How do I create a link? has several answers with methods to produce the link.

---
Tags: 8, blocks, navigation
---


# Question
Title: How to deny access to menu items that aren't expected
I want to find a way to make requests to `hook_menu` that I don't expect be denied. For example I have defined a menu like this:

```
$items[$my_url] = array(
  'title' => $my_title,
  'page callback' => 'my_page_callback',
  'access callback' => TRUE,
  'page arguments' => array('hot'),
  'file' => 'includes/my.pages.inc',
  'type' => MENU_NORMAL_ITEM,
);
$items[$my_url . '/hot'] = array(
  'title' => 'hot',
  'page arguments' => array('hot'),
  'type' => MENU_DEFAULT_LOCAL_TASK,
  'access callback' => TRUE,
);
$items[$my_url . '/new'] = array(
  'title' => 'new',
  'page arguments' => array('new'),
  'type' => MENU_LOCAL_TASK,
  'access callback' => TRUE,
);
$items[$my_url . '/rising'] = array(
  'title' => 'rising',
  'page arguments' => array('rising'),
  'type' => MENU_LOCAL_TASK,
  'access callback' => TRUE,
);
$items[$my_url . '/controversial'] = array(
  'title' => 'controversial',
  'page arguments' => array('controversial'),
  'type' => MENU_LOCAL_TASK,
  'access callback' => TRUE,
  'weight' => 10,
);

```

How can I make sure `$my_url/something` doesn't return the `MENU_DEFAULT_LOCAL_TASK` page but instead returns a 403 page or something like that.

# Answer
> 0 votes
The following `MENU_CALLBACK` worked to deny wild card matches for me.

```
$items[$my_url . '/%'] = array(
  'type' => MENU_CALLBACK,
  'page callback' => 'drupal_access_denied',
  'access callback' => TRUE
);

```

---
Tags: hooks, navigation, page-controller
---


# Question
Title: Problem with i18n_string + features + sites with different default language
*(I will talk about i18nviews in this question, but I think the problem applies equally to other cases of i18n\_string)*

## Background

With regular Drupal t(), Drupal will always assume that the original string is in English.

With i18n\_string, it is assumed that the original string is in the site default language.

## Use case / problem

I have multisite with two sites, one with default language German, another with default language English.

I created a page view on the German site, with a page title "Produkte finden".

I exported this view as a feature, and want to enable this feature on the English site. On the English site, the page title should be "Find products".

I thought I can use i18nviews (which uses i18n\_string) to translate the page title configured in the view.

However:

* In the German site, Drupal thinks that the exported page title is in German.
* In the English site, Drupal thinks that the exported page title is in English.

This means that Drupal will never attempt to translate the views page title. So I would get the same, non-localized page title on each site.

## Question

I want to find a way to export a view into a feature that can be installed on sites with different default language, and have localized labels on each site.

If this can be done with i18n\_string, great. If not, I am open for other suggestions.

## Thoughts

I think to make this work, the exported feature would have to contain information about the language with which it was exported, which could then be picked up by i18n\_string (which I assume it is not really capable of atm).

Or all sites would need to have default language = English.

# Answer
My solution:

* Do not enable i18nviews.
* Create all views with English strings.
* Use the core translation system to translate all those strings.
* Optionally, use features\_translations to export translations.

I do not claim that this solution works for all cases where i18n\_string assumed source language causes trouble. But in this case it seems to be sufficient.
> 0 votes

---
Tags: 7, i18n-l10n, features, multi-sites
---


title: Responsive Sticky Headers

text:
# Question
Title: Responsive Sticky Headers
I had previously created a front facing page with a table that has a sticky header using Drupal's built in sticker header js.

Now, we are in the process of making that site responsive. To handle the tables we have set an overflow: scroll on the table container to create a horizontal scrollbar for the table.

However, the sticky header (because it is position fixed) does not scroll.

How can I implement Drupal's sticky header in a responsive site.

Code that generates the table:

```
$block['content'] = theme_table(
  array(
    'header' => $table_headers,
    'rows' => $table_rows,
    'attributes' => array(),
    'caption' => '',
    'empty' => '',
    'colgroups' => array(),
    'sticky' => TRUE,
  )
);

```

# Answer
You may need to attach some additional custom JavaScript to do this. Take a look at the "correct" answer to a similar question.

**EDIT**: I've put together a working version of this page \- which contains a working modification of the tableheader.js to solve the problem of sticky headers not working when scrolling horizontally.

I've created a module with a new theming function that can be used as an alternative to Drupal's `table_theme` to allow for scrolling sticky headers.I also created an example module. It's working great, but may need some tweaking for your case. The modules are not documented (I'll do that later) but you can look at the example. It's self explanatory. It's on GitHub, here.

I hope this is useful.
> 4 votes

# Answer
Please have a look at Responsive Tables module. I think this is what you are looking for.

Some more details about this module (from its project page):

> Adds a library to allow tables to function better in responsive layouts.
>
> You can manually add the library to any table on the site. You also have the option of using the Better Views Tables module to configure the responsive table controls through the Views UI.
> 1 votes

# Answer
make sure you have the corresponding javascript file on the site:

```
drupal_add_js('misc/tableheader.js');

```

actually, theme\_table should will do that, but there are some circumstances you need to do it yourself. (depending on where theme\_table is called)
> 0 votes

# Answer
Please try following code in your custom theme javascript.

```
(function ($, Drupal) {
    /*global jQuery:false */
    /*global Drupal:false */
    "use strict";
    /**
     * Fix tableheader.js Sticky Table headers overflow-x:scroll issue.
     */
    Drupal.behaviors.tableheader = {
        attach: function (context) {
            var $table = $(".table-responsive");
            if ($table.length == 0) {
                console.log($table.length);
                $table = $("html");
            }
            var $header = $(".sticky-header");
            var $header_left = parseInt($header.css('left'));
            $table.on("scroll", function (e) {
                $header.css('left', $header_left-$table.scrollLeft());
            });
            $(window).on("scroll", function (e) {
                $header.css('left', $header_left-$table.scrollLeft());
            });
        }
    };
})(jQuery, Drupal);

```
> 0 votes

---
Tags: 7
---


# Question
Title: How To Alter Web Form Elements Permanently?
Webform elements can be altered using the function `MYMODULE_form_alter`. However the changes are not permanent. For example, if you're changing the title of an element from `'#title' => t('Old Title') to '#title' => t('New Title')` ,the change will not affect source - the (View) Source page will still show `'#title' => t('Old Title')`
So my question is: Is it possible to alter the source (YAML) from code because that will make changes permanent.I have tried to locate **weformX.yml** for **webformX** inorder to alter it in code but I can not find.

# Answer
You can alter the yaml source of a webform by loading the config entity and modify `elements`:

```
use Drupal\webform\Entity\Webform;
use Drupal\Core\Serialization\Yaml;

  $webform = Webform::load('contact');
  $elements = Yaml::decode($webform->get('elements'));
  $elements['name']['#title'] = 'Please fill in your name';
  $webform->set('elements', Yaml::encode($elements));
  $webform->save();

```
> 1 votes

---
Tags: webforms, 8, entities
---


# Question
Title: How to show webform results only on pages, where from they has been submitted?
I have a website with products. By using fivestar and webform fivestar modules i created a simple solution that allows users to add opinion about products.

The 'add opinion' functionality shows on every page with product, but I want also show opinions (webform results) about products only on pages they were submited from.

**More detailed description how I was trying to do that:**

I created a simple webform with 3 fields: comment, fivestar and hidden page URl- which keeps url of the page where comment has been submitted from. I transformed the webform into block and add the block to page content.

That makes users to add product rating but they didn't see previous ratings.

**To display previous results:** I created view with block option and added the block to content.

All works ok, except that on every product page every comment is visible. I want to make a filter to limit already existing comments to the comments that concern only this product. My idea was to compare url's in PHP, that's why in form I created a field which keeps the URL of source of content :\[current-page:url\]

In view I add a PHP field like this:

Then in filters I made check to eliminate redundant comments: Filter comment:

And it's not working, I even created additional php field to check all variables and the results are ok:

results: http://plmyhp.platform-preprod.vetoquinol.com/produkty/zdrowie/dermanorm

But it's not working :( I don't have access to files via ftp or any other all I can do is to use admin panel functions.

I need help, maybe there is other way than using php and comparing website URL's ?

# Answer
> 0 votes
First of all, using Views PHP is considered bad practice. Read: **What are the downsides of using PHP Filter code in blocks, nodes, views-args, etc?**

Second, I don't like that you're using `$_SERVER{HTTP_HOST]` because if you were to have a development environment, the host name will change; therefore, your functionality will break. Also, if they were to add a subdomain or change the domain name, this will also break your functionality. In summary, any change in the URL will cause critical failure to your functionality.

## The better approach (Use NID's)

Instead of using the URL, a better approach would be to link the webform and the product display node by creating a reference of NID (Node ID). This basically does what you're currently doing, but uses the NID instead of URL.

1. Install Webform References module
2. Install Token module, which will allow you to use tokens.
3. Add a Node Reference field to your webform.
4. Create a custom module

/webform\_nid\_reference/**webform\_nid\_reference.info**

```
name = Webform NID reference
description = Grabs the current Node ID and puts it the reference field.
package = Webform
version = 7.x-1.0
core = 7.x
dependencies[] = webform
dependencies[] = webform_references

```

/webform\_nid\_reference/**webform\_nid\_reference.module**

```
/*
 * Implementation of hook_form_alter()
 */

function webform_nid_reference_form_alter(&$form, &$form_state, $form_id) {

   if ($form_id == 'webform_client_form_475') {

       $form['#validate'][] = 'webform_nid_reference_validate';

   }

}

function webform_nid_reference_validate($form, &$form_state) {

   if ($node = menu_get_object()) {
    // Get the nid
    $current_nid = $node->nid;
    // Set webform field value
    $form_state['values']['submitted']['node_ref_autocomplete'] = $current_nid;

   }

}

```
6. Enable custom module
7. In Views remove all of your views php stuff. Under advanced (far right) add a Contextual Filter of your webforms reference field (the field you created in step 3)

* **When filter value is not in the URL**, Select `provide default value` and select `Content ID from ULR`

Your view will go blank, because the View Edit Page URL does not have a contextual filter. When you go visit a node, the view should show up then.

---
Tags: views, webforms, rating
---


title: Block error on CMI

text:
# Question
Title: Block error on CMI
I have two identical sites on Drupal 8 (A and B), on (A) I created a custom block(block/add), and then I export the configuration(drush config-export) and import this config on (B) (drush config-import), no error, but on the site (B) the block that I imported said on any region that I put "This block is broken or missing. You may be missing content or you might need to enable the original module." And I cant edit the content of this block. How I can fix that?

Site A:

Site B:

# Answer
> 3 votes
A custom block is made of two entities, one for the placement and the actual content. Only the actual placement can be exported with cmi. The content can not. You can either send your content via REST or you can manually edit the uuid of another block to match. In the future you'll be able to use Entity Pilot (entitypilot.com) - disclaimer - this is my product.

# Answer
> 3 votes
For anyone looking for a quick and dirty way to export all custom block data from site A and import it into site B (**IMPORTANT:** This will overwrite any custom block content on site B):

**On site A:**

Make a directory to put migration data in:

`mkdir block_migration`

Export block specific tables to individual files:

`mysqldump -u mysql_username -p database_name block_content > block_migration/block_content.sql`

`mysqldump -u mysql_username -p database_name block_content__body > block_migration/block_content__body.sql`

`mysqldump -u mysql_username -p database_name block_content_field_data > block_migration/block_content_field_data.sql`

`mysqldump -u mysql_username -p database_name block_content_field_revision > block_migration/block_content_field_revision.sql`

`mysqldump -u mysql_username -p database_name block_content_revision > block_migration/block_content_revision.sql`

`mysqldump -u mysql_username -p database_name block_content_revision__body > block_migration/block_content_revision__body.sql`

Transfer these new sql files to Site B via git or other method. If you're doing this often, you could even get fancy and put the above mysqldump commands into a pre-commit hook.

**On Site B:**

Assuming you've pulled in the code that contains the table drop/create logic we exported above, import the tables into your database:

`mysql -u mysql_username -p database_name < block_migration/block_content.sql`

`mysql -u mysql_username -p database_name < block_migration/block_content__body.sql`

`mysql -u mysql_username -p database_name < block_migration/block_content_field_data.sql`

`mysql -u mysql_username -p database_name < block_migration/block_content_field_revision.sql`

`mysql -u mysql_username -p database_name < block_migration/block_content_revision.sql`

`mysql -u mysql_username -p database_name < block_migration/block_content_revision__body.sql`

Clearing your caches is always a good idea. If you're using drush:

`drush cr`

# Answer
> 0 votes
Thanks to everyone that posted here; we were really confused about this issue (blocks, block configuration, and the CMI).

Using the information here as a starting point, I created the following script (you can run it with drush php-script from your Drupal root) which will fix the UUIDs in the database. This assumes that the blocks you want to use are already there however (which isn't a problem for us since our blocks come over from a Drupal 6 migration). The script also assumes that the 'info' value for each block, a.k.a. its 'label' is unique, so your mileage may vary.

We will need to figure out a way to script the creation of new blocks as well so that any configuration exported from our development environment can be used in our production environment as well, but that is another story.

```
<?php
  use Drupal\Component\Serialization\Yaml;

  // we need to parse all uuids from deploy dir and override local uuids
  $dir = \Drupal::root() . '/' . config_get_config_directory('sync') . '/';
  $files = scandir($dir);

  \Drupal\Core\Database\Database::setActiveConnection();
  $connection = \Drupal\Core\Database\Database::getConnection();

  $logger = \Drupal::logger('code_driven_devel');

  // Gather all 'block_content' blocks; store the label and uuid
  $labelled_blocks_to_uuids = array();
  $labels = array();
  foreach($files as $file) {
    $ext = substr($file, -4);
    if ($ext == '.yml') {
      $info = Yaml::decode(file_get_contents($dir . $file));
      $name = substr($file, 0, -4);
      $isblock = substr($name, 0, 5);
      if($isblock == 'block') {
        if(is_array($info) && array_key_exists('settings', $info)) {
          $id = $info['settings']['id'];
          $id_parts = explode(':', $id);
          if ($id_parts[0] == 'block_content') {
            $uuid = $id_parts[1];
            $label = $info['settings']['label'];
            if (strlen($label) > 0) {
              $labelled_blocks_to_uuids[$label] = $uuid;
              array_push($labels, $label);
            }
          }
        }
      }
    }
  }
  $logger->notice(t("Found " . count($labels) . " block_content config YML that may need to have their UUIDs synched..."));
  $results = $connection->select('block_content_field_data', 't')
    ->fields('t')
    ->condition('info', $labels, 'IN')
    ->execute();
  if ($results) {
    foreach ($results as $record) {
      $logger->notice(t("Updating UUID for block_content with id = " . $record->id . "..."));
      $uuid = $labelled_blocks_to_uuids[$record->info];
      $connection->update('block_content')
        ->fields(array(
            'uuid' => $uuid,
            ))
        ->condition('id', $record->id, '=')
        ->execute();
      $logger->notice(t("UUID for block_content with id = " . $record->id . " updated to " . $uuid));
    }
  }

```

# Answer
> 0 votes
Another approach for keeping content that is added as part of development also pushed to test and live environments is to use the Default Content module to export the content. It is built for the content to be exported to an installation profile's 'content' folder, and then the module, if enabled, automatically brings the content in when the site is installed, but it's also possible to import the content one item at a time, such as in an update hook, with the below code in your example.install or example.profile:

```
<?php
/**
* Import a piece of content exported by default content module.
*/
function example_import_default_content($path_to_content_json) {
  list($entity_type_id, $filename) = explode('/', $path_to_content_json);
  $p = drupal_get_path('profile', 'guts');
  $encoded_content = file_get_contents($p . '/content/' . $path_to_content_json);
  $serializer = \Drupal::service('serializer');
  $content = $serializer->decode($encoded_content, 'hal_json');
  global $base_url;
  $url = $base_url . base_path();
  $content['_links']['type']['href'] = str_replace('http://drupal.org/', $url, $content['_links']['type']['href']);
  $contents = $serializer->encode($content, 'hal_json');
  $class = 'Drupal\\' . $entity_type_id . '\Entity\\' . str_replace(' ', '', ucwords(str_replace('_', ' ', $entity_type_id)));
  $entity = $serializer->deserialize($contents, $class, 'hal_json', array('request_method' => 'POST'));
  $entity->enforceIsNew(TRUE);
  $entity->save();
}

```

Export a custom block with an ID of 8:

```
drush dcer block_content 8

```

(If you don't set your profile path in Drush settings you'll have to specify it above.)

And use the resultant export in your example.install file like this:

```
<?php
/**
* Add the footer block content.
*
* Implements hook_update_N().
*/
function example_update_8001() {
  example_import_default_content('block_content/136efd63-021e-42ea-8202-8b97305cc07f.json');
}

```

See easily add default content with update hooks for more.

# Answer
> 0 votes
I have just publish a contributed module that solves this. Essentially, the module provides a type of block based on configuration (the fixed block) that wraps a custom block (the content block). The fixed block is stored in the website configuration along as the default content. In your scenario, the custom block is created automatically in the site B with the default content as soon as needed.

Everything is done through UI, no special files or custom module are needed. I named it "Fixed block content" and it is published at:

https://www.drupal.org/project/fixed\_block\_content

---
Tags: 8, blocks, importing-exporting, configuration
---


title: Alter existing routes doesn't work

text:
# Question
Title: Alter existing routes doesn't work
I'm working on a D8 project trying to add custom access rules to some pages.

I want to restrict access to specific users based on their id.

I checked this and seems easy but I can't make it work!

I want to change the access for the route

> entity.webform\_submission.canonical /admin/structure/webform/manage/{webform}/submission/{webform\_submission}

But as I didn't manage to make it work I tried an easier example

> contact.site\_page
> /contact

(Which also doesn't work)

So I created my routing file under my\_module/src/Routing folder :

```
namespace Drupal\my_module\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    if ($route_item = $collection->get('contact.site_page')) {
      $requirements = $route_item->getRequirements();
      unset($requirements['_permission']);
      $route_item->setRequirement('_access', 'FALSE');
    }
  }
}

```

After that I added the service file in my\_module's root folder:

```
services:
  my_module.route_subscriber:
    class: Drupal\my_module\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

```

But I don't get Access denied when I visit those pages.

Also, is there any way to test it by using dsm or var\_dump?

Any idea/help/suggestion?

# Answer
you need to enable kint() to get the routs but you need to make sure the permissions for using kint() is correct. and you can add your debugging into alterRouts()
> 0 votes

---
Tags: 8, users
---


# Question
Title: How to determine if a translatable field has translation enabled?
How can I figure out if a translation for a translatable field has been enabled?

I don't mean if a field is translatable in general. e.g.:

```
$entity_type = $entity->getEntityTypeId();
$bundle = $entity->bundle();
$fields = $this->entityFieldManager->getFieldDefinitions($entity_type, $bundle);
foreach($fields as $field){
  if($field->isTranslatable()){
    // Do something.
  }
}

```

Could the langcode be a reliable information? If it is 'und' e.g.:

```
if($entity->get('name')->getLangcode() != 'und'){
  // The field translation is enabled:
}

```

# Answer
To check if the translation is enabled on a field:

```
if ($entity->get('name')->getFieldDefinition()->isTranslatable()) {
  // The field translation is enabled:
}

```

which is by the way the same field definition you get in your code example, only here it is retrieved from the field directly. There is no difference between *translatable* and *translation enabled* as long as the entity is translatable.
> 2 votes

---
Tags: 8, entities, i18n-l10n
---


# Question
Title: How to set paths where to load administration theme?
E.g. administration themes are used only on paths that start with `/admin/`, what if I want to use administration theme on paths like `/user/`, `/users/*` or `user/login`?

There is a module for that where you can set paths where to load your admin theme https://www.drupal.org/project/admin\_theme, but my question is for Drupal 8.

# Answer
> 1 votes
You need a route subscriber, where you search for routes, which have a path you want to load with the admin theme, and add the option:

```
$route->setOption('_admin_route', TRUE);

```

More info Altering existing routes and adding new routes based on dynamic ones.

**Example**

There is an example in core. You can configure the admin theme for the node edit form in UI and this route subscriber is applying this configuration:

```
namespace Drupal\node\EventSubscriber;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Sets the _admin_route for specific node-related routes.
 */
class NodeAdminRouteSubscriber extends RouteSubscriberBase {

  /**
   * The config factory.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $configFactory;

  /**
   * Constructs a new NodeAdminRouteSubscriber.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The config factory.
   */
  public function __construct(ConfigFactoryInterface $config_factory) {
    $this->configFactory = $config_factory;
  }

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    if ($this->configFactory->get('node.settings')->get('use_admin_theme')) {
      foreach ($collection->all() as $route) {
        if ($route->hasOption('_node_operation_route')) {
          $route->setOption('_admin_route', TRUE);
        }
      }
    }
  }

}

```

---
Tags: theming, 8
---


# Question
Title: Commerce Order email with an "Unknown" payment method (Drupal 7)
I placed the order programatically. Everything seems to work fine, even the "**payment method**" on the order page is show up correctly. However the order email I received, the payment method is **unknown**. It suppose to show "**Add to account**"

I don't know why, I thought that could be the email rules is executed before the token is available with the payment method name to use. On Drupal commerce email configuration, it's set to use the token **\[commerce-order:payment-method-short-title\]**

```
$payment_method = commerce_payment_method_instance_load('bank_transfer|commerce_payment_bank_transfer');

 $charge = $order->commerce_order_total['und'][0];

$transaction = commerce_payment_transaction_new('bank_transfer', $order->order_id);
$transaction->instance_id = $payment_method['instance_id'];
$transaction->amount = $charge['amount'];
$transaction->currency_code = $charge['currency_code'];
$transaction->status = COMMERCE_PAYMENT_STATUS_SUCCESS;
$transaction->message = 'Name: @name';
$transaction->message_variables = array('@name' => 'Add to Account');

commerce_payment_transaction_save($transaction);
commerce_payment_commerce_payment_transaction_insert($transaction);
commerce_checkout_complete($order);
commerce_order_save($order);

```

# Answer
> 0 votes
I now found the solution, I need to add the payment method to the order object, so the token system can pick it up and use in the order email.

Before save the order, we need to add the payment method.

```
$order->data['payment_method'] = 'bank_transfer|commerce_payment_bank_transfer';
commerce_order_save($order);

```

It can be placed before the transaction section.

---
Tags: 7, commerce
---


title: How to reset the display of nodes?

text:
# Question
Title: How to reset the display of nodes?
For some reason I can no longer manage the display of a node in the backend. Managing the form display works but not the frontend display managing. I get the following error message:

> Fatal error: Maximum execution time of 50 seconds exceeded in /customers/2/f/2/igghq.com/httpd.www/core/modules/field\_ui/src/Element/FieldUiTable.php on line 100

I can still manage the display of other content types. Just not that specific one. Is there a way to reset the manage display backend form, maybee through the database?

* running display suite
* Drupal 8

More info: it only locks-up when loading the default display mode. Teaser still works

# Answer
I've uninstalled and installed fieldgroups and that fixed it. I could access the default display of the content type again. Now I have to redo all my tabs but hey. I now know what killed it. I'll report back if i can find official confirmation of this issue.
> 0 votes

# Answer
Wanted to post my solution(i encounter it too) if anyone stumble upon.

You don't have to uninstall and reinstall fieldgroup if you know which content type is causing this issue.

* Go to Configuration Export ( \[your URL\]/admin/config/development/configuration/single/export)
* Choose *Entity View Display* in **Configuration type**
* Look for your content type in **Configuration Name**
* Copy the configuration that appeared in **Here is your configuration:**
* Open a text file and paste your config.
* Look for *field\_group:* , delete it together with it's child or until *id*
* Then re-import your config.

That works for me without resetting other content type field groups.
> 1 votes

# Answer
You will have to edit your `php.ini` for this. Open it and locate the `max_execution_time` setting. In your case, it will be set to `50`. Update the setting to `300` for example (300 seconds = 5 minutes), save the file and restart Apache.
> 0 votes

# Answer
Another place you can update is settings.php file.

Simply try this `-> edit sites/default/settings.php` and added the following line:

```
ini_set('max_execution_time', 0);

```
> 0 votes

# Answer
Do you have Page Manager enabled?

If you're using D7, Page Manger comes with C-tools module.

If you're using D8, you need to download it.

So enable the Page Manager module, and you should be able to manage them all from here.
> 0 votes

---
Tags: 8, display-suite
---


title: Override user registration form

text:
# Question
Title: Override user registration form
I'm looking for a OOP way to have a simplified User registration form in Drupal 8.

As of today, the default User registration form is declared directly as an annotation in the User class. From the administration pages, it is possible to add a **Register** form display for the user form. However, when removing all possible fields save for the password/login, there is still a bunch of fields showing up that I want removed:

* Username
* Password confirmation
* Locales settings
* Contact settings
* etc.

What I want is an extremely simple registration form, with just two fields: **e-mail address** and **password**. All other fields will be editable later. I want this form to use OOP if possible, so extending the class **Drupal\user\RegisterForm** seems to me a good way to achieve this...

I extended the form but can't use it. It requires an entity to be passed to it apparently, but I don't know how to do that.

The ideal way to do it would be:

```
$entity = \Drupal::entityTypeManager()
  ->getStorage('user')
  ->create([])
;
$formObject = \Drupal::entityTypeManager()
  ->getFormObject('user', 'register')
  ->setEntity($entity)
;
$registerForm = \Drupal::formBuilder()->getForm($formObject);

```

However this will insist on fetching the original, non-inherited **RegisterForm** class, not my custom one. How can I tell Drupal to instanciate my own form instead?

BTW how can I make **username** optional?

I've seen a few solutions out there for redefining the user registration form, however most of them are Drupal 7 solutions and none of them are OOP.

# Answer
If you want to use the extended register form class, you need to put it in the place of the original form class in the user entity type:

*mymodule.module*

```
  /**
   * Implements hook_entity_type_alter().
   */
  function mymodule_entity_type_alter(array &$entity_types) {
    $entity_types['user']->setFormClass('register', 'Drupal\mymodule\MyRegisterForm');
  }

```
> 6 votes

# Answer
You have to create a custom module and add a service:

@file: *my\_module.services.yml*

```
  services:
    route_subscriber:
      class: Drupal\my_module\Routing\RouteSubscriber
      tags:
        - {name: event_subscriber }

```

@file: *src/Routing/RouteSubscriber.php*

```
  /**
   * @file
   * Contains \Drupal\my_module\Routing\RouteSubscriber.
   */

  namespace Drupal\my_module\Routing;

  use Drupal\Core\Routing\RouteSubscriberBase;
  use Symfony\Component\Routing\RouteCollection;

  /**
   * Listens to the dynamic route events.
   */
  class RouteSubscriber extends RouteSubscriberBase {

    /**
     * {@inheritdoc}
     */
    protected function alterRoutes(RouteCollection $collection) {
      // login form
      if ($route = $collection->get('user.login')) {
        $route->setDefault('_form', '\Drupal\my_module\Form\NewUserLoginForm');
      }
      // register form
      if ($route = $collection->get('user.register')) {
        $route->setDefault('_form', '\Drupal\my_module\Form\NewUserRegisterForm');
      }

    }
  }

```

and a custom form class:

@file: *src/Form/NewUserRegisterForm.php*

```
  /**
   * @file
   * Contains \Drupal\my_module\Form\NewUserRegisterForm.
   *
   * credits to: https://gist.github.com/davidDuymelinck/cd20ab7049749358717127f12666b68c
   */

  namespace Drupal\my_module\Form;

  use Drupal\Component\Datetime\TimeInterface;
  use Drupal\Core\Entity\EntityFormBuilderInterface;
  use Drupal\Core\Entity\EntityManagerInterface;
  use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
  use Drupal\Core\Extension\ModuleHandlerInterface;
  use Drupal\Core\Form\FormStateInterface;
  use Drupal\Core\Language\LanguageManagerInterface;
  use Drupal\user\Entity\User;
  use Drupal\user\RegisterForm;
  use Symfony\Component\DependencyInjection\ContainerInterface;

  /**
   * Provides a user register form.
   */
  class NewUserRegisterForm extends RegisterForm {
      public function __construct(EntityManagerInterface $entity_manager, LanguageManagerInterface $language_manager, EntityTypeBundleInfoInterface $entity_type_bundle_info = NULL, TimeInterface $time = NULL, ModuleHandlerInterface $moduleHandler) {
          $this->setEntity(new User([], 'user'));
          $this->setModuleHandler($moduleHandler);
          parent::__construct($entity_manager, $language_manager, $entity_type_bundle_info, $time);
      }
      /**
       * @inheritdoc
       */
      public static function create(ContainerInterface $container) {
          return new static(
              $container->get('entity.manager'),
              $container->get('language_manager'),
              $container->get('entity_type.bundle.info'),
              $container->get('datetime.time'),
              $container->get('module_handler')
          );
      }
      public function form(array $form, FormStateInterface $form_state) {
          $form = parent::form($form, $form_state);
          $form['test'] = [
              '#markup' => '<p>Test extended form</p>',
          ];

          return $form;
      }
  }

```

**NB:** I did not find how to alter/modify the submit button because `$form` has no *actions* key.
> 4 votes

# Answer
I would use the REST resources for creating users instead of hooking into Drupal classes. It is much easier and your frontend guys can completely control the registration experience.

1. Enable REST and REST UI
2. Enable /user/register REST route
3. Edit permissions for this route adding "anonymous access"
4. Now you send JSON objects to /user/register via ajax
5. Example:

```
$.ajax({
    url: Drupal.url('user/register?_format=json'),
    type: 'POST',
    dataType: 'json',
    data: JSON.stringify(userForm),
    headers: {
        'X-CSRF-Token': csrfToken,
        'Content-type': 'application/json'
    },
}).done(function(response) {
  console.log('done')
  console.log(response)
}).fail(function(jqXHR, textStatus) {
  console.log( JSON.parse(jqXHR.responseText))
});

```
6. Now your registration form HTML is completely customizable.
> 2 votes

---
Tags: 8, forms, users
---


# Question
Title: Access / Alter user registration form submit button in $form variable
In drupal 8, I have created a custom module to alter the user login and register forms in 2 class that extends `UserLoginForm` and `RegisterForm` respectively.

Whereas for the login form I can add some link in the `$form['action']` array or add a class to the submit button:

```
 $form['actions']['submit']['#attributes'] = [
    'class' => ['btn', 'btn-primary'],
 ];

```

a contrario, there is no *action* array in user register `$form` variable(!)

So how can I access in my class the submit button, and more generally, the *action* array?

# Answer
> 1 votes
While `UserLoginForm` is a regular form based on form api, `RegisterForm` is an entity form, where the actions are defined in a separate method EntityForm::actions(), which is overridden in `RegisterForm`:

```
  protected function actions(array $form, FormStateInterface $form_state) {
    $element = parent::actions($form, $form_state);
    $element['submit']['#value'] = $this->t('Create new account');
    return $element;
  }

```

which you can override again in your extended class.

---
Tags: 8, forms, users
---


title: Search_api not searching taxonomy names

text:
# Question
Title: Search_api not searching taxonomy names
I feel like I have tried messing with every setting I can find but I simple cannot make my search\_api search view return any results based on taxonomy names.

I want to be able to search based on a custom taxonomy and search on the fulltext field of the name.

* I am using the built in database.
* I have added the taxonomy term database sources.
* I have added a relationship for the taxonomy term on my custom views
* In the fulltext search on the view the taxonomy name field is selected to be searched
* In the index I have added the custom taxonomy I want included.
* I have set it to fulltext and boosted in to 5.0

What else am I suppose to do?

Does anyone know of any guide or any information that explains how to make this work? It has been a month I still cannot get this module to return content that has associated taxonomy terms.

Is there any modules that do this? It should be a standard use case...

# Answer
> 0 votes
I went through the same case, reinstall the search and entity modules. And try to install search\_api using Database Search Default module and after installation, uninstall the database search Default module. Boost taxonomy name to 8 or 13. Then it should work.

---
Tags: views, 8, search
---


# Question
Title: In which file is the username/password located?
I did a standard installation of drupal 8 varbase and added this into Aqucia Dev Desktop 2.

Where can I find the username/password which is used for the database access from Drupal for the database? I looked into the settings.php but could not find any of this.

To be more specific. Below is the COMPLETE settings.php file without all the comments.

```
$databases = array();
$config_directories = array();
$settings['hash_salt'] = '';
$settings['update_free_access'] = FALSE;
$settings['container_yamls'][] = $app_root . '/' . $site_path . '/services.yml';

$settings['file_scan_ignore_directories'] = [
  'node_modules',
  'bower_components',
];

$settings['entity_update_batch_size'] = 50;

// <DDSETTINGS>
// Please don't edit anything between <DDSETTINGS> tags.
// This section is autogenerated by Acquia Dev Desktop.
if (isset($_SERVER['DEVDESKTOP_DRUPAL_SETTINGS_DIR']) && file_exists($_SERVER['DEVDESKTOP_DRUPAL_SETTINGS_DIR'] . '/loc_inzicht_dd.inc')) {
  require $_SERVER['DEVDESKTOP_DRUPAL_SETTINGS_DIR'] . '/loc_inzicht_dd.inc';
}
// </DDSETTINGS>
$settings['install_profile'] = 'varbase';

```

As the site name is named "Inzicht" I expect to find an option in devdesktop but could not find it.

\[SOLVED\] I did a long scan over the complete HDD and found the connection string in C:\Users\\.acquia\DevDesktop\DrupalSettings

# Answer
They are not stored in a file, they're both stored in the `users_field_data` database table. The password is stored as a salted hash, you won't be able to reverse engineer it.

Varbase does make some changes in its install profile; it sets the default username to "webmaster" instead of "admin", and locks that field so it can't be altered.

So your username is "webmaster", and your password is whatever you set it as during the installation process.
> 2 votes

---
Tags: database, configuration
---


title: prevent redirect after form submit?

text:
# Question
Title: prevent redirect after form submit?
I'm using drupal's form API as part of a block in my module.

When the form is submitted, I want to change the content of the block to something else, let's say "Thanks". I do **not** want the page to redirect, as is default behaviour.

(Admittedly the default behaviour has the benefit of removing the POSTed page from the browser History, so you don't get questioned on hitting Back.)

If not clear, please let me know and I'll post a code sample.

# Answer
Set `$form_state['redirect'] = false` in the submit handler.
> 8 votes

# Answer
For Drupal 8 use this instead: $form\_state-\>disableRedirect();
> 2 votes

---
Tags: 7, forms
---


# Question
Title: File (Field) Paths upload/remove not recognized
This behavior started after upgrading our Drupal 7.43 system to 7.56. In the process we also upgraded the Views module to 7.x-3.18 and the File (Field) Path module is at 7.x-1.0.

In the content type field management the File field configuration is using this setting for File Name:

```
[file:ffp-name-only-original].[file:ffp-extension-original]

```

As an example the file name sellsheet.pdf is displayed on the content page.

In the files/pdf directory the files and revisions are:

> sellsheet.pdf
> sellsheet\_0.pdf
> sellsheet\_1.pdf
> sellsheet\_3.pdf
> sellsheet\_4.pdf
> sellsheet\_5.pdf

This file is attached to a view using Rewrite results code of:

```
<a href="[field_sell_sheet]">Sell Sheet</a>

```

Which generates a link to sellsheet\_5.pdf

When I delete this content on the content page I would expect the link on the view to disappear. It does not, it changes the link to the file sellsheet\_2.pdf which did not exist before but does now because when looking the directory the files are:

> sellsheet.pdf
> sellsheet\_0.pdf
> sellsheet\_1.pdf
> sellsheet\_2.pdf
> sellsheet\_3.pdf
> sellsheet\_4.pdf

This because sellsheet\_5.pdf has been renamed to sellsheet\_2.pdf.

So the view still provides a link even though it should not.

When I upload a new file in the content edit page the directory of files becomes:

> sellsheet.pdf
> sellsheet\_0.pdf
> sellsheet\_1.pdf
> sellsheet\_3.pdf
> sellsheet\_4.pdf
> sellsheet\_5.pdf
> sellsheet\_6.pdf

The new file was uploaded and named sellsheet\_5.pdf and sellsheet\_2.pdf was renamed to sellsheet\_6.pdf.

So when you click on the link on the content editing page it opens sellsheet\_5.pdf, but the view link goes to sellsheet\_6.pdf.

I'm not sure what is going on but suspect it may have something to do with Drupal not being able to update the database.

There are no errors in watchdog, Apache or MySQL logs.

Has/is anyone else experienced this? I'm assuming it's a File (Field) Path issue.

# Answer
I have finally discovered the issue. Even though the node shows a status of published there is actually a draft. Up until the upgrade users were able to publish the content they created using Workbench Moderation. Now after saving an edit to the node the status never changes to draft and will not allow the user to publish the content. The only way the content can be published is by an administrator setting the Moderation status at the bottom of the page and then saving the record.

I have not been able to find a way to correct this issue yet. I will post a separate question that has a clearer description of the issue now that I have one.
> 0 votes

---
Tags: views, files
---


title: How to make a whole block clickable?

text:
# Question
Title: How to make a whole block clickable?
I'm trying to make a little block that links to the logged-in user's profile. I've already created a view block with the necessary information, but I don't know how to make it clickable and link it to the user's profile.

How can I achieve this?

---

**Edit:** One can find some more details about the code that fixed this problem at https://stackoverflow.com/questions/23552893/how-to-create-a-clickable-block.

# Answer
Here's a possible solution. In your view, exclude all fields add field 'Global: Custom text'. You may also have to add fields to generate the appropriate path to the user profile.

Then, add the token replacement patterns for the excluded fields. You can either 1) wrap this output in an anchor with the appropriate path /user/\[uid\] (a field you may have to add, or you may be able to use the user's alias), or 2) in the rewrite section, tick 'Output this field as a link' and specify the path there (also use replacement patterns from UID or the alias).
> 0 votes

# Answer
If you can't edit the output html and don't want to make a custom template, you could do this with CSS by positioning the link div over the block and expanding it to 100% width & height. Apply it to both the container div and the a. Resize the a text & make transparent to so it should still work with screen-readers, ie:

```
.block-name .field--type-link,
.block-name .field--type-link a {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
color: transparent;
font-size: 1px;
}
<div class="block-name">
  <h3>title</h3>
  <div class="field--type-content"><p>Content</p></div>
  <div class="field--type-link"><a href="#">Link</a></div>
</div>

```
> 1 votes

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


# Question
Title: How can I upload bulk images as separate nodes in drupal 8?
I have a folder of images I am trying to bulk upload. As they will be used in galleries that can be filtered by year and location I was hoping to make them individual nodes with year and location fields that the bulk upload would fill in with a preset on each upload batch.

I've played with the media entity module and managed to upload a group of images as a single media entity but I don't really want the files grouped.

Is there a way to do this in D8 yet? I'm fairly new to D8 so am not too sure of how things work yet.

# Answer
DropZoneJS can auto-create media entities for every uploaded image.

Remember that you need to set up an entity browser using the DropZoneJS-Widget for the bulk-upload feature.

Your image gallery is an entity reference field to media entities (unlimited cardinality).

If you are looking for a general tutorial on how to set up media entities, I found this tutorial quite helpful.
> 1 votes

---
Tags: 8, nodes, media
---