# Question
Title: How do I Group Repeatable Fields Programatically?
I'm in the middle of coding a custom entity in Drupal 8. Currently, I'm defining fields using the baseFieldDefinitions method. I've run into a small problem now where I have a subset of fields that need to be grouped together and repeatable. For example, I have a checkbox, a text box, and a select box that all need to be associated while allowing someone to click an "Add" button to produce another set of those three fields.

It seems that if I was using the UI to create a custom content type, then I could use Paragraphs to handle this, but I wasn't able to figure out how to do that in code, and all the modules that are used in Drupal 7 as example of how to do this either don't exist in D8, or point to using Paragraphs instead.

Some ideas that I had:

1. Create all three as repeatable fields in baseFieldDefinitions and override the form to present them as a unit and write some ajax to make it work the way I want. I don't think this is ideal because it seems like I'm fighting the framework.
2. Make this group of fields into their own entity and try to figure out how to add an entity creation form inside my parent entity creation form. I'm not sure if this is possible, but it seems like it should be.
3. Use hook\_schema to create a database table with the three fields that I need and an additional column to tie that record to my custom entity. This is the way I would have done it in Drupal 7, but I'm worried about the long term of running reports in Views using the data that isn't in the Entity itself. This seems like the quick and dirty way to do it but I don't want a Views headache later.
4. Figure out how to do this in Paragraphs.

Hopefully, someone with a little more experience than I have in D8 can point me to the most preferable way to handle this. Any help would be greatly appreciated.

# Answer
I would pick option 3: Create a custom field type that holds all 3 values in one table. This works fine with views. This can be done with Drupal console to simplify the process, see generate:plugin:field. I would also create a separate module for the the plugin with the custom field type so you can test enabling and disabling you main module without running into dependency issues. The advantage of this method over all others is all the data is held in one DB table which keeps things simple and is more efficient.

To briefly touch on your other options, 1 seems dirty and prone to problems. 2 is not bad and does give you more flexibility but means more code and more database tables. If you don't need the added flexibility then there is no need. Paragraphs, Option 4 will create as many DB tables as a custom entity but with less flexibility (you can't add methods to the ContentEntityBase) and more reliance on contrib modules. This is only a good option if your a site builder and don't want to worry about coding.
> 1 votes

---
Tags: 8, entities
---


# Question
Title: 7 embed an external website page in a node
I have two website one is in drupal 7 the other in rails.
Is it possible to have one page from the rails app to be embedded in a drupal 7 node? The page have a graph and search form.

# Answer
An iFrame is the only option that doesn't involve huge amounts of work.

I guess if you really wanted to you you could write an API for the rails app that Drupal could consume and recreate the content off this data.

Technically you could get Drupal to scrape the HTML (file\_get\_contents or curl) of the ruby app and then cache this locally and embed in the node. This doesn't seem like a good idea as is inefficient and you may have problems with the search action and cache flushing mechanisms.
> 1 votes

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


# Question
Title: How do I create a conditional form field?
I have this dropdown menu of options in the user registration page of my site (image shown below), and i want when the user selects the employer, some text fields appear, like name of company, and when they select job seeker, the text field that appears asks for things like uploading CV.

I have conditional fields module installed but it does not cater for user registration form (image shown below) .

Is there a way to add the user registration form to be one of the options that conditional fields module offers? I have followed each of those links and none of them is helpful.:(

Lastly, in the account type drop down image shown above, I want to filter out the administrator, anonymous user and authenticated user options such that the user only creates either an employer account or job seeker account. Any ideas how i can do that?

# Answer
> 0 votes
You can do this using taxonomy terms. A warning though ... taxonomy worked terribly due to the amount of conditional items. For my situation, user selected a state, then the town it took about a minute for each selection.

Does this help? http://www.webbykat.com/2013/04/conditional-fields-and-term-reference-tree-two-small-bugs-their-resolution

I'm assuming you have this Drupal 7 module? https://www.drupal.org/project/conditional\_fields

# Answer
> 0 votes
If you happy doing some custom coding then you can use `hook_form_alter()` to alter the form and then use states to conditionally hide and show fields. You can also remove the other options from the account type select whilst your there.

For example your code may look something like this:

```
/**
 * Implements hook_form_FORM_ID_alter() for user_register_form.
 */
function YOUR_MODULE_form_user_register_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  // Install devel and uncomment this line to understand the struture of the $form array
  //dpm($form);

  $form['your_field']['#states'] = [
    'visible' => [
      ':input[name="somefield[value]"]' => ['checked' => TRUE],
    ]
  ];

  unset($form['account_type']['#options']['administrator']);
  unset($form['account_type']['#options']['anonymous user']);

}

```

This code just gives you an idea of the kind of thing required - you will need to modify what is above to fit your exact use case.

This is certainly more complex than using the conditional fields module but is also far more flexible.

---
Tags: 8
---


# Question
Title: How to create field collection item fields programmatically?
I'm trying to program a field collection with field collection item fields like the code as given by rbruhn on Creating field collection programatically. I want to create it on an easier level for testing purposes. My goal is to create a taxonomy reference dropdown and a textfield.

I managed to reproduce the field\_collection type. However, I can't reproduce any field collections item fields.

Let's say I want a textfield in my field collection. Creating an ordinary textfield field collection item field would make sense to me, but it doesn't work.

Can someone tell me what I am doing wrong?

Instead of appearing inside my field collection, it appears as a field inside my node which contains my field collection field.

```
    array(
      'field' => array(
        'field_name' => 'name_of_my_field',
        'type' => 'text',
        ),
      ),
      'instance' => array(
        'field_name' => 'name_of_my_field',
        'entity_type' => 'field_collection_item',
        'bundle' => 'name_of_my_field_collection_field',,
        'widget' => array('type' => 'text_textfield'),
      )
    ),

```

# Answer
This works for me (my field collection is called field\_fc\_test). I imagine the problem is with the way you are calling field\_create\_instance.

```
$new_field = array(
  'field' => array(
    'field_name' => 'name_of_my_field',
    'type' => 'text',
    ),
  'instance' => array(
    'field_name' => 'name_of_my_field',
    'entity_type' => 'field_collection_item',
    'bundle' => 'field_fc_test',
    'widget' => array('type' => 'text_textfield'),
  ),
);
field_create_field($new_field['field']);
field_create_instance($new_field['instance']);

```
> 0 votes

# Answer
Here is some sample code to create a field collection called carousel\_slides:

```
$field = array(
  'settings' => array(
    'hide_blank_items' => 1,
    'path' => '',
  ),
  'field_name' => 'carousel_slides',
  'type' => 'field_collection',
  'cardinality' => '-1',
);
if (field_info_field($field['field_name']) === NULL) {
  field_create_field($field);
}

```

And then to create the instance:

```
// carousel_slides instance
$instance = array(
  'label' => 'Slides',
  'widget' => array(
    'weight' => '1',
    'type' => 'field_collection_embed',
    'module' => 'field_collection',
    'active' => 0,
    'settings' => array(
    ),
  ),
  'settings' => array(
    'user_register_form' => FALSE,
  ),
  'display' => array(
    'default' => array(
      'label' => 'hidden',
      'type' => 'field_collection_view',
      'weight' => '1',
      'settings' => array(
        'edit' => '',
        'delete' => '',
        'add' => '',
        'description' => 0,
        'view_mode' => 'full',
      ),
      'module' => 'field_collection',
    ),
  ),
  'required' => 0,
  'description' => '',
  'default_value' => NULL,
  'fences_wrapper' => 'ul', // You probably won't need this unless you are using the fences module
  'field_name' => 'carousel_slides',
  'entity_type' => 'node',
  'bundle' => 'carousel',
  'deleted' => '0',
);
if (!field_read_field($instance['field_name'])) {
  field_create_instance($instance);
}

```

Here I'm doing checks to make sure that the field and instance doesn't exist first to make sure it won't cause an error and stop updates running when this code is in hook\_update\_N in an environment with a database that could potentially be out of sync.

There are also many properties here that you probably don't need. These arrays were created programmatically by exporting the field directly from Drupal with a script.
> 0 votes

---
Tags: entities
---


title: Ckeditor missing buttons

text:
# Question
Title: Ckeditor missing buttons
I'm using CKeditor as the Wysiwyg container. I configured it to show the full toolbar but when the user tries to edit it does not show the buttons configured. I'm using the last version of the module available for drupal 7 and jquery 1.7. Some buttons as iframe or letter size are not showing up. What can I do to solve this. Best regards Eduardo

# Answer
If it is showing for you (user one or admin) but not someone else logged in, it could be permissions.

I would create a test account with the same permissions as the person having issues. Do you see the ckeditor toolbar while logged into the test account?

If that is working, try the solution mentioned here.
> 1 votes

---
Tags: wysiwyg
---


# Question
Title: How to to render a webform (or any configurable form) in a node edit form?
I have a weird use case, where I was looking to perform the following:

* In a node edit form, allow a user to entity reference a collection of webforms
* When a user selects an appropriate webform from the entity reference autocomplete, render that form in the current node edit form
* User fills out fields in these webforms then proceeds to save the node.
* On node save, the webform submit data is stored in a particular field in the node (perhaps in json format).

Is this even possible with webforms, or do any other form modules exist that support this use case?

# Answer
> 0 votes
In this instance it sounds like the paragraphs module solves your problem. However to answer your original question...

I would use entityform, not webform to do this.

Once you added all of your field to your entity form then you can use Inline Entity Form to embed the child form.

---
Tags: 8, webforms
---


title: Forward user email address

text:
# Question
Title: Forward user email address
I use Webform with Commerce product skus field. Now I have a rule to send out an email to customer if webform is submitted. That works fine. But I would like to set a rule to send the email when the customer check out. My problem is that i don't know the token which I have to set in this Drupal Commerce rule. In Webform rule, I use this \[data:e\_mail-value\], but in the Drupal Commerce rule I have \[commerce-order:mail\] which is not the same, is it?

How can I forward the right user email address from webform submission to the final Drupal Commerce confirmation email?

# Answer
> 0 votes
The "commerce-order:mail" token will only show the user email associated with whoever is logged in and submitting the order, while the webform email value from the token \[data:e\_mail-value\] is a component in the webform submission and generally stores the submission with the author/owner being "anonymous".

* If your webform automatically redirects to the commerce cart/checkout, then I'd suggest forcing the user to be logged in before they even fill out the webform and hit submit. Then you can set the default value of the webform email field with a token for the email of current user and hide it from view.
* Otherwise, you'll need to write custom functionality to somehow store and pass the webform submitted data:e\_mail-value to a hidden field associated with the order itself in the checkout process.

---

Also as a reminder for the "To" address field in the workflow rule for sending an email, you need to format it to comply with RFC 2822- by wrapping the email address string with \<\>. For example:

Should you want to send to multiple recipients, then you'll want a comma separated list of emails, each wrapped in \<\>.

---
Tags: 7, commerce, rules, webforms
---


# Question
Title: 8 - How do a get a view then save it with a new value
In an `update_hook()` I need to search all views' displays for a value, then resave them with a new/extra one. How do I go about this? What command can I use?

```
$views = Views::getEnabledViews();
foreach ($views as $view) {
  $source_value = '';
  $config = \Drupal::config('views.view.' . $view->id());
  $rawData = $config->getRawData();

  $master = FALSE;
  // Get the display with the draggableviews field.
  // It is a little tricky because the 'default' display is the master.
  foreach ($rawData['display'] as $display_key => $display) {
    $field = isset($display['display_options']['fields']) ? $display['display_options']['fields'] : [];
    if ($display_key == 'default' && array_key_exists('draggableviews', $field)) {
      $master = TRUE;
    }
    if ($display_key != 'default' && array_key_exists('draggableviews', $field)) {
      $source_value = $view->id() . '|' . $display_key;
    }
    if ($master && empty($display['display_options']['fields'])) {
      $source_value = $view->id() . '|' . $display_key;
    }
  }
  if ($source_value) {
    // Save the view with the source value in the sort handler.
    foreach ($rawData['display'] as $display_key => $display) {
      $sorts = isset($display['display_options']['sorts']) ? $display['display_options']['sorts'] : [];
      if (array_key_exists('weight', $sorts)) {
        // **************
        // SAVE VIEW HERE
        // **************
      }
    }
  }
}

```

# Answer
> 0 votes
Replace

```
// **************
// SAVE VIEW HERE
// **************

```

with

```
$view_exec = Views::getView($view->id());
$view_exec->setHandlerOption($display_key, 'sort', 'weight', 'source', $source_value);
$view_exec->save();

```

When you call `Views::getEnabledViews()` it gives you an array of View classes. What you need is the ViewsExecutable class. `Views::getView($id)` returns this.

**ViewsExecutable**

> An object to contain all of the data to generate a view, plus the member functions to build the view query, execute the query and render the output.

Views vs ViewsExecutable

Another good example of using `setHandlerOptions` is in the TestCase

FieldGroupRowTest

---
Tags: 8, views
---


# Question
Title: Copy nodes of content type into Commerce Products
I currently have a Drupal website for an art gallery with a content type of Listing (A piece of Art work). Each Listing has a price in a decimal field type.

We are now looking to convert the website to ecommerce using Drupal Commerce, but there is about 500 Listings.

Is there a way to bulk copy/create all the Listings into Products and auto create the product reference and copy the price over as well?

# Answer
There is no direct option or module which can convert a content type nodes to commerce products. But there are few ways you can do it. You can export your nodes to CSV via node export or views bulk operations and then import those products using commerce feeds module. Another way is to create a custom module and do db\_select of all nodes of your particular content type and then create commerce products programmatically. You can use batch process to do this so that php execution time don't break your script.
> 1 votes

# Answer
This is the way I have done this:

Export all nodes of \[type\] using module **Views Data Export** https://www.drupal.org/project/views\_data\_export

Import these as products using **Feeds** and **Commerce Feeds**.

Automatically link and manage 1 Product to 1 Node using **Auto Product Display** https://www.drupal.org/project/commerce\_auto\_product\_display

If anyone wants a more detailed answer as to the exporting/importing/importing with the SKU references, happy to share.

## Summary

Use the Nid as the Unique Reference
1. Export Nodes
2. Import as Products
3. Import to existing nodes - but only mapped the SKU field for the product reference
> 0 votes

---
Tags: nodes, commerce
---


title: Set a date programmatically

text:
# Question
Title: Set a date programmatically
Once a page is saved I want to put the current time (I know I can do it by the form, but I need to do it programmatically). My code:

```
function mymodule_node_presave(EntityInterface $entity) {
    $node_type = $entity->bundle();
    if ($node_type === 'page') {
            $date = date('Y-m-d 00:00:00', time());
            $entity->field_mydate->value = $date;
            $entity->body = $date;
       }
}

```

It changes the body correctly but not the date field. I tried all those, none works. I can't understand where is the problem.

# Answer
> 1 votes
Solved the issue. In my case, after debugging the value, I guessed the right code could be:

```
$date = date('Y-m-d\T00:00:00', time());

```

And it is. I'm not sure what the date format depends on. For sure it doesn't depends on the form display format since in the I'm using the Italian one (d/m/Y).

---
Tags: 8, datetime
---


# Question
Title: How to change taxonomy url in node view page?
How to change taxonomy url in node view page in Drupal 8?

In node view page I am getting taxonomy term url pattern as term/{%term\_id}. I want to change taxonomy term url to custom url in Drupal 8.

Any help?

# Answer
the code below replaces term/{%term\_id} by node/39?technologie={%term\_id} with `THEME_preprocess_field` :

```
use Drupal\Core\Url;

function MYTHEME_preprocess_field__FIELD_TAXO_MACHINE_NAME(&$variables, $hook){

    foreach ($variables['items'] as $index => $item) {

      $route_name = 'entity.node.canonical';
      $params     = 39;
      $tid = $item['content']['#options']['entity']->id();

      $options = [
        'query' => ['technologie' => $tid],
      ];

     $url = Url::fromRoute($route_name, array('node' => $params), $options);
     $variables['items'][$index]['content']['#url'] = $url;
  }
}

```
> 2 votes

# Answer
* Goto **Home -\> Administration -\> Structure -\> Views -\> Taxonomy term -\> Edit** and Click **Duplicate page** and update the path with your custom path.
* Now update the existing node view's and Add **Term Id** field.
* Then update term field by clicking on it, select **Rewrite result**
-\> **Output this field as a custom link** -\> Enter the link to new view's path with term id from **Replacement Patterns** and save the view. Now you will get page same default term page.
> 0 votes

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


# Question
Title: How to create media image entities like an image field?
I have been using a content type **Article** with an **Image** field to allow users to upload images. I have decided that I want to use media image entities instead because the images will be re-used on multiple nodes, so it would be better to use a module like Entity Browser to allow admins to pick the images they want to use.

Following this tutorial, I set up Media Entity, Media Entity Image, Embed, and Embed Entity on my site. I can now add entities from the `/media/add/image` page.

But, with using this set of modules, the workflow has changed.

**Image field on content type workflow**

1. User uploads images in the field when creating a node.

**Media entity image + content type/embed workflow**

1. User uploads images.
2. User creates a node.
3. User embeds the images on the node.

So actually this new workflow has more steps than the old one. Is there a way to "embed" creation of media entities as if it was just an **image** field attached to the content type?

# Answer
> 3 votes
Sounds like exactly the use case Inline Entity Form was built for:

> Provides a widget for inline management (creation, modification, removal) of referenced entities.

---
Tags: 8, entities, media, workflows
---


title: How do I use MariaDB instead of MySQL?

text:
# Question
Title: How do I use MariaDB instead of MySQL?
I need to use MariaDB instead of MySQL in Drupal 8. I have already installed MariaDB in my local system.

How do I use it with Drupal 8? What changes are required to use it?

# Answer
> 4 votes
MariaDB is a drop-in replacement for MySQL. No changes are required.

You'll obviously need to update your connection/credential details to match the new server, but as far as configuring Drupal to use MariaDB, there's nothing to do.

# Answer
> 2 votes
Drupal 8 requires MySQL 5.5.3/MariaDB 5.5.20/Percona Server 5.5.8 or higher with InnoDB as the primary storage engine. If you have the right version of MariaDB, Drupal will work without you doing anything different from when using MySQL, which also means you don't need to select a different driver, or tell Drupal the database engine is not MySQL.
Be sure you are using the correct credentials for accessing the database.

MariaDB is a drop-in replacement, which means PHP will think to be talking with MySQL, so you don't need to do anything different from when you would use MySQL.

### References

---
Tags: database
---


title: Permissions filter like module filter

text:
# Question
Title: Permissions filter like module filter
The module filter makes managing modules from the UI very easy to manage. Live update with the search query and grouping. I've been looking for a similar module for the more messy permissions table. A similar module would definitely make it easier to manage that monstrous table :D

**Does anybody know if a module exists for this?**

I did try searching but I might not have used the right terms just like when I searched for user spoof and it resulted to a module named Masquerade.

# Answer
> 7 votes
The Fast Permissions Administration module is the closest equivalent that I've found

> This module is here to alleviate frustration when trying to manage permissions in Drupal. By providing a better permissions interface hopefully a few innocent keyboards and mice can be saved.

You get a UI like:

# Answer
> 4 votes
The 2.x branch of Module Filter includes a filter on the permissions page. By default it filters on the name of the module rather than the permission, but if you want to search by permission you can use a query prefixed with "perm:", e.g., perm:administer.

The available updates page also has a filter.

# Answer
> 2 votes
There is also the Filter Permissions (filter\_perms) module.

Both this and the accepted answers are good solutions, I think for Drupal 7 (no need to change the accepted answer). I think the difference between Filter Permissions (filter\_perms) and Fast Permissions Administration fpa is that the filtering provided by the fpa module is mainly (or perhaps totally) client-side based (I am guessing possibly that the entire module list is in the browser and client-side code provided with fpa filters this (perhaps using JS etc)). Whereas with filter\_perms, the filter is submitted to the server-side, to the module in the Drupal site code which returns a filtered list.

My comparison of both is based on the following references:

from https://www.drupal.org/project/fpa :-

> **Optional integration with Filter permissions:**
>
> If you have a large number of permissions and roles, you might experience memory limit issues when accessing the permissions page that FPA is not designed to handle.
>
> If you are experiencing these issues, it is suggested that you install the Filter permissions module along side FPA.

from: https://www.drupal.org/project/filter\_perms :-

> If you aren't having performance issues due to massive permissions/roles and want a nice filtering solution that works entirely client side, Fast Permissions Administration is a slick module that has a different approach than Filter Permissions but will give similar benefits.

Also from my own experience of using filter\_perms, the interface uses a html form based filter with a post to the server-side to send the filtering information.

As said, I think both modules are good solutions and therefore it would be for the site builder to choose.

The bottom line I think is that on the basis of being more client-side-based in filtering, fpa is the faster at filtering (as the name of the module suggests), but for sites with a large number of permissions it might not be scaleable if there are server-side memory limitations when rendering the page and also on the browser/client side if performance and memory there is limited.

Meanwhile although filter\_perms might be perhaps a little slower as it uses a form submit to the server to filter, it would perhaps be more scaleable for a large amount of permissions if only the filtered subset are rendered on the server side and sent to be displayed in browser (e.g. out of memory fatal errors are less likely)

Both modules also have a Drupal 8 development branch, however I have not used this version at time of writing so could not advise on if there is available functionality in the Drupal 8 versions of the modules.

# Answer
> 2 votes
I'm using now in Drupal 8 the Permissions Filter module

> The permission Filter module is a simple approach to provide a search functionality in the people/permission page. It will help site admin to get the desired result without scrolling down.

For Drupal 7 you have (apart the modules mentioned by other users) these modules:

Dream permissions

> This module facilitates the management of permissions, it allows you to exclude roles and modules from the management screen.
>
> The management page uses ajax to load the relevant permissions, you have to select at least one role and at least one module, otherwise you don't get any results. Both roles and modules can be filtered to make the selection easier.

Permission Select

> Permission Select is a module that allows for quicker editing of role permissions on /admin/user/permissions.
>
> The module utilizes jQuery to manipulate the DOM, creating links to check all / uncheck all on each set of permissions for each module. This allows for quicker manipulation of permissions for standard users.

Permissions Grid

> This gives an alternative way of administering permissions, by showing those that form a related set in a grid of 'verbs' and 'objects'. For example, for node permissions, this shows 'create', 'edit own', and so on across the grid, and node types down the side.

---
Tags: users
---


# Question
Title: Trying to save an image field on a user using services, but for some reason it isn't saving in base64
So my server (running Drupal 7) is getting this information:

```
[field_picture] => Array
    (
        [und] => Array
            (
                [0] => Array
                    (
                        [file] => iVBORw0KGgoAAAANSUhEUgAAAIwAAACMCAYAAA..... (the rest of a huge base64 string)
                        [filename] => test.png
                        [filemime] => image/png
                        [target_uri] => test.png
                        [filepath] => public://
                        [mimeType] => image/png
                    )

            )

    )

```

This is to a user endpoint, and this is the only field that doesn't update.

The rest of what is sent to the server looks like this:

```
[field_description] => Array
        (
            [und] => Array
                (
                    [0] => Array
                        (
                            [value] =>
                            [format] =>
                            [safe_value] =>
                        )

                )

        )

[uid] => 22
[roles] => Array
    (
        [2] => authenticated user
    )

```

And my AJAX to put this up:

```
    $.ajax({
        url: SITE_URL + "/" + ENDPOINT + "/user/" + localStorage.uid,
        type: 'PUT',
        crossDomain: true,
        headers: {
            'X-CSRF-Token': token
        },
        contentType: 'application/json',
        data: JSON.stringify(json),

...etc

```

The request doesn't fail (or at least it doesn't go to my error callback) - what is going on here and why isn't it saving?

# Answer
> 0 votes
You need to make two requests, the first you will POST the base64 encoded string of the file which in turn will return to you the file id, at which point you can make the second call to save the user entity with the file id on the field in question. I have a blog post about this here: http://tylerfrankenstein.com/code/drupal-services-file-create-example-json-and-jquery

Here's the gist of it (assuming your endpoint path is `api`):

```
// Get the file id...
$.ajax({
  type: "post",
  data: {
    "file":{
      "file": my_base_64_encoded_image_string,
      "filename": "my_image.jpg",
      "filepath": "public://my_image.jpg",
    }
  },
  url: 'https://www.example.com/api/file.json',
  dataType: 'json',
  success: function(result) {

    // Now that we have the file id, save it on the user entity.
    var userAccount = {
      field_picture: { und: [ { fid: result.fid } ] }
    };

    $.ajax({
      url: "https://www.example.com/api/user/" + localStorage.uid,
      type: 'PUT',
      crossDomain: true,
      headers: {
          'X-CSRF-Token': token
      },
      contentType: 'application/json',
      data: JSON.stringify(userAccount)
    });

  }
});

```

---
Tags: 7, media, services
---


# Question
Title: User can't access own private files via Views
I've set up a private directory *sites/default/files/private* and use it for a file field.

As an admin, everything works as expected when uploading and viewing a private file.

As a user who uploads a private file, I can only download own private files with the Views formatter *Download link* (example.com/file/585/download?token=TcBjzT2I), but not view them via *Generic file* (example.com/system/files/private/mypic.jpg) or other formatters. When using the latter, I get

"Access Denied You are not authorized to access this page."

Permission "View own private files" for role enabled. Even enabling "View private files" has no effect.

What am I missing?

# Answer
> Files in the private directory are not accessible directly through the web server;

You may have to use file\_create\_url or hook\_file\_download to access the files under private directory.

For More info on **Accessing Private Files** check here
> 0 votes

---
Tags: 7, files
---


# Question
Title: How to change the length of field settings?
I have set once to a website a lenght limit to a field. And now the client wants to put more characters to that field.

I cannot change the maximum size from Drupal because I get the following error message:

> There is data for this field in the database. The field settings can no longer be changed.

However there must be a solution. Shall I change it in database (the field is one implemented by the Field-collections module)?

# Answer
Dylan Tack solution is the easiest, but personally I enjoy exploring the inner wards of Drupal's database to seen how things are managed down there.

So, assuming you have a text field which machine name is field\_text of 10 characters you want to grow to 25:

* data will be stored in two tables: field\_data\_field\_text and field\_revision\_field\_text
* definition is stored in field\_config for the storage data, and field\_config\_instance for each instance of this field (stuff like label).

Now let's do a little heart surgery.

1. Alter the data tables columns definitions:

```
ALTER TABLE `field_data_field_text`
CHANGE `field_text_value` `field_text_value` VARCHAR( 25 )
CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL;

ALTER TABLE `field_revision_field_text`
CHANGE `field_text_value` `field_text_value` VARCHAR( 25 )
CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL;

```
2. Change the **definition** column, this one is very tricky because it's stored in a *BLOB*, but that's not something that will stop you for doing this.

* Dissect the guts of this *BLOB* thing:
```
SELECT CAST(`data` AS CHAR(10000) CHARACTER SET utf8)
FROM `field_config` WHERE field_name = 'field_text';

```

* This will give you something like:
```
a:7:{s:12:"translatable";s:1:"1";s:12:"entity_types";a:0:{}s:8:"settings";a:2:
    {s:10:"max_length";s:2:"10";s:17:"field_permissions";a:5:
    //a lot more stuff...

```

* This is a PHP serialized array, the interesting part is `s:10:"max_length";s:2:"10";`, this mean this array has a property named `max_length` (which name is a 10 characters string - hence the "s") which value is 10 (which is a 2 characters long string). It's pretty easy, isn't it?
    * Changing its value is as easy as replacing the `s:2:"10"` part by `s:2:"25"`. **Be careful:** if your new value is longer in character length, you have to adapt the "s" part accordingly. For example putting 100 will be `s:3:"100"` as 100 length is 3 characters.
    * Let's put this new value back in the DB, don't forget to keep the whole string.
```
UPDATE `field_config`
SET data = 'a:7:{...a:2:{s:10:"max_length";s:2:"25";...}'
WHERE `field_name` = 'field_text'

```

* Flush your caches.
3. ???
4. PROFIT!

By the way, PhpMyAdmin has some setting to allow direct modification of BLOB columns, but why go the easy way?

PS: This can also save your life when putting some PHP code in views and getting a WSOD because of an error in your code.
> 94 votes

# Answer
```
function mymodule_update_7100() {
  $items = array();
  _field_maxlength_fix('field_name');
  return $items;
}

function _field_maxlength_fix($field_name, $maxlength = 255) {
  _alter_field_table($field_name, $maxlength);
  $data = _get_field_data($field_name);
  $data = _fix_field_data($data, $maxlength);
  _update_field_config($data, $field_name);
}

function _alter_field_table($field_name, $maxlength) {
  db_query("ALTER TABLE field_data_".$field_name." CHANGE ".$field_name."_value ".$field_name."_value VARCHAR( ".$maxlength." ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
  db_query("ALTER TABLE field_revision_".$field_name." CHANGE ".$field_name."_value ".$field_name."_value VARCHAR( ".$maxlength." ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL");
}

function _get_field_data($field_name) {
  $qry = "SELECT data FROM field_config WHERE field_name = :field_name";
  $result = db_query($qry, array(':field_name' => $field_name))->fetchObject();
  return unserialize($result->data);
}

function _fix_field_data($data, $maxlength) {
  $data['settings']['max_length'] = (string)$maxlength;
  return serialize($data);
}

function _update_field_config($data, $field_name) {
  $qry = "UPDATE field_config SET data = :data WHERE field_name = :field_name";
  db_query($qry, array(':data' => $data, ':field_name' => $field_name));
}

```
> 21 votes

# Answer
This appears to be a limitation of the current text module. text\_field\_settings\_form() has this comment: "**@todo**: If $has\_data, add a validate handler that only allows max\_length to increase.".

As a temporary workaround, you could comment out `'#disabled' => $has_data` in modules/field/modules/text/text.module, around line 77.

I couldn't find an existing issue for this specific case, but you might mention it on #372330.
> 9 votes

# Answer
**Drupal 7**

> When creating a text field in Drupal 7, you must a choose a maximum length for your data. As soon as you create any data for this field, the maximum length become immutable in the Drupal field settings.
>
> It's understandable that this would be disabled for decreasing the maximum length because it could results in a loss of data, however, it should be possible to increase the maximum length for any field. A todo in the Drupal 7 Text module code shows this was intended but never accomplished.
>
> The 3 things that need to happen:
>
> 1. Change the VARCHAR length of the value column in the field\_data\_{fieldname} table
> 2. Change the VARCHAR length of the value column in the field\_revision\_{fieldname} table
> 3. Update the configuration of the field to reflect the new max length setting The following function accomplishes all 3 of these steps and takes 2 easy parameters including the name of the field and the new maximum length.

```
/**
 * Helper function to change the max length of a text field.
 */
function MYMODULE_change_text_field_max_length($field_name, $new_length) {
  $field_table = 'field_data_' . $field_name;
  $field_revision_table = 'field_revision_' . $field_name;
  $field_column = $field_name . '_value';

  // Alter value field length in fields table.
  db_query("UPDATE `{$field_table}` SET `{$field_column}`=SUBSTR(`{$field_column}`, 0, {$new_length})");
  db_query("ALTER TABLE `{$field_table}` CHANGE `{$field_column}` `{$field_column}` VARCHAR( {$new_length} )");
  // Alter value field length in fields revision table.
  db_query("UPDATE `{$field_revision_table}` SET `{$field_column}`=SUBSTR(`{$field_column}`, 0, {$new_length})");
  db_query("ALTER TABLE `{$field_revision_table}` CHANGE `{$field_column}` `{$field_column}` VARCHAR( {$new_length} )");

  // Update field config with new max length.
  $result = db_query("SELECT CAST(`data` AS CHAR(10000) CHARACTER SET utf8) FROM `field_config` WHERE field_name = '{$field_name}'");
  $config = $result->fetchField();
  $config_array = unserialize($config);
  $config_array['settings']['max_length'] = $new_length;
  $config = serialize($config_array);
  db_update('field_config')
    ->fields(array('data' => $config))
    ->condition('field_name', $field_name)
    ->execute();
}

```

> Once this function is available in your custom install file you can create a new database update function that uses this new function to make your required changes.

```
/**
 * Change max_length of Name field
 */
function mymodule_update_7002() {
  MYMODULE_change_text_field_max_length('field_name', 50);
}

```

Source: http://nathan.rambeck.org/blog/42-modify-drupal-7-text-field-maximum-length

---

### Drupal 8

Here is the version of the same function proposed by @Christopher:

```
/**
 * Utility to change the max length of a text field.
 *
 * @param string $field_name
 *   Field name.
 * @param int $new_length
 *   Field length in characters.
 *
 * @throws \DrupalUpdateException
 */
function MYMODULE_change_text_field_max_length($field_name, $new_length) {
  // The transaction opens here.
  $txn = db_transaction();

  try {
    // Update field content tables with new max length.
    foreach (['field_data_', 'field_revision_'] as $prefix) {
      db_query('
      ALTER TABLE {' . $prefix . $field_name . '}
        MODIFY ' . $field_name . '_value VARCHAR( ' . $new_length . ' )
      ');
    }

    // Update field config record with new max length.
    $result = db_query("
        SELECT CAST(data AS CHAR(10000) CHARACTER SET utf8)
        FROM {field_config}
        WHERE field_name = :field_name
      ", [':field_name' => $field_name]
    );
    $config = $result->fetchField();
    if ($config) {
      $config_array = unserialize($config);
      $config_array['settings']['max_length'] = $new_length;
      $new_config = serialize($config_array);
      db_update('field_config')
        ->fields(['data' => $new_config])
        ->condition('field_name', $field_name)
        ->execute();
    }
  }
  catch (Exception $e) {
    // Something went wrong somewhere, so roll back now.
    $txn->rollback();
    // Allow update to be re-run when errors are fixed.
    throw new \DrupalUpdateException(
      "Failed to change $field_name field max length: " . $e->getMessage(),
      $e->getCode(), $e
    );
  }
}

```
> 8 votes

# Answer
Try this... this will update the field data type from TEXT to LONG\_TEXT and update the `max_length` from 4000 to max long text length... hope this helps.

```
function my_module_update_1001(&$sandbox) {
  // Check if our field is already created.
  if (field_info_field('sample_text_field')) {
    db_query('ALTER TABLE field_data_sample_text_field CHANGE sample_text_field_value sample_text_field_value LONGTEXT');
    db_query('ALTER TABLE field_revision_sample_text_field CHANGE sample_text_field_value sample_text_field_value LONGTEXT');
    db_query("UPDATE field_config SET type = 'text_long' WHERE field_name = 'sample_text_field' ");

    $field = array(
      'field_name' => 'sample_text_field',
      'type' => 'text_long',
      'cardinality' => 1,
      'settings' => array(
         'max_length' => 0,
      ),
    );
    field_update_field($field);
  }
}

```
> 3 votes

# Answer
**D8**

1. Comment out the two lines in `core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorageSchema.php` that throw exceptions with the text "The SQL storage cannot change the schema for an existing field". About lines 1312 and 1403.
2. In your browser, navigate to `/admin/config/development/configuration/single/export`. The configuration type is "Field Storage", and choose the field in question. Copy the configuration.
3. Navigate to `/admin/config/development/configuration/single/import`. . The configuration type is "Field Storage". Paste the configuration. Change the length.
4. Submit the form.

Note (as you probably already know), if you shorten the length, then existing data will be truncated.
> 3 votes

# Answer
In Drupal 7, I made modifications to 2 tables in phpmyadmin, and refreshed the cache.

1. "field\_data\_field\_lorem": changed "field\_lorem\_value" to "longtext"
2. "field\_config": changed "type" to "text\_long"
> 1 votes

---
Tags: 7, entities, database
---


title: Date field exposed filter - select year

text:
# Question
Title: Date field exposed filter - select year
Back in Drupal 7 I've created exposed filter with Year from date field. (Selet list).

* View all
* 2017
* 2016
* 2015 etc...

And when creating such filter we had options like on this picture:

BUT, now in Drupal 8 I cannot see that is supported.

I've installed Better Exposed filters but only thing is that I can select datepicker instead of plain text field for this filter, but I need select list and only years.

If it's not possible yet, where I can find examples of creating custom exposed filters or something like that?

# Answer
Luckily just a day before your question this tutorial for year select filter was posted on Drupal planet:

https://www.flocondetoile.fr/blog/filter-content-year-views-drupal-8
> 1 votes

---
Tags: 8, views, datetime
---


# Question
Title: Uploaded image in Block Plugin keeps on getting deleted overnight
I have a block plugin that allows users to upload an image to be used as a background. Below is what is inside my blockForm function.

```
    $form = [
        'image' => [
            '#type' => 'managed_file',
            '#title' => 'Image',
            '#upload_location' => 'public://my_style/images',
            '#default_value' => $this->configuration['image'],
        ],
    ];

```

And my block submit function is as follows.

```
public function blockSubmit($form, FormStateInterface $form_state) {
    $values = $form_state->getValues();

    foreach ($values as $index => $value) {
        $this->configuration[$index] = $value;
    }
}

```

Initially this works just fine. The image is uploaded and appears in the background of my block plugin. However overnight it's always deleted. I did see this post Set image as permanent in custom block plugin, temporary URI however I don't see anything different that would cause issues with my code against the one provided in that post. Is there something missing? Or is there anything wrong with how I'm performing the submit function.

I suppose I could try to check if the formstate value is a file and then load the file and then set it to permanent and then save it. But even if that works why would it be necessary in this case but not in others?

# Answer
As you guessed its must to set permanent while saving the file. You need to include, $file = File::load( $fid ); if ($file) { $file-\>setPermanent(); $file-\>save(); }

> The files will be added to the {file\_managed} table as temporary files. Temporary files are periodically cleaned. Use the 'file.usage' service to register the usage of the file which will automatically mark it as permanent.
> 2 votes

---
Tags: 8, blocks
---


# Question
Title: View uses the wrong template when cache is enabled
I'm using the latest version 8.2.4 of drupal core, which ships with view.

After enabling the internal cache system, some of my views get broken.

My view configuration is:

```
uuid: xxx
langcode: de
status: true
dependencies:
  config:
    - block.block.unternavigation_unternehmen
    - core.entity_view_mode.node.standort
    - field.storage.node.field_ansprechpartner
    - node.type.standort
    - system.menu.main
  content:
    - 'block_content:formulare:13194389-5c27-4811-aa91-478cd4d80d52'
  module:
    - node
    - user
id: standorte
label: Standorte
module: views
description: ''
tag: ''
base_table: node_field_data
base_field: nid
core: 8.x
display:
  default:
    display_plugin: default
    id: default
    display_title: Master
    position: 0
    display_options:
      access:
        type: perm
        options:
          perm: 'access content'
      cache:
        type: tag
        options: {  }
      query:
        type: views_query
        options:
          disable_sql_rewrite: false
          distinct: false
          replica: false
          query_comment: ''
          query_tags: {  }
      exposed_form:
        type: basic
        options:
          submit_button: Anwenden
          reset_button: false
          reset_button_label: Zurücksetzen
          exposed_sorts_label: 'Sortieren nach'
          expose_sort_order: true
          sort_asc_label: Aufsteigend
          sort_desc_label: Absteigend
      pager:
        type: some
        options:
          items_per_page: 20
          offset: 0
      style:
        type: default
        options:
          row_class: ''
          default_row_class: true
          uses_fields: false
      row:
        type: 'entity:node'
        options:
          relationship: none
          view_mode: default
      fields:
        title:
          id: title
          table: node_field_data
          field: title
          entity_type: node
          entity_field: title
          label: ''
          alter:
            alter_text: false
            make_link: false
            absolute: false
            trim: false
            word_boundary: false
            ellipsis: false
            strip_tags: false
            html: false
          hide_empty: false
          empty_zero: false
          settings:
            link_to_entity: true
          plugin_id: field
          relationship: none
          group_type: group
          admin_label: ''
          exclude: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: true
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_alter_empty: true
          click_sort_column: value
          type: string
          group_column: value
          group_columns: {  }
          group_rows: true
          delta_limit: 0
          delta_offset: 0
          delta_reversed: false
          delta_first_last: false
          multi_type: separator
          separator: ', '
          field_api_classes: false
      filters:
        status:
          value: '1'
          table: node_field_data
          field: status
          plugin_id: boolean
          entity_type: node
          entity_field: status
          id: status
          expose:
            operator: ''
          group: 1
        type:
          id: type
          table: node_field_data
          field: type
          value:
            standort: standort
          entity_type: node
          entity_field: type
          plugin_id: bundle
      sorts:
        field_sortierung_value:
          id: field_sortierung_value
          table: node__field_sortierung
          field: field_sortierung_value
          relationship: none
          group_type: group
          admin_label: ''
          order: ASC
          exposed: false
          expose:
            label: ''
          plugin_id: standard
      title: ''
      header: {  }
      footer:
        entity_block_content:
          id: entity_block_content
          table: views
          field: entity_block_content
          relationship: none
          group_type: group
          admin_label: ''
          empty: false
          tokenize: false
          target: 13194389-5c27-4811-aa91-478cd4d80d52
          view_mode: default
          bypass_access: false
          plugin_id: entity
      empty: {  }
      relationships: {  }
      arguments: {  }
      display_extenders: {  }
    cache_metadata:
      max-age: -1
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - 'user.node_grants:view'
        - user.permissions
      tags: {  }
  footer_block:
    display_plugin: block
    id: footer_block
    display_title: Footer
    position: 5
    display_options:
      display_extenders: {  }
      display_description: ''
      footer: {  }
      defaults:
        footer: false
        filters: false
        filter_groups: false
      filters:
        status:
          value: '1'
          table: node_field_data
          field: status
          plugin_id: boolean
          entity_type: node
          entity_field: status
          id: status
          expose:
            operator: ''
          group: 1
        type:
          id: type
          table: node_field_data
          field: type
          value:
            standort: standort
          entity_type: node
          entity_field: type
          plugin_id: bundle
        field_nicht_im_footer_value:
          id: field_nicht_im_footer_value
          table: node__field_nicht_im_footer
          field: field_nicht_im_footer_value
          relationship: none
          group_type: group
          admin_label: ''
          operator: '='
          value: '0'
          group: 1
          exposed: false
          expose:
            operator_id: ''
            label: ''
            description: ''
            use_operator: false
            operator: ''
            identifier: ''
            required: false
            remember: false
            multiple: false
            remember_roles:
              authenticated: authenticated
          is_grouped: false
          group_info:
            label: ''
            description: ''
            identifier: ''
            optional: true
            widget: select
            multiple: false
            remember: false
            default_group: All
            default_group_multiple: {  }
            group_items: {  }
          plugin_id: boolean
      filter_groups:
        operator: AND
        groups:
          1: AND
    cache_metadata:
      max-age: -1
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - 'user.node_grants:view'
        - user.permissions
      tags: {  }
  kontakt:
    display_plugin: page
    id: kontakt
    display_title: Kontakt
    position: 1
    display_options:
      display_extenders: {  }
      path: kontakt
      display_description: ''
      menu:
        type: normal
        title: Kontakt
        description: ''
        expanded: false
        parent: ''
        weight: -42
        context: '0'
        menu_name: main
    cache_metadata:
      max-age: -1
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - 'user.node_grants:view'
        - user.permissions
      tags: {  }
  standorte:
    display_plugin: page
    id: standorte
    display_title: Standorte
    position: 2
    display_options:
      display_extenders: {  }
      display_description: ''
      path: standorte
      footer: {  }
      defaults:
        footer: false
        sorts: false
      menu:
        type: normal
        title: Standorte
        description: ''
        expanded: false
        parent: 'menu_link_content:a1b2d8c6-75af-459e-937e-0d1c792ef9b4'
        weight: -48
        context: '0'
        menu_name: main
      sorts:
        created:
          id: created
          table: node_field_data
          field: created
          relationship: none
          group_type: group
          admin_label: ''
          order: ASC
          exposed: false
          expose:
            label: ''
          granularity: second
          entity_type: node
          entity_field: created
          plugin_id: date
    cache_metadata:
      max-age: -1
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - 'user.node_grants:view'
        - user.permissions
      tags: {  }
  standorte_ansprechpartner:
    display_plugin: attachment
    id: standorte_ansprechpartner
    display_title: 'Standorte Ansprechpartner'
    position: 4
    display_options:
      display_extenders: {  }
      display_description: ''
      style:
        type: default
        options:
          row_class: ''
          default_row_class: true
          uses_fields: false
      defaults:
        style: false
        row: false
        fields: false
        footer: false
      row:
        type: 'entity:node'
        options:
          relationship: none
          view_mode: standort
      fields:
        field_ansprechpartner:
          id: field_ansprechpartner
          table: node__field_ansprechpartner
          field: field_ansprechpartner
          relationship: none
          group_type: group
          admin_label: ''
          label: ''
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: null
            word_boundary: false
            ellipsis: false
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: false
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          click_sort_column: target_id
          type: entity_reference_entity_view
          settings:
            view_mode: standort
          group_column: target_id
          group_columns: {  }
          group_rows: true
          delta_limit: 0
          delta_offset: 0
          delta_reversed: false
          delta_first_last: false
          multi_type: separator
          separator: ', '
          field_api_classes: false
          plugin_id: field
      attachment_position: after
      displays:
        standorte: standorte
      footer: {  }
    cache_metadata:
      max-age: -1
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - 'user.node_grants:view'
        - user.permissions
      tags:
        - 'config:field.storage.node.field_ansprechpartner'
  standorte_kurzbeschreibung:
    display_plugin: attachment
    id: standorte_kurzbeschreibung
    display_title: 'Standorte Kurzbeschreibung'
    position: 3
    display_options:
      display_extenders: {  }
      display_description: ''
      displays:
        standorte: standorte
      footer: {  }
      defaults:
        footer: false
        header: false
      header:
        entity_block:
          id: entity_block
          table: views
          field: entity_block
          relationship: none
          group_type: group
          admin_label: ''
          empty: false
          tokenize: true
          target: unternavigation_unternehmen
          view_mode: default
          bypass_access: true
          plugin_id: entity
    cache_metadata:
      max-age: -1
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - 'user.node_grants:view'
        - user.permissions
      tags: {  }

```

The main structure is:

```
View:
  - Attachement before (standorte_kurzbeschreibung)
    node--view--standorte--standorte-kurzbeschreibung.html.twig
  - Page (standorte)
    node--view--standorte--standorte.html.twig
  - Attachment after (standorte_ansprechpartner)
    node--view--standorte--standorte-ansprechpartner.html.twig

```

When enabling cache, drupal uses same node template (both are set to display rendered node) for attachement before and page rows. The templates are using default suggestion hooks `node--view--view-id--display-id.html.twig`.

Also the configured block (footer\_block) uses the same template when enabling cache.

Any suggestion how to solve this?

# Answer
The answer is simple and possible a bit unfortunate for you.

Do not use node--view-\* templates. They are broken.

See this core issue here. The problem is that fixing it would result in a performance regression for other sites that do not use that feature; as more cache variations have to be stored if the same node is displayed in multiple views.

Instead of that, use a unique view mode for your view that you can address as a template through that.
> 15 votes

# Answer
We ended up working around this issue by creating a new content "display" mode called "Topper" (like a Teaser, but call yours whatever you want).

This allowed us to create a Twig template for that new Display using the `node--type--topper.html.twig` hint, instead of the `node--view--view-id--display-id.html.twig` hints.

Then we set the specific View to use that Display for the output (instead of, say, the Teaser), instead of themeing the View.
> 0 votes

---
Tags: views, theming, 8
---


# Question
Title: perform a calculation inside a view and retain the value calculated to be used in the next row for the view
Im using drupal views. I have created a view with and inside the view i need to perform some calculations on each field inside the view. for example I have a beginning balance, payment, ending balance. I need to retain the ending balance in the first row and replace beggining balance on the next row. Thanks everyone in advance

Cheers

# Answer
> 1 votes
There are two approaches to balance calculation like this: 1) on-the-fly, or 2) maintaining the values separately in the database. It sounds like you're trying to build these values on-the-fly (every time the View is rendered, they are recalculated dynamically). This is the simpler approach of the two, but you may run into performance issues if you are trying to render a large amount of results. Approach #2 is essentially a form of caching for the balance - and thus comes with all the complexity of caching (ie: invalidating certain values if one in the past is changed, etc).

Assuming you want to stick with approach #1, there are two sub-approaches - aka two possible places to do the balance calculation: 1a) in the SQL query, or 1b) in PHP.

1a: It's possible to build these "balance" fields in the SQL query itself using a sub-query field that adds up all the payments up to the date of the current payment. In order to achieve this in Views, you would need to create a custom Views field handler that adds the subquery field.

1b: Using PHP and one of the hook\_X\_alter() functions that Views provides, it's possible to alter the values of fields AFTER the database query runs, and BEFORE it gets rendered on the page. This previous answer might help: How to alter single custom field value in views?

---
Tags: views
---


title: Button in form not working properly

text:
# Question
Title: Button in form not working properly
I am unable to get a button to work as I intend it to in Drupal 7.

I am adding the button to the add content page of a specific content type using form alter:

```
function charlie_get_form_article_link_node_form_alter(&$form, &$form_state, $form_id) {

    $form['add_button'] = array(

        '#type' => 'item',

        '#markup' => '
            <script>
                function getArticleInfo() {
                    jQuery.get("articlegrabber.php?url=TEST", function(articleHTML) {
                        console.log(articleHTML);
                    });
                    return false;
                }
            </script>

            <button type="button" onclick="getArticleInfo()">
                Submit URL
            </button>

        ',

    );

}

```

I have simplified the articlegrabber.php file down to just this (though I don't think it matters, because the button click does not seem to be executing the JS):

```
<?php

$ogLink = $_GET['url'];

echo $ogLink;  ?>

```

Instead of my intended results (which the code delivers independent of its implementation in Drupal), the console logs the HTML for the add content page that the button is on.

I have read a lot about how Drupal likes to make all button types "submit", but my button is actually rendering as type="button". The HTML from the rendered page (as you would expect):

```
                    <script>
                        function getArticleInfo() {
                            jQuery.get("articlegrabber.php?url=TEST", function(articleHTML) {
                                console.log(articleHTML);
                            });
                            return false;
                        }
                    </script>

                    <button type="button" onclick="getArticleInfo()">
                        Submit URL
                    </button>

```

Any ideas about how to get it to execute the code on click rather than returning the HTML for the page would be much appreciated.

# Answer
> 1 votes
You need **Simple Drupal AJAX load with jQuery and delivery callback** which is explained in 5 simple steps this page.

So include a anchor link through the form alter and have the link render the content through attached javascript file through `jQuery.load()` function.

To attach js file,

```
$form['#attached']['js'][] = array(
  'data' => drupal_get_path('module', 'module_name') . '/some_file.js',
  'type' => 'file',
);

```

For Drupal ajax forms refer this official documentation.

---
Tags: forms, javascript
---


# Question
Title: Preprocess views view to concat two dates and add variable
I've been trying to get a custom format placed upon a date range with particular rules (Explained in code comments) within Drupal 8 views.

What I currently have worked with regard to me being able to get the original two dates and to customize them but what I can't seem to do is pass the result ($display\_date\_range) forward to the **fields view** TWIG file (views-view-field--group-travel.html.twig)

What I have so far

```
/*****************************************************************************
 * VIEWS VIEW PRE-PROCESS
 * @param $variables
 *****************************************************************************/
function cazloyd_preprocess_views_view(&$variables) {
  $view = $variables['view'];
  $id = $view->storage->id();

  // Handle the Group Travel Listing view
  if($id == 'group_travel_listing'){
    foreach ($view->result as $key => $result){
      // Get start date from view
      $date_start = $result->_entity->get('field_start_date')->getValue();

      // Get end date from view
      $date_end = $result->_entity->get('field_end_date')->getValue();

      $months_are_same = (date('n', strtotime($date_start[0]['value']))==date('n', strtotime($date_end[0]['value'])))?TRUE:FALSE;

      if($months_are_same){
        // Month of start and end date are same, show only the day part of the start date
        // e.g. 11 - 23 July 2017
        $formatted_date_start = date('j', strtotime($date_start[0]['value']));
      }else{
        // Event crosses over into new month, therefore show day and month part of start date
        // e.g. 11 July - 5 August 2017
        $formatted_date_start = date('j F', strtotime($date_start[0]['value']));
      }

      $formatted_date_end = date('j F Y', strtotime($date_end[0]['value']));

      // Build final date range
      $display_date_range = $formatted_date_start . ' - ' . $formatted_date_end;

      echo '<pre>';
      print_r($display_date_range);
      echo '</pre>';
    }
  }
}

```

# Answer
> 1 votes
`hook_preprocess_views_view()` is used to alter the variables that are passed to a `views-view[...].html.twig` template file which is for the entire View, not just for the fields. It might make more sense for you to use `hook_preprocess_views_view_fields()` or `hook_preprocess_views_view_field()` since you are trying to alter the variables that are used in a `views-view-field[...].html.twig` template file (specific to the individual field, not the whole view).

See:

https://api.drupal.org/api/views/theme%21theme.inc/function/template\_preprocess\_views\_view\_fields/7.x-3.x

https://api.drupal.org/api/views/theme%21theme.inc/function/template\_preprocess\_views\_view\_field/7.x-3.x

---
Tags: views, 8, hooks
---


# Question
Title: Templating. Check if entity is comment or node?
I'm modifying a template file for an Advanced Forum sub theme. AF uses a single template to theme both nodes AND comments with the same markup. I need to add a php check inside the node template to see if the current entity is a node or a comment, then print some flags based on the result.

I don't think there is a straight forward $entity\_type variable to check, so how would I go about writing this?

# Answer
> 3 votes
Assuming this is for Drupal 7, there isn't an official way to do this, unfortunately. See core issue: https://www.drupal.org/node/1042822

One possible workaround is to check if the entity has some known fields that you are aware of. This obviously wouldn't be a generalized solution - but might work for you.

---
Tags: theming
---


# Question
Title: How to customize the homepage title without creating new pages?
I can set up my page like this and it works fine:

```
somepage:
  path: '/my_page'
  defaults:
    _title: 'My custom page title'
    _controller: '\Drupal\my_module\MyController::content'
  requirements:
    _permission: 'access content'

```

BUT I need the `path` to be empty, so I tried this: `path: '/'` \- not working. What I need is to be able to customize default homepage title of drupal 8 (without having to create new pages).

Tried `path: '/'` `path: /` `path: ''`. No success.

Any suggestions?

# Answer
By default the homepage for D8 is set to `/node` (similar to D7).
And unlike Drupal 7, this is a view. So, adding a title is as simple as adding the title to the view. (Views in core, yay!)

1. Go to `/admin/structure/views/view/frontpage`.
2. Add title to the view
3. Save

It is as simple as that!
If you save any other page as your homepage, then you could set the title to the route as you have already specified in the question.
> 8 votes

# Answer
Use Metatag module to set home page title

> The Metatag module allows you to automatically provide structured metadata, aka "meta tags", about a website. In the context of search engine optimization, when people refer to meta tags they are usually referring to the meta description tag and the meta keywords tag that may help improve the rankings and display of a site in search engine results.
> 2 votes

# Answer
Adding a title to the view works fine for customizing the page title.

But there is one more problem as the Navigation Menu entry "Home" is not editable. So I went again in the view settings and created a "Normal menu entry" with my custom tile. Then I edited the Navigation Menu settings and to disable the original "Home" menu entry and now I have the custom "Home" menu entry.
> 1 votes

# Answer
I was having the same problem and it worked for me. I went to the url alias and saw that the front page was node 1. If it is not I sugeste to go there and discover what node is. Then change the title property.

admin/config/search/path

I hope that help for some of us.

Best regards
> 1 votes

---
Tags: 8
---


title: Products with 2 different titles

text:
# Question
Title: Products with 2 different titles
Is it possible for a product to have 2 different titles. One would be displayed on full product page and the other shorter one on a grid product catalog.

# Answer
Yes, a product can have two different titles.

You can add fields to products on the product type admin screen (`/admin/commerce/config/product-types`) by choosing the appropriate product type and selecting *manage fields*. I would add a **text (plain)** field and call it *short name* or something like that.

Then, you can configure the display settings for the product type to hide the *short name* field (disable it), ensuring only the full title is shown on the product page.

Then, in your grid product catalog, configure your view (or whatever you use to make the catalog) to show only the short name, not the title field.
> 1 votes

---
Tags: commerce
---


# Question
Title: Creating a Slider paragraph type, how do I manage tabs "on the fly" within that?
I'm creating a `paragraph type` that represents a Slider. It has a couple of simple fields like "title" and "subtitle". It also has a *variable number of tabs*. The tabs are where the real content is.

Tabs have a title, and a variable number of entity references (to Movies, Characters, etc.). The entities all have an image and link associated with them so a user can click through to the entity's page. I created a `taxonomy` for Tabs and it has a two fields: the title and a list of Entity references.

Essentially there is a hierarchy: Slider contains tabs, tabs contain entities like Movies.

So in the end, the Slider `paragraph type` has a list of `taxonomy` tabs. The problem I have now is that the UI for adding a Slider to a page shows only the Slider's title fields and a list for the tabs *as references* to existing instances of a tab.

That is, a tab needs to be created *beforehand* in a separate tab taxonomy UI before it can be referenced in the Slider's properties.

My question is: **Is there a way to change the form UI to create instances of a Tab taxonomy *on the fly*, while I am creating an instance of the Slider Paragraph type.** I would like to create a complete slider on one form without having to jump back and forth to another page to modify the tabs of the slider.

For clarification, here's a rough mock up of how the tabs are organized in a slider.

# Answer
The solution I found was to make the Tabs into a `paragraph type` as well, instead of `taxonomy`. This way the Slider paragraph type would have a reference to a Tab (or group of tabs) and within the UI form for inserting a Slider, it shows the tabs that make up the Slider, along with a form to populate each tab's data points and references in line. This was what I was looking for. A user now does *not* need to go to a separate screen to create a tab first, then attach it to a Slider object.
> 1 votes

---
Tags: taxonomy-terms, paragraphs
---


# Question
Title: Is it possible to have a dynamic route as configure module page?
I installed the SEO Checklist module and when I go the search in the Extend (admin/modules) page the module Configure page I don't see it, so I go the the module issue an create a new issue Add link to configure page to solve the problem, I thought at the end this will be very easy, the page exists (admin/config/search/seo-checklist) so, is just search the route and add it to the .info.yml file.

But when I start to check the module files I see that the .info.yml file have the configure page defined with the same route that have as url admin/config/search/seo-checklist

```
configure: checklistapi.checklists.seo_checklist

```

So I start to dig a little in the code and I found that this route checklistapi.checklists.seo\_checklist is defined dynamically in the Checklist API module

```
  $routes["checklistapi.checklists.{$id}"] = new Route($definition['#path'], [
    '_title' => (string) $definition['#title'],
    '_form' => '\Drupal\checklistapi\Form\ChecklistapiChecklistForm',
    'checklist_id' => $id,
    'op' => 'any',
  ], $requirements);

```

I'm missing something here or is not possible to have a dynamic route as configure module page?

# Answer
> 1 votes
It is possible to use any route for the configure link, as long as all route parameters are satisfied (parameters can be specified via `configure_parameters`).

In the case of the above bug, the access check was failing, preventing the link from displaying.

The problem was solved in: ChecklistapiAccessCheck looks in the wrong place for 'checklist\_id' and 'op'

---
Tags: 8, routes
---


# Question
Title: Stuck with Drush on OS X with AMPPS and Homebrew
I am setting up a new development environment on a local machine and am using AMPPS. I have installed Drush using Homebrew and am running a Mac (OS X 10.12.5 Sierra).

I have successfully installed a fresh Drupal site in my development environment. When I attempt to run a drush command, I get the Drush status along with the classic bootstrap/jailed shell message:

```
Command pm-list needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal[error]
environment to run this command.
The drush command 'pm-list' could not be executed.                                                                 [error]
Drush was not able to start (bootstrap) the Drupal database.                                                       [error]
Hint: This may occur when Drush is trying to:
 * bootstrap a site that has not been installed or does not have a configured database. In this case you can select
another site with a working database setup by specifying the URI to use with the --uri parameter on the command
line. See `drush topic docs-aliases` for details.
 * connect the database through a socket. The socket file may be wrong or the php-cli may have no access to it in a
jailed shell. See http://drupal.org/node/1428638 for details.

```

Here is the output of `drush status`:

```
Drush was attempting to connect to:
 Drupal version         :  7.54
 Site URI               :  http://default
 Database driver        :  mysql
 Database hostname      :  localhost
 Database port          :
 Database username      :  myuser
 Database name          :  drupal
 PHP executable         :  /Applications/AMPPS/php-5.6/bin/php
 PHP configuration      :  /Applications/AMPPS/php-5.6/etc/php.ini
 PHP OS                 :  Darwin
 Drush script           :  /usr/local/Cellar/drush/8.1.15/libexec/drush.php
 Drush version          :  8.1.15
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  /Applications/AMPPS/www/drupal/docroot
 Drupal Settings File   :  sites/default/settings.php
 Site path              :  sites/default

```

Please note:

* I have tried changing localhost to 127.0.0.1 in `sites/default/settings.php` and restarting the server
* I added the path to drush to php via `export DRUSH_PHP=/Applications/AMPPS/php-5.6/bin/php`
* I am executing the command within the docroot of the drupal installation
* I do not have a `~/.my.cnf` file
* symlink in `/usr/local/bin` for PHP goes to Homebrew's instead of AMPPS's but it's for version 7.1.10 and I'm using PHP 5.6

There are a lot of posts on this with slightly different details or environments and I'm having no luck deriving a solution from those so I thought I would post my issue with the specific scenario.

I mostly used these instructions: https://www.drupal.org/node/954766

# Answer
> 3 votes
Even though I did export the Drush PHP path, I had not added the link to AMPPS' mysql bin in .bash\_profile. That solved my issue.

```
nano ~/.bash_profile
export PATH=$PATH:/Applications/AMPPS/mysql/bin
source ~/.bash_profile

```

# Answer
> 0 votes
You might need to specify the path to Drush

I had

export PHP\_ID="php-5.6"

export PATH="/Applications/AMPPS/$PHP\_ID/bin:/Applications/AMPPS/mysql/bin:/Users//.composer/vendor/bin/drush:$PATH"

there is good info here Stuck with Drush on OS X with AMPPS and Homebrew

---
Tags: 7, drush
---


# Question
Title: How to customize Commerce order admin view
I would like to customize the Commerce order admin layout, the tables shown when admin clicks View or Edit in the Orders table.

These pages are typically shown on the following URLs: yoursite/admin/commerce/orders/order\_id/view and yoursite/admin/commerce/orders/order\_id/edit where order\_id is a number.

I want to add a custom column (a field from my product content type) to these tables. I have searched all the views which were created automatically when I installed Commerce but wasn't able to find the one which is rendering these pages.

# Answer
> -1 votes
***In Drupal 7, Commerce 1 (7.x-1.x)***

1. For the actual individual order page, you'll want to edit the view entitled "Line items (Commerce Line Item)"

Bear in mind however, the column you add may cause errors if the field only exists for some product types and not others. You might need to add an additional relationship to the view to get the field of data.
2. For the actual order summary page found at /admin/commerce/orders, you'll want to edit the "Orders" view. You'll probably need to add a relationship for *Commerce Order Line Items*.

---
Tags: commerce
---


# Question
Title: How to change the default search button value in awesome zymphonies free theme?
please have a look at the site, http://35.187.238.51/jrdtml/. This is a prototype site of the library I'm working for. I'm using Drupal 8.4 with Awesome Zymphonies free theme. I would want to change the text in the default Search box from 'Search' to 'Site Search'. Also I would like the Search box to appear in different pages other than just the Home page.

Thanks for your attention.

Best, Francis

# Answer
> 0 votes
**How to override the search text string**

For how to change the text of the search box, you'll need to do a string override. See the answer to this question on how to write your own custom module to do this.

Drupal also has a String Overrides module so that you don't have to write your own code, but it's not ready for Drupal 8 yet. There is a test version here but it's not safe for production sites.

A third way to do this-- and perhaps the easiest approach if you will be changing lots of Drupal interface text-- is to add "English" as a translatable language on the language settings page (`admin/config/regional/language`) and then disable the original "English." What this allows you to do is "translate" any text that appears in the Drupal UI.

**How to show the search box on other pages**

The search box is (most likely) a block that can be controlled on the block administration page: `/admin/structure/block`.

You can edit the block settings to choose which pages it appears on. You can also place additional search blocks and then edit the settings to show them in different places on different pages.

---
Tags: search
---


title: Product status defaulting to disabled

text:
# Question
Title: Product status defaulting to disabled
I am having a weird issue from one of our client web sites. When a user goes to add a product through the /admin/commerce/products/add/product, the status form field isn't rendered (by design). The database sets the default value to 1 (active) however when the user adds the product it sets the status to "Disabled".

I have looked all around and I can't figure out how this is being changed. Any ideas where I should be looking to fix this issue?

# Answer
There's no telling without seeing the code you've used to hide the status field. My bet is the way you've hidden it is causing the form system to interpret the absence of a value as the disabled status, given PHP would treat both a 0 value and a NULL value similarly.
> 0 votes

---
Tags: commerce
---


# Question
Title: How can I programmatically unselect "View published content" checkbox for anonymous users?
I am using Drupal 8. I want to programmatically unselect the *View published content* checkbox for anonymous users.

>

How can I achieve this?

# Answer
> 2 votes
You have to insert this code in a hook\_install() or hook\_update() :

```
$role = \Drupal\user\Entity\Role::load('anonymous');
$role->revokePermission('your_permission');
$role->save();

```

---
Tags: users
---


# Question
Title: Page redirect in custom WebformHandlerBase
I have written a custom WebformHandlerBase and attached it to the Mulitpage webform. With this I'm able to get the values into the custom handler as soon as user clicks on Next Page\> button

```
class MyFormHandler extends WebformHandlerBase {
     public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {

         $form_id = 'webform_submission_' . $webform_submission->getWebform()->id() . '_form';

         if($form_id == 'webform_submission_registration_content_form') {
            $values = $webform_submission->getData();
            /* custom code to calculate the score based on the values */
             $eligible_to_participate = 1;
             if ($score >= x && $score <= y) {
                  $eligible_to_participate = 1;
              }
             else
             {
                 $eligible_to_participate = 0;
             }
             if($eligible_to_participate == 0) {
                  // This user is not eligible so redirect to 'finish page'
                  /* The below code is not working
                   * how-ever the same code is working in hook_form_FORM_ID_alter()
                   */
                  $url = Url::fromRoute('entity.node.canonical', ['node' => 78]);
                  $response = new RedirectResponse($url->toString());
                  $response->send();
              }
          }
      }
 }

```

Based on the user selected values I need to redirect the user to a different page and the code for doing the same is as follows

```
 use Drupal\Core\Url;
 use Symfony\Component\HttpFoundation\RedirectResponse;

 $url = Url::fromRoute('entity.node.canonical', ['node' => 78]);
 $response = new RedirectResponse($url->toString());
 $response->send();

```

Now the problem is, this code is not working in custom handler function. If I write the same code in hook\_form\_FORM\_ID\_alter() it is working fine.

Any idea where am I doing wrong? Any help much appreciated.

# Answer
Example for a webform handler plugin redirecting:

```
<?php

namespace Drupal\sa_webform\Plugin\WebformHandler;

use Drupal\Core\Form\FormStateInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\webformSubmissionInterface;

/**
 * Form submission handler.
 *
 * @WebformHandler(
 *   id = "my_webform_handler",
 *   label = @Translation("My webform handler"),
 *   category = @Translation("Webform Handler"),
 *   description = @Translation("Calculate the score with webform submissions"),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_SINGLE,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 * )
 */

class MyWebformHandler extends WebformHandlerBase {

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {
    $form_id = 'webform_submission_' . $webform_submission->getWebform()->id() . '_form';
    if ($form_id == 'webform_submission_xxx_form') {
      $values = $webform_submission->getData();
      /* Take the action based on the Webform submission values */
    }
  }

  /**
   * {@inheritdoc}
   */
  public function confirmForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {
    $form_id = 'webform_submission_' . $webform_submission->getWebform()->id() . '_form';
    if ($form_id == 'webform_submission_xxx_form') {
      if (based_on_some_condition) {
        /* Here 12 is the node id where i wanted to redirect to */
        $form_state->setRedirect('entity.node.canonical', ['node' => 12]);
      }
    }
  }

}

```

For more examples refer webform modules src code located at webform\src\Plugin\WebformHandler

BrokenWebformHandler.php

DebugWebformHandler.php

EmailWebformHandler.php

RemotePostWebformHandler.php
> 8 votes

---
Tags: 8, webforms
---


# Question
Title: Right way to update a drupal distribution?
I have a site which is a Commerce Kickstart distribution.

My distribution version is 7.x-2.0-rc1 and now the 7.x-2.0-rc2 version is available.

How do I update a distribution? I tried these method (both failed...)

1) I follow the update standar process using the drupal ui. I get this error message:

```
>     Notice: Undefined index: version_major in update_calculate_project_update_status() (line 595 of
> /Applications/MAMP/htdocs/mySite.com/modules/update/update.compare.inc).
>     Downloading updates failed:
>
>     commerce_kickstart-7.x-2.0-rc2-core.tar.gz does not contain any .info files.
>     Notice: Undefined index: version_major in update_calculate_project_update_status() (line 595 of
> /Applications/MAMP/htdocs/mySite.com/modules/update/update.compare.inc).

```

2) I downloaded the distribution and replace the folder mysite.com/profiles/commerce\_kickstart This didn't work neither.

¿Which is the right way to to do this?

# Answer
> 8 votes
You should try it with drush.

```
drush dl commerce_kickstart
drush updatedb -y

```

(I have not tried it for commerce kickstart; I just got the answer on drupal.org.)

# Answer
> 5 votes
Commerce Kickstart has a documentation page explaining how to install or update the distribution: http://www.drupalcommerce.org/commerce-kickstart-2/install. It is linked from the project page on drupal.org.

The updater inside Drupal can't update distributions (or Drupal core itself), so it can't work for Kickstart.

# Answer
> 2 votes
Although "drush pm-download" should work, there is an initiative to have this work with "drush pm-updatecode" as well. See the issue on Github Drush up should update contrib profiles as well for details.

At the time of this writing, there's nothing available for use, but hopefully there will be usable code soon. Feel free to contribute to the thread so that we can get this done faster.

# Answer
> 1 votes
**Eleven steps to upgrade a Drupal 7 distribution:**

1. Backup and/or Test locally
2. Read the Release Notes
3. Maintenance / Off-line Mode
4. Copy Sites Folder
5. Delete Existing Files
6. Downloading Updated Distribution Code
7. Restore Sites Folder
8. Run Updates
9. Revert Features
10. Clear Cache
11. Disable Maintenance Mode / Go On-line

Source and details into this official documentation at https://www.drupal.org/docs/7/distributions/maintaining-sites-built-with-distributions#update-distribution

---
Tags: updating, distributions
---


title: Checkbox in views

text:
# Question
Title: Checkbox in views
How to bring the input type as check box for a field .

I ve used Global:Custom Text and in that field I gave like this in text

```
<div class="cmp-button"><input type="checkbox" name="product-compare" value="123"> Compare</div>

```

but i din get the check box .. any solution please

# Answer
you need to install Views PHP module then go to your view and add global PHP field then add your code it will work
> 0 votes

# Answer
I dont see how placing a checkbox in a text field will help you?

If you need people to be able to edit nodes directly from a views output, then try the editable fields module.

In the content type, add a CCK boolean or list field with your options, then add that field into your view, and format the field as "editable".

That field can now be changed directly in the view, and can save automatically with ajax if you wish.
> 0 votes

# Answer
I believe you want to use check boxes for multiple operation(s). You can do that with Views Bulk Operation module, install and add field **bulk operations** in views.
> 0 votes

---
Tags: views
---


# Question
Title: How can I remove an entry from the blog front page?
If you enable the **Blog** core module in D7, you have a multiuser blog. It will produce a *blog front page* for all blog entries published at the path `/blog`. It is just like the ordinary front page `<front>`, but only show nodes of type "blog". By default, all published blog nodes appear on the blog front page.

For the site's default front page there is checkbox "Promoted to front page" under "Publishing options". Unchecking that prevents the node from appearing on the default front page.

Adding a similar checkbox field named "Promoted to blog front page" to the "blog" content type will of course do nothing by itself.

I want to use this field to control whether a blog node appear on blog front page, but have not found a "hook" or a "preprocess-function" or similar Drupal-thing that let me do so with the view of blog teasers that the core blog module produces.

I know I can do this by replacing the blog core module with my own, using **Views** to produce the list of teasers for the blog front page.

But in this question, I am looking for a way to do this with the view produced by the core blog module?

Is this possible, or must I use **Views** if I want this?

# Answer
The blog module builds this page in the function `blog_page_last()`.

The query in `blog_page_last()` does have a `node_access` tag so you could use `hook_query_TAG_alter()` to add a condition but may be tricky to just target that one query on that page.

I think a better option would be to use `hook_menu_alter()` to change the callback for the `blog` menu item to a function in your own module. In this function you can just copy the code from `blog_page_last()` but add a additional condition for your new promoted field.
> 3 votes

---
Tags: 7, nodes
---


# Question
Title: Help with db_delete using both LIKE and IN.. I'm trying to delete many rows whilst having a wildcard
I'm writing a custom cache clearing module for blocks.

At the moment, I can delete cache for one user and their multiple languages.

```
$uid = 7094;
$module = 'custom_home_panes';
$block = 'custom_home_panes_news_group';
$theme = 'framework';
$table = 'cache_block';

$cid_start = $module . ':' . $block . ':' . $theme . ':';
// Wildcard in middle for language code
$cid_end = ':u.' . $uid;

$delete = db_delete('cache_block')
  ->condition('cid', db_like($cid_start) . '%%' . db_like($cid_end), 'LIKE')
  ->execute();

```

But I'll need to do this for an array of UIDs and I believe I need to use IN like the snippet below..

```
->condition('uid', array(1,5,7),'IN')

```

I thought I could add what I did to an array and got this far.. The LIKE is really confusing me here and I think I'm going about it the wrong way.

```
foreach ($uids as $uid) {
    $queries[] = db_like($module . ':' . $block . ':' . $theme . ':') . '%%' . db_like(':u.' . $uid), 'LIKE';
}

```

The end result should be a query that removes records such as the ones below.

```
custom_home_panes:custom_home_panes_news_group:framework:vi:u.7250
custom_home_panes:custom_home_panes_news_group:framework:en:u.7250
custom_home_panes:custom_home_panes_news_group:framework:vi:u.7253
custom_home_panes:custom_home_panes_news_group:framework:en:u.7253

```

Any help appreciated.. My SQL skills are abysmal. Thanks!

# Answer
You can't combine LIKE and IN in the way you are attempting.

You will need a run a different query for each UID.

E.g.

```
$cid_base_pattern = db_like($module) . ':' . db_like($block) . ':' . db_like($theme) . ':%:u.';

foreach ($uids as $uid) {
    db_delete('cache_block')
      ->condition('cid', $cid_base_pattern . $uid, 'LIKE')
      ->execute();
}

```
> 2 votes

---
Tags: database, caching
---


# Question
Title: Field collection fields are empty in edit mode
### Problem

My content type has several fields and one of them is a field collection. Currently I have following issue: After adding and saving content everything is displayed fine. When editing, the contents of the field collection are all empty, but are saved in the database. After adding the same contents in the empty field collection and saving, when editing again the values are displayed.

So I do really not understand why this append, maybe someone can help me understand it and fix the bug.

P.S.: Please forgive my English (still learning).

# Answer
> 0 votes
I've experienced this a while ago with field collections and paragraphs but can't remember the exact cause. Suggestions for troubleshooting:

1. Check to make sure there's no updates available for the field collection module, Drupal Core, or any other modules that may be impacting the types of fields you're trying to assign in your field collection.
2. If your field collection involves an entity reference to either:
    * another node and allows creation of said node within the edit form, make sure to click save on the embedded node creation form before saving the overarching node.
    * a file upload, make sure to upload the file before clicking save on the overarching node.

If this still doesn't work, try creating the field collection from scratch, adding one field at a time to determine which one is causing the issue.

---
Tags: 7, entities
---


# Question
Title: How can an existing user login to check on previous orders?
I see where an existing customer can login during the checkout process for a new order. But where can they login to check on existing orders? Or is that even possible?

I tested and it appears that the Drupal site logon is not the same as the Commerce customer login.

# Answer
> 1 votes
The Drupal site login and Commerce login are definitely the same; check the login details again.

Commerce 2 supports checking the details of orders out of the box.

It adds an "Orders" tab to the user profile (`/user/UID/orders`), and a view (that you can customize if you like) is provided to display the order history (`/admin/structure/views/view/commerce_user_orders/edit/order_page`).

---
Tags: commerce
---


# Question
Title: Which tables and which data can I omit from backup?
Which tables and which contained data can I omit from SQL backup?

There seem to be many different answers to this around Internet, but most answers do not make it clear whether they are specifying that tables can be omitted or the data *in* the tables. My guess is it comes down to knowing which modules are robust and will re-create their own empty tables if they aren't there.

Without knowing the code innards of *every* module that is a possible candidate for omission, is there a good answer to the question?

At the moment, my intention is to start with the default lists built into Backup and Migrate; for anything else, I think could be omitted then omit the data from such tables not the table itself (playing safe). It *could* be something published in the documentation for a module but I don't think it is. Is there a completely definitive list somewhere?

It's very confusing seeing lists of "you can omit these" without knowing whether it's referring to the tables or their content.

# Answer
> 0 votes
You can omit the data from some tables. **You cannot omit the actual table creation.**

Tables for modules are created in one of two ways. Either when the module is first enable via hook\_schema or when an update hook (hook\_update\_N) runs. Tables in hook\_schema are only created when the module is first enabled. After an update hook is run the system table is updated with the schema version so it's not run twice.

You can't expect modules (or core) to just recreate tables that they expect to exist but are missing on the fly. It's nothing to do with being robust - this is just how Drupal works. Also it would be very inefficient to check a table exists before running every query. You would be doubling the number of queries you have to run. This would be crazy!

If you have any missing tables you would need to disable, uninstall and then re-install the module to fix it.

This question has suggestions of which which tables contain data that can be excluded.

---
Tags: 7, backups
---


# Question
Title: How to get the Commerce Product type from the order object. D7
I am unable to find the product type when looking at the order object. I have tried

```
commerce_order_load($order_id);

```

This does not give the product type and neither does

```
commerce_line_item_load();

```

I have also looked for a function to achieve this here but can't see anything to achieve this.

I am able to get the line item type it seems but not the product type, seems odd

# Answer
> 0 votes
You would need to load the product to be able to see the product type as this is not a property of the order or the line item.

For example (using entity metadata wrappers):

```
$order = commerce_order_load($order_id);
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
foreach($order_wrapper->commerce_line_items as $line_item) {
  $type = $line_item->commerce_product->type->value();
  dpm($type, '$type');
}

```

Here is an example without using entity wrappers:

```
$order = commerce_order_load($order_id);
foreach($order->commerce_line_items[LANGUAGE_NONE] as $li) {
  $line_item = commerce_line_item_load($li['line_item_id']);
  $product = commerce_product_load($line_item->commerce_product[LANGUAGE_NONE][0]['product_id']);
  $type = $product->type;
}

```

# Answer
> 0 votes
I ended up just querying the database, here is what worked for me

```
$product_type = db_select('commerce_product', 'cp')
    ->fields('cp', array('type', 'product_id'))
    ->condition('cp.product_id', $product_id, '=')
    ->execute()
    ->fetchAll();

```

---
Tags: 7, commerce
---