# Question
Title: What are the features of the Group module versus Organic Group module?
To create groups in Drupal we have at this moment the Group module and the Organic Groups module.

From the Group module page:

> The Group module allows you to create arbitrary collections of your content and users on your site and grant access control permissions on those collections

From the Organic Group module page:

> Enable users to create and manage their own 'groups'. Each group can have subscribers, and maintains a group home page where subscribers communicate amongst themselves.

What are the features of Group versus Organic Group?

# Answer
# About

The Group module allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also. It is designed to be an alternative to Organic Groups.

**Organic Groups** allows content itself to be groups, which isn't always what people want. It relies on an entity reference field to keep track of the ties between a group (node, term, ...) and its content (node, term, user, ...)

**Group** instead creates groups as entities, making them fully fieldable, extensible and exportable. Every group can have users, roles and permissions attached to it (refer to "What are the various roles supported by the Group module?" for more details about that). Groups can also act as a parent of any type of entity. Group provides an extensive API to attach entities to groups.

# Advantages of Group as compared to OG

* **Group** started in D7 only, taking full advantage of entities introduced in D7.
* **Group** doesn't 'abuse' nodes by adding custom fields to them in order to make the module work.
* **Group** does not allow you to have per-group roles or permissions. These are instead defined on the group type. So group types, group roles and permissions are configuration instead of content. Because of this approach, group types and roles exportable (with or without Features).
* **Organic Groups** is commonly perceived as a huge module, which carries a lot of "legacy" from pre-D7 releases and makes it tougher to ever get upgraded to D8.
* A D8 version of **Group** is already available (not so for Organic Groups).

# Disadvantages of Group as compared to OG

* As of today, **Group** only has alfa / beta releases (not any official release).
* Even though some say it is self documenting, I think it is not (maybe because I don't want to digest the source code to find out what this module can do ...).
* Not a lot of documentation available.
* As of today, there is no tag on drupal.SE, though there is an tag, and there are already quite a few Group specific questions. Anybody interested in creating it (again), feel free to reuse my previously approved tag wiki and/or tag excerpt (no need for credits ...).

# Integration with various modules

The Group module integrates with various other (popular) modules, including:

The beauty, IMO, of these integrations are that they are more or less out-of-the box (not dozens of extra modules needed to make those integrations work).

Refer to Integrations with other modules and its "Related issues" about other modules for which integrations already exist, or are in the pipeline.

# Resources

# What people say about the Group module

Similar to what you see in the **Group** issue queue: most (if not all) people who know about **Group** just love it ...
> 11 votes

# Answer
There is an article that comes from being published named: GROUP FOR DRUPAL

The author says about group:

* Simple

> Groups should be like content types. I want different kinds of groups with different fields, roles and permissions. That’s exactly how Group handles it.

* Group content

> Basically anything you attach to the group can be fieldable. Another interesting thing about the relationship entity that sits between the group and the actual user/content is, that if you delete it from the Group interface, you are not deleting the content, but the linking entity instead, so the content (or user/entity/whatever) is left unchanged.

* Powerful

> Every group type has their own group content types and every one of them has configurable permissions and fields.
>
> Out of the box, Group integrates with Views, Rules, i18n, Title and I’m sure much more is coming. Built on top of Entity, API Group provides all of its benefits to developers.

And as conclusion:

> There is no doubt that Group is here to take the place of OG. It has everything that OG provides plus all the things that were missing. All brought in a neat UI, where you can configure so much without being a coder.
>
> The only downside of Group I can think of currently is the state of the module. It’s currently marked as alpha, but seeing the growing number of contributors and downloads can only mean the development speed is increasing. It’s also hard to expect finding a lot of answers online, because Group is a very young module. Nevertheless, given very good response rates on the module’s issue queues I would say that writing a ticket is your best bet if you need any help.

**EDIT:** Another god article to read is: Building Community Sites in Drupal 8: A Guide To D8 Modules For Community Support Sites
> 5 votes

---
Tags: organic-groups
---


title: How do i setup PostgreSQL?

text:
# Question
Title: How do i setup PostgreSQL?
I am following https://www.drupal.org/node/1438206, but i got stuck at Point 2. i.e Add the bin directory of postgres, /Library/PostgreSQL/8.4/bin to the PATH in your .bashrc file in your home directory. Remember to run ./.bashrc to update the path.

I installed postgreSQL using brew. Now i do not find /Library/PostgreSQL/\*/bin path i.e I do not find PostgreSQL inside Library. Also i do not find .bashrc file .

I have installed postgreSQL for sure.Please help me out.

# Answer
I highly, highly suggest not installing these things directly to the operating system. It will just be more problematic instead of using a contained, virtual environment.

Instead, I advise using virtual environments (Vagrant/Docker). I use DrupalVM for development. For PostgreSQL you can see this thread for info on how to get it up and going.

Here is a Docker flavored VM with instructions on PostgreSQL support.

The linked drupal.org page you mentioned is four years old. I wouldn't follow it.
> 0 votes

---
Tags: database, installation
---


# Question
Title: upload picture and make it my css background-image
I want to upload picture and make it my CSS background-image in Drupal? Is it possible?

Please reply if you know how thank you!

# Answer
> 1 votes
You can do something like this:

```
hook_node_view($node, $viewmode, $langcode)
{
  if(count($node->field_background_image) && isset($node->field_backround_image[LANGUAGE_NONE][0]['uri']))
  {
    $node->content['#attached']['css'][] = array
    (
      'type' => 'inline',
      'data' => '#some_div{background-image:url(' . file_create_url($node->field_background_image[LANGUAGE_NONE][0]['uri']) . ');}',
    );
  }
}

```

# Answer
> 1 votes
If you have access to the File Manager there is another way doing this.

1.I would go to /sites/default/files and upload the image there

(because that's were a lot of image from drupal get uploaded)

2.Then go over to the style-sheet (/sites/all/themes/*CURRENT\_THEME*/css/style.css) through the file manager and edit it.
(*CURRENT THEME* being the folder of the theme you have active)

3.Add this code:

```
body {
background: url("http://www.intrawallpaper.com/static/images/abstract-mosaic-background.png");
background-color: #cccccc;
/* background color is there color it shows until the image loads or if a user has images disabled. */
}

```

Hope this helps.

---
Tags: theming, media
---


# Question
Title: Adding map with user location into the profile
I am trying to add a *'IPGV&M: Map (Google) centered on visitor's location' block* to all user profiles and I kinda succeeded. The map appears in the user profile, in the footer where i intended to have it, when I visit the user profile it asks if it can use my location. After clicking yes, I face couple problems:

1. It just shows a world's map from far far away without any marker on the location of a user
2. I have to make it so when visiting a user's profile I would be able to see where he/she is from in the map. If I use this method I talked about, doesn't it mean that when I visit someone else's profile I will be still seeing my own location? How to solve this problem?

# Answer
I'm no expert but try using the Location Module. It

> "..allows real-world geographic locations to be associated with Drupal nodes, including people, places, and other content"

God Bless.
> 0 votes

---
Tags: users, location
---


title: Batch operation doesn't get called

text:
# Question
Title: Batch operation doesn't get called
I am trying to write a batch. And I have a problem that none of the batch operations callback functions are getting called.

I wrote `drupal_set_message` at the start of each callback and none of the messages are displayed.

I can get the batch page, but the callback ops aren't called at all.

Here's the code I used:

```
function mymdoule_node_batch()
{
    $batch = array(
        'title'         => t("Migrating"),
        'operations'    => array(
            array('mycallback_001'),
            array('mycallback_002'),
        ),
        'finished'      => 'mycallback_finished',
        'init_message'  => t('Initializing...'),
        'error_message' => t('An error occurred.'),
    );

    batch_set($batch);
    drupal_set_message("step: 0"); // this is the only message the system returns
}

function mycallback_001(&$context)
{
    drupal_set_message("step: 1");
    $nids = db_select("node", "n")
            ->fields("n", array("nid"))
            ->orderBy("nid", "ASC")
            ->execute()
            ->fetchCol();
}

function mycallback_002(&$context)
{
    drupal_set_message("step: 2");
    $nids = db_select("node", "n")
            ->fields("n", array("nid"))
            ->orderBy("nid", "ASC")
            ->execute()
            ->fetchCol();
}

```

P.s. The batch is getting called in form submission.

What's wrong in that?

# Answer
It worked after I added `file` to the `$batch` array.

```
function mymdoule_node_batch()
{
    $batch = array(
        'title'         => t("Migrating"),
        'operations'    => array(
            array('mycallback_001'),
            array('mycallback_002'),
        ),
        'finished'      => 'mycallback_finished',
        'init_message'  => t('Initializing...'),
        'error_message' => t('An error occurred.'),
        'file'          => 'mypatch.ops.inc',
    );

    batch_set($batch);
    drupal_set_message("step: 0");
}

```
> 3 votes

# Answer
This Problem happens when we put our file in different folder like as includes/form\_test.inc.In this scenario batch function can't call.So to handle this we put 'file' =\> 'path\_to\_file\_containing\_myfunctions' in our submit function.

```
    $batch = array(
      'title' => t('Custom File uploader'),
      'operations' => array(
        array('test_feeds_import_form_batch', array($uri)),
      ),
      'progress_message' => t('Uploading Multiple Products...'),
      'error_message' => t('Error!'),
      'finished' => 'test_feeds_import_form_batch_finish',
      'file' => drupal_get_path('module', 'test') . '/includes/test_form.inc',
    );

    batch_set($batch);
    batch_process('admin/import-data'); //Work like as drupal goto

```
> 1 votes

---
Tags: 7, batch-operations
---


title: Batch operation not called

text:
# Question
Title: Batch operation not called
I am trying to write a Batch import to create nodes based on a uploaded file. The form works and I receive the file, and can read it in my submit callback which should initiate the Batch import. Here is the code:

```
function mymodule_import_submit(&$form, $form_state) {
  $xml = file_get_contents($form_state['values']['xml']->uri);

  $ads = xml2ary($xml);

  $batch = array(
    'title' => t('Importing Content ...'),
    'operations' => array(),
    'init_message' => t('Commencing'),
    'progress_message' => t('Processed @current out of @total.'),
    'error_message' => t('An error occurred during processing'),
    'finished' => 'mymodule_import_finished',
  );

  foreach ($nodes['nodes']['_c']['node'] as $new_node) {
    $batch['operations'][] = array('mymodule_import_create_node', array($new_node['_c']));
  }

  batch_set($batch);
}

```

While it seems to know the amount of operations needed (how many need to be created) my callback doesn't seem to get called. Here is its code:

```
function mymodule_import_create_node($new_node) {
  $clean_body = make_safe($new_node['CONTENT_BODY']['_v']);

  $node = new stdClass();
  $node->type = 'article';
  node_object_prepare($node);

  $node->title = substr(strip_tags($clean_body, 0, 20)) . '...';
  $node->body['und'][0]['value'] = $clean_body;
  $node->status = 1;
  $node->field_article_category = array();
  $node->field_article_location = '';
  $node->field_email_address = '';
  $node->uid = 1;

  node_save($node);

  $context['results']['articles_imported']++;
}

```

I put a few dumps at the start of the batch callback and it never exits. Watchdog indicates nothing, and no new nodes appear.

# Answer
> 3 votes
According to the Batch operations page on api.drupal.org, the processing function needs to have `$context` passed by reference.

Thus your import create node function should read `function mymodule_import_create_node($node, &$context)` and that should do it

Edit: sample code

# Answer
> 0 votes
You have to include node.pages.inc in your function to make node\_object\_prepare() work.

```
module_load_include('inc', 'node', 'node.pages');

```

# Answer
> 0 votes
This Problem happens when we put our file in different folder like as includes/form\_test.inc.In this scenario batch function can't call.So to handle this we put 'file' =\> 'path\_to\_file\_containing\_myfunctions' in our submit function.

```
$batch = array(
  'title' => t('Custom File uploader'),
  'operations' => array(
    array('test_feeds_import_form_batch', array($uri)),
  ),
  'progress_message' => t('Uploading Multiple Products...'),
  'error_message' => t('Error!'),
  'finished' => 'test_feeds_import_form_batch_finish',
  'file' => drupal_get_path('module', 'test') . '/includes/test_form.inc',
);

batch_set($batch);
batch_process('admin/import-data'); //Work like as drupal goto

```

---
Tags: 7, batch-operations
---


# Question
Title: Update a view page content without refreshing the page
Is there a module that updates a view automatically when it is changed, without refreshing the view page?

For example, when a new node is added to the view or deleted from the view, or a node is edited, the view is automatically updated without refreshing the page.

What is the best way to do this?

# Answer
The Views Hacks module (poorly named in my opinion) has an auto-refresh submodule that should accomplish this for you. You may want to also look at using the Views content cache module so that you can still enable caching on your view.
> 1 votes

# Answer
I've been trying to find the answer to this for some time and I don't think I can improve on the previous answer.... but I think it is not really correct.

The way I would approach it is to put more of the Views formatting functionality in some JQuery Javascript so that the Javascript fetched the data for the View from the Drupal server via JSON and not HTML.

Then periodically - rather than using Views Hacks autofresh - it would say "give me all the records for this view which are newer than this datetime"

Unfortunately this would require hand coding for now as I have not seen this in any contributed module.
> 2 votes

# Answer
You can use this module https://www.drupal.org/project/views\_refresh or just use the code below in your JS to refresh the view.

```
$('.view-dom-id-403402eee35f68cd32fe87b45702dc63').triggerHandler('RefreshView');

```
> 0 votes

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


title: Batch job not running callback

text:
# Question
Title: Batch job not running callback
I am trying to run a batch job of importing items from a csv file. When I click submit on my form and my batch process starts, I do get a batch process bar which says its progressing, but it never calls my callback function or my finished function. I've done a `dpm()` of th $batch array before I run it, and it seems to be in order. What am I missing?

```
$count = 1;
  while($count <= count($csv) ) {
    $operations[] = array('ons_institutional_subscriber_importer_import', array(array_slice($csv, $count, $count + 10)));
    $count = $count + 10;
  }
  $batch = array(
    'title' => t('Importing Institutional Subscribers'),
    'operations' => $operations,
    'finished' => 'ons_institutional_subscriber_importer_finished',
    'init_message' => t('Import is starting.'),
    'progress_message' => t('Processed @current out of @total.'),
    'error_message' => t('Import has encountered an error.'),
  );
  dpm($batch);
  batch_set($batch);
  batch_process();

```

and my callback functions

```
function ons_institutional_subscriber_importer_import($csv, &$context) {
  dpm('hello');
  //more code here...
}
function ons_institutional_subscriber_importer_finished($success, $results, $operations) {
  if ($success) {
    $message = format_plural(count($results), 'One post processed.', '@count posts processed.');
  }
  else {
    $message = t('Finished with an error.');
  }
  drupal_set_message($message);
}

```

# Answer
> 1 votes
This Problem happens when we put our file in different folder like as includes/form\_test.inc.In this scenario batch function can't call.So to handle this we put 'file' =\> 'path\_to\_file\_containing\_myfunctions' in our submit function.I wish this code will help you in understanding.you are missing 'file' in your batch array.

```
$batch = array(
  'title' => t('Custom File uploader'),
  'operations' => array(
    array('test_feeds_import_form_batch', array($uri)),
  ),
  'progress_message' => t('Uploading Multiple Products...'),
  'error_message' => t('Error!'),
  'finished' => 'test_feeds_import_form_batch_finish',
  'file' => drupal_get_path('module', 'test') . '/includes/test_form.inc',
);

batch_set($batch);
batch_process('admin/import-data'); //Work like as drupal goto

```

---
Tags: 7, batch-operations
---


title: How to alter the path of login page?

text:
# Question
Title: How to alter the path of login page?
I want to alter the path of login page, /user/login, to /ulogin. How can I accomplish this?

# Answer
> 9 votes
You can use module Rename Admin Paths

> This module allows you to:
>
> rename path like '/admin/...' to '/something/...' rename path like '/user/..' to '/something else/..' It can be effective against registration spam bots or malicious people.
>
> This small module just implements hook\_outbound\_alter and hook\_inbound\_alter to rename paths. A settings form allows to choose replacement term for "admin" and "user".

---
Tags: 8, routes
---


# Question
Title: How to edit Team Members from Drupal site
I have been tasked with updating my companies website done in Drupal and I can find dozens of ways and places to configure a block, I just cannot find where I can make a simple, basic edit to the content and remove a Team Member.

When I use the search toolbar in Drupal it directs me only to the instances/ mentions of the Team Member block and NOT the actual list of Team Members. I've found the Tiers that are used to place them in the block, but still no actual list of said Team Members.

I don't know if my attached screenshot is at all helpful, but any suggestions on where to find these Team Members would be appreciated. BTW, they are not a part of the 'People' admins of the site.

# Answer
The attached screenshot in your question is a bit tough to digest, but it shows just enough details to suggest an alternative approach/solution to what you're trying to do ... and which should also work for any user who does not have authority to use any path starting with `/admin`.

### 1. Browse your views page results

After you closed the popup window, use the `View page` button included in (the right of) your screenshot, to show the actual "list" of all *Team members* in a page with title "*Team grid*".

From the "*Filter criteria*"-section included in (the left of) your screenshot, it seems that your list (or "grid") includes 1 entry (= a row included in the query results of your View) for each (published) "*node*" of content type `Blog Author` or `Team member`.

From the "*Fields*"-section included in (the left of) your screenshot, it seems that this list (or "grid") should at least show you these data about each of the included Team member:

* Title
* Job Title
* Picture

Use these data to decide which Team member you need to process (as detailed in step 2 below).

### 2. Select the Team member to be removed

It's impossible to tell from your screenshot, but pretty sure that for each Team member shown in your list (grid), you'll be able to click on it, to "*view*" more details about the Team member you selected. After you do so, you'll (probably) be viewing the actual *node* of the Team member you selected.

### 3. Edit/delete the Team member

Assuming *you* have permission to edit nodes of content type Team member, you'll have an `Edit` tab and a `View` (maybe even other tabs).

Use (click) `Edit` and scroll down to the bottom, to locate the buttons `Save`, `Preview` and `***Delete***`.

To finish, just hit the `***Delete***` button, confirm you want to do so ... voilà, gone is the Team member.
> 0 votes

# Answer
You can probably find what you need at /admin/content. What you are looking at is the views interface to build a list - the list doesn't exist anywhere but in your database, and it won't exist in the database as a list, it will just be separate rows in the database table, so don't bother looking there. The list is build from the database, using the interface that you have shown a screenshot of.

You should be able to find the various items you want at /admin/content. You may have to filter by a content type, depending on how much content is on your site.
> 1 votes

---
Tags: views, nodes, blocks
---


# Question
Title: Is it possible to have a block of content on a taxonomy term page?
If I have taxonomy of company and term companyx when I visit www.sitename.com/company/companyx I get a list of posts with that term // vocab. Is it possible to put a block of content above the posts? Or is there another better way of creating 'landing pages' for the taxonomy terms? On Drupal 7.

# Answer
One way to change the output of these pages is to use a module like Taxonomy Views Integrator. This will allow you to create any number of views for different vocabs or even specific taxonomy terms and drive the presentation of the taxonomy output. I use this regularly to override the default term page and present different layouts of content (typically powered by view modes).

Another way to approach it (creating landing pages) would be to create a content page representing that taxonomy page, then drop a TVI view block on this page under the main content. You could also use Panels to do that, but I don't use Panels, so I can't speak to that.
> 2 votes

# Answer
If you have a certain block that you would like to turn on for this URL then you can set the Block Visibility settings / Show block on specific pages check "Only the listed pages" and you can give "company/companyx" in the textbox.
> 2 votes

---
Tags: 7, taxonomy-terms
---


title: Force image link download

text:
# Question
Title: Force image link download
I have an image path like `http://example.com/sites/default/files/image.jpg`.

I have a download link like:

`<a href="http://example.com/sites/default/files/image.jpg">Download</a`\>

So on clicking on the download it opens the image in the browser. Instead I want when I click on the Download link, it should download that image.

Is it possible?

# Answer
You can use DownloadFile module. This module provides display formatter, for images, file etc, that uses downloadable links(of type: */download/file/fid/\[fid\]*) and should be compatible with older browsers.

Note:

* If you are doing custom coding, you can use file id (fid) to create your download link.
* You must upload the image, so that it can be assigned a file id.
> 1 votes

# Answer
In modern browsers it works:

```
<a download="image.jpg" href="http://example.com/sites/default/files/image.jpg">Download</a>

```
> 0 votes

---
Tags: 7, media
---


# Question
Title: How to get field collection values from user object?
I added a field collection to the user 'manage field' page, the field machine name is 'houses'. The user may add as many home he want.

This field collection regroup :

* a sample text plain field (the name of the house), the machine name "house\_name"
* a sample integer field (the size of the house), the machine name "house\_size"

In a custom module, I want load the current user and get values of all values of all his houses (in an array ?), how can I do that ?

I tried this :

```
$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
$user_houses = $user->get('field_houses')->getValue();
ksm($user_houses);

```

But I get :

It's ok, I set 8 houses in "user edit" page, so I get an array of 8 entries. But, I would like get all data in an array like this :

```
house 1 : name1 : size1
house 2 : name2 : size2
...
house 8 : name8 : size8

```

Thank you :)

# Answer
I find =)

With :

```
use Drupal\field_collection\Entity\FieldCollectionItem;
...
$test = FieldCollectionItem::load(3);

```

Where "3" is, by example, a value returned by $user-\>get('field\_houses')-\>getValue();
> 4 votes

---
Tags: 8, users, entities
---


# Question
Title: Why do I get this error when I try to use db_change_field()?
My Drupal installation has a table with a field `title` of type varchar and length of 255.

For some custom process, I need to increase the length to 500 characters.

I tried doing so with the following code:

```
function mymodule_schema_alter(&$schema){
    if( isset($schema['field_data_field_document_title']) ){
        db_change_field('field_data_field_document_title', 'field_document_title_value', 'field_document_title_value',
            array(
                'length' => 11,
            )
        );

    }
}

```

Originally I had that code in my .module file. When I flushed caches I could verify using the DEVEL module that my field length changed. But in phpmyadmin the field length remained 255.

Then I migrated the function to the .install file. I execute *run updates* and get the following error:

> PDOException: SQLSTATE\[42000\]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DEFAULT NULL' at line 1: ALTER TABLE {field\_data\_field\_document\_title} CHANGE `field_document_title_value` `field_document_title_value` DEFAULT NULL; Array ( ) in db\_change\_field() (line 3020 of /var/www/Intranet/includes/database/database.inc).

I could really use some help, please.

# Answer
> 1 votes
The error you get is because you aren't using `db_change_field()` with the correct arguments. For example, if you look at `block_update_7003()`, you will see it calls the function as follows.

```
  db_change_field('block', 'weight', 'weight', array(
    'type' => 'int',
    'not null' => TRUE,
    'default' => 0,
    'description' => 'Block weight within region.',
  ), array(
    'indexes' => array(
      'list' => array('theme', 'status', 'region', 'weight', 'module'),
    ),
  ));

```

The last argument is the full array defining the field, not just the part that you need to change.

As the description for `block_update_7003()` says, its purpose is changing the weight column to normal int. If your code were correct, `block_update_7003()` should use the following call.

```
  db_change_field('block', 'weight', 'weight', array(
    'type' => 'int',
  ));

```

Also, `hook_schema_alter()` should be used to alter the schema, not adding or removing database fields. Drupal doesn't use that hook, but the example code is clear enough.

```
function hook_schema_alter(&$schema) {
  // Add field to existing schema.
  $schema['users']['fields']['timezone_id'] = array(
    'type' => 'int',
    'not null' => TRUE,
    'default' => 0,
    'description' => 'Per-user timezone configuration.',
  );
}

```

The description of the hook is probably not clear, since it doesn't say in which way the schema should be changed, but since is talking of `$schema`, the idea behind that hook is that it alters what returned from `hook_schema()`, which is what an alter hook normally does: Change the values returned from another hook.

It is then `hook_install()` or `hook_update_N()` that effectively changes the database table.

# Answer
> 1 votes
Check the documentation for `hook_schema_alter()`: `db_change_field()` is not supposed to be used there, instead change the `$schema` array to the required structure.

```
function mymodule_schema_alter(&$schema){
    if( isset($schema['field_data_field_document_title']) ){
        $schema['field_data_field_document_title']['fields']['field_data_field_document_title_value']['length'] = 500;
    }
}

```

However, if the module is already installed and has existing data (seems like this is the case), then a call to `db_change_field()` inside a `hook_update_N()` implementation is necessary to update the schema.

```
function mymodule_update_7100() {
    $table = drupal_get_schema('field_data_field_document_title', TRUE);
    db_change_field('field_data_field_document_title', 'field_document_title_value', 'field_document_title_value', $table['fields']['field_document_title_value']);
}

```

Note (if there is existing data): both these functions need to be included in mymodule.install, as the second function depends on the first: the change of field length made in `mymodule_schema_alter()` will be included in the table schema returned by `drupal_get_schema()`.

---
Tags: database
---


# Question
Title: What is the correct way to create a new ImageItem and attach it to a FileFieldItemList?
I'm writing a custom module to pull in some images from an old D6 installation (the cck plugin is failing to connect images to the correct node). So I need to be able to create new ImageItem and add them to the field.

Can I simply create a new object like:

```
$field = $node->field_gallery;
$img = new ImageItem();
$img->setValue(array(
   "target_id" => 123,
    "alt" => "Alt text"
   "title" => "Title text"
));

$field->set($delta, $img);
$node->save();

```

Or do I need to do something with entityManager to get it linked properly?

# Answer
You don't need any of that. You just set the values, everything else will be taken care of for you.

```
$node->set('field_gallery', [
  'target_id' => 123,
  'alt' => 'Alt text'
  'title' => 'Title text'
]);

```

If you want to have multiple items, use \`$node-\>field\_gallery-\>appendItem($values);
> 1 votes

---
Tags: 8
---


# Question
Title: How to add fields wrapper in field preprocess
My code:

```
function MYTHEME_preprocess_field(&$vars, $hook) {
  $element = $vars['element'];
  if($vars['element']['#field_name'] == 'field_example') {
    foreach($vars['items'] as $key => $item) {
      $vars['items'][$key]['#prefix'] = '<figure class="col-xs-4 col-sm-3 col-md-2">';
      $vars['items'][$key]['#suffix'] = '<figcaption>' . $item['#item']['alt'] . '</figcaption>';
      $vars['items'][$key]['#suffix'] .= '</figure>';
    }
  }
}

```

I want to wrap all items in a div. I should use some code outside the foreach, but I hadn't found any solution. Can you help me?

# Answer
> 1 votes
Based on the question I'm assuming you are asking for D7 ...

You should use a "container" for this. Something like this:

```
$element = $vars['element'];
if($vars['element']['#field_name'] == 'field_example') {
  foreach($vars['items'] as $key => $item) {
    // Do whatever you want...
  }
  $vars['items']['#type'] = 'container';
  $vars['items']['#attributes'] = array(
    'id' => "some-id",
    'class' => array(
      'some-class',
    ),
  );
}

```

See this other question for more details. Also, if you want to get a little more fancy you can look at using theme wrappers.

---
Tags: theming, entities
---


# Question
Title: How to consistently style the titles of Views in my Panels sidebar?
My Panels website has a sidebar and I put several Views in there as Panes. Every View has a title and I would like to wrap this title in a `h3` header. Until now, I manually overrode the Pane's title with **%title** and chose the `h3` tag in the Pane's settings. This works fine, but sometimes I forget to make the adjustments and then things look ugly for a while. It is also possible that one day I prefer to use `h2` instead and then I will be facing dozens of Panes to adapt.

Therefore, I would like to know whether there is an easier and more efficient way to achieve what I want. After reading Drupal 7 Views: Use one views.tpl.php file for multiple views, I thought about using a View template, but I cannot just tag the Views that will turn up in the sidebar, because some Views have multiple blocks and only one of them will be put in the sidebar.

Do you have any suggestions that might make life easier for me (or at least the website developing side)?

# Answer
You just need to target it with css.

```
.pane-region-class .pane-title h2,
.pane-region-class .pane-title h3 {
  font-size: 16px;
  etc.
}

```

I think you can add classes to panel regions. And do the above without `h2` / `h3` to style the general title.
> 0 votes

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


# Question
Title: enforce naming conventions for page aliases by content type
I would like to set mandatory url naming conventions for custom content type nodes.

When users create a new content type I want to force certain naming conventions for the url alias. For example:

when creating 'Type A' and 'Type B' pages they should have aliases of the form:

* www.example.com/a/{user-assigned} (Type A)
* www.example.com/b/{user-assigned} (Type B)

is there a way to do this in Drupal 8?

# Answer
Yes, this use case is covered under the Pathauto module.

Essentially, you'll add a new *Content* patterns (from the admin UI in **admin/config/search/path/patterns**) for each of your content types with the following path pattern, `my_type/[node:author:account-name]`.

As long as the user doesn't have the *Administer URL aliases* & *Create and edit URL aliases* permissions, their created content path will be set automatically without being able to change the path.
> 1 votes

---
Tags: 8, path-aliases
---


# Question
Title: Set a default font family and size in ckeditor
Its been 4 days I am trying to set a default font family to the ckeditor(not set default label) but I am not able to do the task. Also i tried working with content.css but its not working. Please need a help

# Answer
> 1 votes
Assuming you are using the CKEditor module you will need to override it using CSS. You can either create a ckeditor.css file to override it or edit it in your theme file.

Or you can add

```
config.extraCss += "body{font-family:Arial, serif;}";

```

To your extra javascript section in the settings text format.

# Answer
> 0 votes
Hope this will help you.

In Drupal 7, go to the configuration options of CKEditor in your admin area (admin/config/content/ckeditor) press the "edit" button for the profile that you want to add this option to, and add the code in the "Advanced Options" -\> "Custom JavaScript configuration".

```

    config.font_names =
            'Helvetica, Arial, sans-serif;' +
            'Times New Roman/Times New Roman, Times, serif;' +
            'Verdana';

```

**You can also achieve it by**

* Let say **Verdana** be the default font
    + Open **contents.css** file and change the font to
    ```
    font-family: Verdana;
    ```
    + In the **application/page** where the output will be published, add this style
    ```
    <style> .entry-content {font-family: Tahoma;} </style>
    ```

CKEditor offical document

# Answer
> 0 votes
Add below lines in CKEditor `config.js` or your own `custom.js` where you configure the CKEditor options.

```
config.font_defaultLabel = 'Arial';
config.fontSize_defaultLabel = '16px';

```

# Answer
> 0 votes
You've to do 3 steps of work to set the CK Editor default Font family & Size.

Edit your content.css in the CKEditor folder

1. Change the Font-family & font-size as per your need in Body → This will set your default font family

```
body
{
font-family:Georgia;
}

```
2. Change the same font-size as per your need in .cke\_editable → This will set your default font-size in the Editor

```
.cke_editable
{
font-size: 18px;
}

```

\`3. Go to Your CKEditor → Update your CKEditor Dropdown config settings

```
        using (Html.BeginForm())
        {
            @Html.AntiForgeryToken()

            @Html.TextArea("ContentEditor", CurrentItem.Content)
            <script>
            CKEDITOR.replace('ContentEditor');
            CKEDITOR.config.font_defaultLabel = 'Georgia';
            CKEDITOR.config.fontSize_defaultLabel = '20';
            </script>

        }

```

Hopes this will Help...

---
Tags: wysiwyg
---


# Question
Title: Tagging people on blog entries and being able to access their profiles from tags
I'm trying to create a blog posts where users are able to create challenges and tag other users. I succeeded in creating blog entries, I succeeded in adding tags on blog posts.

But I struggle with making so that clicking on tag would bring me to the user profile. I tried creating taxonomy called **users** and I specified *url alias*: `/user/*` Saddly if I clicked on tagged person, Im being brought to `..../taxonomy/term/4`

How can I solve this?

# Answer
> 0 votes
You can achieve that using the Mentions module

> The Mentions module offers Twitter like functionality, recording all references to a user's username - using the **\[@username\]** or **\[@#uid\]** filter format - from various locations, providing a centralized page to track all mentions (via the Views module).

This module provides a configuration page, through that you can define the mentions pattern, and path (supports tokens)

---
Tags: users, taxonomy-terms, nodes
---


# Question
Title: How to show data of user that flagged a content(5 flag types or more)?
This is a followup question about this Old question

I have 5 flag types for a content type. consider we have 5 flag types and we don't know how many flags our user used. I mean, the first user can flag a content by flag type 1, type 2 and type 5, and other user can flag same content by flag type 2 and type 4, and etc, OK? I want to show a list of users that flagged same content, some users can use all flag types and others can use some flag types. thus I don't know users will use what flag types. You consider moreover "username", I want to show user's "E-mail". thus in this table I want to show "username", user's "E-mail" and "flag fields".

In below picture, I showed that a content can has different value. because any user can input different value in flag field. this table will appear in content page. I mean any content page has its specific table.

**UPDATE**

Now I have a new Idea that I would explain. I can use **Global custom text** field. Consider I have 5 flag types, I added my 5 flag types **username** fields and hide them in views(exclude from display). As you know, First I should add flag types in **Relationship part of views**. when I add a username field, I should choose relationship in username field. Thus I should add 5 username fields. After that I can use **REPLACEMENT PATTERNS** in "global custom text". Now I have 5 patterns for my 5 username fields. Now I have a problem. Consider when one user use 3 flag types(**3 of 5 flag types** that I enabled for specific content), I mean when he(she) flag(s) a specific content by 3 flag types, in custom text field we can see username that **repeated 3 times**, because we use **all 5 PATTERNS** of username fields in global custom text field.

How can I solve this problem?

Is there any HTML code to show one of these patterns?

Also I can use **global PHP**. Is there any PHP code for this problem?

alternatives welcome also

# Answer
> 2 votes
As per the "*alternatives welcome also*" in your question, I would format/present the data in your table in a different format/layout. which will make the data shown in it way more easy to digest/understand.

Have a look at this alternative, which shows the same data (to which I added a few more similar sample rows to illustrate what I mean):

```
---------------------------------------------------------------------
| User   | Email       | Flag A | Flag B | Flag C | Flag D | Flag E |
---------------------------------------------------------------------
| John   | John@a.com  | 4333   |        |        |        |        |
---------------------------------------------------------------------
| Jack   | Jack@b.com  | 9000   |        |        | 1390   | 7677   |
---------------------------------------------------------------------
| Hamed  | Hamed@c.com | 0123   | 0456   | 0789   |        |        |
---------------------------------------------------------------------
| Niall  | Niall@d.com |        | 3377   |        | 5566   |        |
---------------------------------------------------------------------

```

If you agree, note however that creating such table is not obvious if you're trying to do so with the Views module. However, using the Forena module (disclosure: I'm a co-maintainer), creating such table is straight forward: it's what is called a ***Crosstab table***. This is a table with a special layout. It is formatted as a grid, with:

* the **rows** representing one or more (combinations of) facts, such as countries or regions, names of persons (or users) like employees / salespeople (or user IDs / user names), **names of Models**, etc.
* the **columns** representing one or more other facts, such as periods (months of a year, **years**, etc), available types/flavors of something (like types of errors), etc.
* the **intersections of rows and columns** containing the actual information (data), such as summarized information (counts of something), timestamps, etc. and which might (optionally) **include a hyperlink to a drill-down report**.

For more info on this, have a look at the "Northwind database" demo videos, i.e:

To create such table for each "*content page*" (as in your question), you can use an appropriate Report parameter, which is like the equivalent of a *Contextual filter*. In your case, the node's id (= `nid`) would probably be a good candidate for such parameter. Have a look at this example report, and note the query string (= `state=OH`) in its URL. Just change that string to, eg,`state=IL` (or select some other value for *state* in the *Parameters* form) to get the basic idea about such parameter. Refer to the tutorial about Forena report parameters for more details about this topic.

This technique can also be applied to any of your entities you want to create reports about (nodes, users, whatever). For example, after you enabled Forena in your own site, you'll have access to one of its sample reports (= Active users), located at `/reports/drupaladmin.active_users`. If you then follow the link "logs" in that report for any of the users in the report (say with user name = *SomeUserName*), you'll get the (log) details about that user, via an URL similar to `/reports/drupaladmin.user_logs?name=SomeUserName`. So in this case the user name is used as such report parameter also.

---
Tags: 7, entities, views, flags
---


# Question
Title: Will memcache work in this configuration?
I've got a Drupal site running with

* 1 x Load balancer in front
* 2 x web servers running Apache, PHP and Drupal, traffic coming from load balancer, and
* 1 x Generic server hosting MySQL (MariaDB) Drupal database and `sites/default/files` accessed by the above 2 servers over the network.

If I wish to use memcached, would it work if I install memcached on the 2 web servers and configure Drupal to connect localhost using the memcache module?

Edit: are there any special consideration in order to make this work? I think I have read somewhere about session stored.

# Answer
Short answer is yes, that's a fairly common configuration. You might also want to consider using Nginx instead of Apache.

For user session support, it's possible to use Memcache. However, memcache data is more transient and you may prefer the more persistent storage, for longer and more durable user sessions, that the database engine provides.

For `cache_form` you should use a more persistent cache, such as the database, to avoid form cache validation errors.

e.g: `$conf['cache_class_cache_form'] = 'DrupalDatabaseCache';`

It's recommended to use Memcache for the lock API layer as it's quick read/write and short cache lifetime is suitable.

e.g: `$conf['lock_inc'] = 'sites/all/modules/contrib/memcache/memcache-lock.inc';`

For Memcache integration with Drupal, you can use https://www.drupal.org/project/memcache or https://www.drupal.org/project/memcache\_storage
> 1 votes

---
Tags: caching
---


# Question
Title: Drupal 8, use "query api" with "collection fields" (not via FieldCollectionItem::load)
I added a field collection to the user 'manage field' page, the field machine name is 'houses'. The user may add as many home he want.

This field collection regroup :

```
- a sample text plain field (the name of the house), the machine name "house_name"
- a sample integer field (the size of the house), the machine name "house_size"

```

In a custom module, I want check if the current user have a house with a size = 4 (if in collection fields, there is a house with "house\_size = 4"), how can I do that via the Drupal 8 Query Api ?

I found several example of Drupal "Query API", but nothing with collections fields..

I can use the function load of the class FieldCollectionItem, but I want use a fastest way for get the information I want.

Thanks you :)

# Answer
> 0 votes
Try to query the fields of the `FieldCollectionItem` with `.entity`:

```
 $user_ids = \Drupal::entityQuery('user')
    ->condition('houses.entity.house_size', 4)
    ->execute();

```

---
Tags: 8, entities
---


title: multi-domain recognition at db level

text:
# Question
Title: multi-domain recognition at db level
I have:

* 2 domains
* single database
* Single codebase
* single form with a text-editor and submit button.

What I want is the recognition of domain at database level. So, let's say if I hit http://example.com/en it should save in db with table **T1** and if I hit http://example.fr/en it should also save in same db but with different table **T2**.

And now when I will fetch default value from table **T1**, it should only reflect to http://example.com/en and similarly for **T2** it goes here - http://example.fr/en.

But because of **same database and code base** of both domains it is difficult to know from which domain the request is coming.

I have **1 solution is** like create a table in `.install` file by considering `global $base_url;` and then check if table name = `$base_url.my_table` exists, fetch all results.But I'm not sure it's the best approach in Drupal 8 or some other way to achieve this.

Please share best approach for this.

# Answer
> 1 votes
You need to enable multisite.

The documentation inside the settings.php file is also very helpful, read that too by viewing the source of the file here https://api.drupal.org/api/drupal/sites!default!default.settings.php/8.

Briefly, the steps are,

1. Multi-site requires the existence of the sites/sites.php file in your Drupal 8 installation. You will need to create this file manually.

Example content would be:

```
<?php
$sites['mysite.com'] = 'site1';
$sites['8000.localhost'] = 'site2';

```
2. Create a site directory inside sites/, the path should be sites/site1. Put a settings.php file in this directory in order for Drupal 8 to recognize it.
3. Visit the URL of site1, like mysite.com to install it.

---
Tags: 8, multi-sites
---


# Question
Title: Is Contact module the right choice for multiple ask a question pages?
I have a set of pages already developed. For each page I need to add a new page with an "Ask a Question" form to let end users contact via email the corresponding page owner.

I tried the Contact module but it doesn't seem the right choice.

One of the requirements is to hide the recipient email address from the user.

How can I create such a customized form and be able to set a different recipient on each page? Do I have to create a new Feature?

# Answer
Depends , you can use the webforms module to create custom forms it's better suited for creating forms than the contact module
> 1 votes

---
Tags: 7, emails
---


# Question
Title: How to override ID's in Drupal and comply to CSS Lint|?
How to override ID's ( or not use ID'S) in Drupal and use Classes only to comply to CSS LINT ( consider that I must use a subtheme and not always can write the HTML. I will have to work with what Drupal gives me). Can anyone advise me about best practices?

# Answer
> 0 votes
Using a subtheme you can override whatever templates contain IDs and change them to use classes instead, updating the CSS along the way.

For example you can override the node template by creating a node.tpl.php file in your subtheme, and the markup can be changed to whatever you need.

You'll have to identify which templates need to be overridden yourself, as there isn't a list available; it will depend on what modules you have installed, and what base theme you're using.

It's also worth bearing in mind that contributed modules (and possibly core modules) may use IDs to target elements in javascript. So test thoroughly, as you might need to make some changes there as well.

*However*

Don't forget that you're just trying to comply with CSS standards here. You don't need to actually remove the IDs to do that, just any CSS that uses them in selectors.

Drupal 8 core conforms to the rule anyway (see .csslintrc in the root), so you should be covered there, but contributed modules may not. That's when you'll need to check manually and maybe override templates/CSS files that they provide.

Earlier versions of Drupal don't conform to the same standards as far as I know so YMMV.

---
Tags: theming
---


# Question
Title: I want my LinkItem to get target="_blank" if my node has the checkbox checked
I'm not sure if hook\_preprocess\_node is the right hook. But I cant find the setting for target in the LinkItem. Can you help me?

A different approach I failed is to extended the FieldWidget of Link and add a checkbox to toggle the target setting. I wasn't able to save this setting though...

```
class TargetLinkWidget extends LinkWidget {
  public static function defaultSettings() {
    return ['target' => ''] + parent::defaultSettings();
  }

  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
    $element = parent::formElement($items, $delta, $element, $form, $form_state);

    $element['target'] = [
      '#type' => 'checkbox',
      '#title' => t('Open link in new window'),
      '#value' => '_blank',
      '#default_value' => $this->getSetting('target'),
    ];
    return $element;
  }
}

```

# Answer
> 1 votes
According to your answer to my comment on the question, you are using a view. To have my solution work, it needs to display fields, not teasers.

First off, you do **not** need to add an additional field to the node type/content type.

All you need to do is to add the already displayed link field in views a second time. All fields get a views internal machine name which is often identical to the field's machine name. However, if you add a field twice, you will end up with two machine names, thus you can determine which version of the rendered field to use at some point.

So, you end up having the same field (Link - field\_link) showing up twice in your view's field list. The one added first will be accessible through the token `[field_link]`, the second one by using `[field_link_1]`.

In the first one's settings, choose the plain URL formatter and then go to the "Rewrite result" section. Select the option to output the field as link and enter `[field_link]` as url and `_blank` for target:

Finally, set the option "Exclude from display". Repeat that with the second link field, but use `[field_link_1]` as url and *do not* set the target.

With both field instances set up and excluded from display, add your checkbox field which may have the machine name `field_link_is_external`.

Now you need to rewrite that field to be `[field_link]`:

*If the checkbox is checked, the link version with target set "\_blank" will be shown.*

Next, you need to set the "No result behaviour" as follows:

*If the checkbox is not checked, it's value is zero, hence we treat 0 as empty and thus the second link field (w/o target) will be shown.*

And that's all there is to it. No need for any editor to enter some url twice. They just need to set the link and decide whether or not to check that checkbox.

---
Tags: views, entities, hooks, navigation
---


# Question
Title: Display 2 contents types fields in 1 view
I am trying out Drupal 7 - and am a complete noob, so please bear with me!

I have a content type - 'film' which displays various fields about a film and another called 'venue' which displays data about a screening of a film.

I wanted to merge the display of content types film and venue so that they display in the same screen (all the fields in one screen). Is this possible? Do I do it with views? I have heard of relations, but I'm finding it all confusing.

Thanks.

# Answer
> 2 votes
If there is a 'venue' content type linked through a node reference field, you can do it using a relation in a view.

# Answer
> 1 votes
I think this is a perfect sample for views attach. If anyone is still waiting or looking for a solution: http://drupal.org/project/eva

# Answer
> 0 votes
by using entity reference make a call to particular node.and in views you can add the relations based on reference.then you can display the both in single page

eg: In venue type-create node and give reference of film.in views relations display based on the reference field

---
Tags: 7, views
---


title: Need JS help on Vertical Tabs

text:
# Question
Title: Need JS help on Vertical Tabs
I can barely cut and paste JS stuff and have not seen an example of this anywhere. I have added a vertical tab to the node admin page and I want to show either "Limited" when the value of a field in the tab is not zero or "Not limited" if it is.

I see lots of examples of using check boxes, but this is a numeric field.

# Answer
> 0 votes
Sorry for the late response, your question escaped my mind.

```
(function ($) {
   (function Forever(){ // we create a function called Forever
     var grabval = $('#edit-title').val();
     $('.vertical-tab-button').each(function(){
       if ($(this).children().children('strong').text() == 'Content Limit'){
         if (grabval == 0 && $(this).children().children('span') == null){
           $(this).children().children('strong').after('<span class="summary">Not Limited</span>');
         }
         else if (grabval == 0 && $(this).children().children('span') != null){
           $(this).children().children('span').html('Not Limited');
         }
         else if (grabval != 0 && $(this).children().children('span') == null){
           $(this).children().children('strong').after('<span class="summary">Limited</span>');
         }
         else if (grabval != 0 && $(this).children().children('span') != null){
           $(this).children().children('span').html('Limited');
         }
       }
     });
   setTimeout(Forever, 1);
   })();
})(jQuery)

```

I used the node title for mine, so if you change the title to 0 or 1 or 2 ..etc, it will change.

So all you have to do is change the `var grabtext = $('#edit-title').val();` more specifically the `#edit-title` part, and put the ID or Class name of your Maximum per time period box.

---
Tags: javascript, forms
---


# Question
Title: Drupal module updates failing through administrative interface after update to 7.50
So, I just updated my site to Drupal 7.50, and in addition to being informed of a host of modules that weren't properly uninstalled, it seems that I can no longer update modules through the administrative interface. I have a long list of module updates and it will be annoying to do all of them manually.

So is there some setting that changed? Or how can I get back to being able to update modules through the admin UI. I've tried a few at a time, as well as one at a time. I get the following warning after trying to update

```
The file could not be created.
https://ftp.drupal.org/files/projects/google_analytics-7.x-2.3.tar.gz could not be saved to temporary://update-cache-d103ec38/google_analytics-7.x-2.3.tar.gz.
The file could not be created.
https://ftp.drupal.org/files/projects/webform-7.x-4.14.tar.gz could not be saved to temporary://update-cache-d103ec38/webform-7.x-4.14.tar.gz.
Downloading updates failed:

Failed to download google_analytics from https://ftp.drupal.org/files/projects/google_analytics-7.x-2.3.tar.gz
Failed to download webform from https://ftp.drupal.org/files/projects/webform-7.x-4.14.tar.gz

```

# Answer
> 3 votes
This is most likely a problem with your file permissions. A quick test on simplytest.me showed that module installation is not broken in 7.50.

I would try to check the file\_temporary\_path variable under:

"Administrator -\> Configuration -\> Media -\> File System"

And see that the web server can write to the configured directory.

If my assumption is correct, then also all other file uploads will fail, so it might be a good idea to test uploading an image to an article, too.

---
Tags: 7, updating
---


title: Edit link in views leads to wrong node

text:
# Question
Title: Edit link in views leads to wrong node
Just before the title field I have added a "Content: Edit link" in several of my views to make it easy to edit nodes. In the Rewrite section for this item I have added this to change the edit symbol:

```
<img src="/sites/all/themes/mysite/images/application_edit.png" alt="Edit symbol" height="16" width="16">

```

Now I have discovered that the Edit link redirects to the wrong node. The link looks like this:

```
www.mysite.com/node/25305/edit?destination=node/24207

```

How can I make it direct the user to the right node? Should I enable Output this field as a link and add the node ID manually? I am not quite sure how to do that using the replacement patterns.

# Answer
OK, I solved it the easy way. I enabled "Output this field as a link", added the field "Content: nid" as the first field and then changed my rewritten field to this:

```
<a href="http://www.mysite.se/node/[nid]/edit?destination=node/[nid]"><img src="/sites/all/themes/mysite/images/application_edit.png" alt="Edit symbol" height="16" width="16"></a>

```

And now it works. Hope this helps somebody.
> 0 votes

---
Tags: 7, views
---


# Question
Title: How to utilise isDefaultRevision() for forward revisioning?
Since "Support revisions in different states" went into the core it is now theoretically possible to have forward revisions of nodes. For example publish revision 1 then create revision 2 but keep it unpublished. This is very useful when someone needs to create new version of a node that needs to be approved before publishing.

Sounds great so here's what I did:

1. I've created a node with title *"Published revision"*. The node ID is `1` and it's revision is `1`.
2. I've created a new revision of node `1` and changed it's title to *"Unpublished revision"*. This node has revision `2` and it has immediately been set as default revision.
3. At this moment `/node/1` shows the node with title *"Unpublished revision"*.
4. I've used PHP to load node `1` with revision `1` and I've set it to default revision (`$node->isDefaultRevision(true)`).
5. At this moment `/node/1` shows the node with title *"Published revision"*.

So far so good. However **the problem is that I'd like to edit revision `2` but I can't**:

1. `/node/1/edit` shows edit form of revision `1`.
2. `/node/1/revisions/2/edit` is of course 404.
3. And on top of that when I go to `/node/1/revisions` the revision `2` is listed as **"Current"** which of course is not true because default revision is `1`. (Let's say I can live with that for now)

**Questions**:

1. How to edit arbitrary node revision?
2. How to control which node revision is saved as default revision?

# Answer
It sounds like you want to use content\_moderation experimental module that just went into Drupal Core 8.2.x-dev and will be available in Drupal 8.2.0.

That module should also be a great inspiration how to implement the functionality.

In general you will need to create your own route where you first load the revision of the entity, then save it when you get it back from the form with:

$node-\>setNewRevision(); $node-\>isDefaultRevision(FALSE);

The function name is very misnamed (https://www.drupal.org/node/2706337 has the details).

However I strongly suggest to check content\_moderation first and maybe you can just utilize it for your needs directly.
> 0 votes

---
Tags: 8
---


title: Devel Krumo not updating

text:
# Question
Title: Devel Krumo not updating
I have the following code in my module in a hook\_form\_alter...

```
if($form_id == "privatemsg_new") {
        dsm($form);
        $form['recipient']['#type'] = 'select';
        $form['recipient']['#title'] = 'Choose Recipient';
        unset($form['recipient']['#autocomplete_path']);
    }

```

**The code works just fine, the title is changed, the form field turns into a select list**

However in Krumo, the fields are not being updated. I guess its not the end of the world, but its annoying to not be able to see my changes!

Type, Title and #autocomplete\_path should all have changed.

I've run cron, flushed caches etc. Anything else I can try?

# Answer
> 2 votes
Put `dsm()` to the end of code...

```
if ($form_id == "privatemsg_new") {
  $form['recipient']['#type'] = 'select';
  $form['recipient']['#title'] = 'Choose Recipient';
  unset($form['recipient']['#autocomplete_path']);
  dsm($form);
}

```

---
Tags: 7, debugging
---


# Question
Title: How do programmatically create fields for content types, and ADD them to the the content type form
Say I have this field, "map\_description". I know I would this function to define the field:

```
$field = array(
  'field_name' => 'map_description',
  'cardinality' => 1,
  'type' => 'text',
);
field_create_field($field);

```

And I have this code which I'm not sure what it does but I'm told that I'll need it:

```
 $instance = array(
    'field_name' => 'map_description',
    'label' => 'The map description.',
    'bundle' => 'my_content_type',
    'entity_type' => 'node',
    'widget' => array(
    'type' => 'text_textfield',
 );
 field_create_instance($instance)

```

Those two code bits are both in my install hook and run when I install the module. But while the fields are in fact created, I have to manually assign them to the content type via "manage fields", is there a way to have the fields automatically assigned to the content type?

# Answer
> 10 votes
You're almost there.

From your code:

```
'bundle' => 'my_content_type',

```

Replace *my\_content\_type* with the name of the content type you want it attached to.

Here's a full example of adding a *Alias* text field to the *Article* content type. (from monarchdigital.com)

```
/**
 * Update hook to add a field to a node.
 */
function my_module_update_7000() {
  $field_name = 'field_alias';
  // Make sure the field doesn't already exist.
  if (!field_info_field($field_name)) {
    // Create the field.
    $field = array(
      'field_name' => $field_name,
      'type' => 'text',
      'settings' => array('max_length' => 64),
    );
    field_create_field($field);

    // Create the instance.
    $instance = array( 'field_name' => $field_name,
      'entity_type' => 'node',
      'bundle' => 'article',
      'label' => 'Alias',
      'description' => 'The article alias.',
      'required' => TRUE,
    );
    field_create_instance($instance);

    watchdog('my_module', t('!field_name was added successfully.', array('!field_name' => $field_name)));
  }
  else {
    watchdog('my_module', t('!field_name already exists.', array('!field_name' => $field_name)));
  }
}

```

# Answer
> 0 votes
Make small changes in your code .In Fields

```
$t = get_t();
$field = array(
   'field_name' => 'map_description',
    'label' => $t('My Description'),
    'type' => 'text',

```

);
field\_create\_field($field);

```
& Write this in Instance

$t = get_t();
return array(
  'map_description' => array(
    'field_name' => 'map_description',
    'type' => 'text',
    'label' => $t('Map Description'),
    'bundle' => 'your_custom_content_type',
    'entity_type' => 'node',
    'widget' => array(
      'type' => 'text_textfield'
    ),
    'display' => array(
      'example_node_list' => array(
        'label' => $t('Map Description'),
        'type' => 'text'
      )
    )
  ),

```

---
Tags: 7, nodes
---


# Question
Title: How to copy view modes between content types in Drupal 8?
I've been doing my first Drupal 8 project, and a major pain point, when you have a site with 10 or more content types, is to copy a view mode to all the other content types after you set it up on one type, such as "article".

The question is, how do speed-up the process within Drupal 8 of copying a change to a view mode on multiple content types? It can be a real pain point for developers on larger sites.

# Answer
> 6 votes
I had an ah ah moment when I found this page: https://api.drupal.org/api/drupal/core!includes!entity.inc/function/entity\_get\_display/8.2.x

You can write little scripts to update a field across many content types. This can potentially save you hours on your Drupal 8 development! We have a site with nearly 20 content types and let's say you want all of them be able to display with your new view mode, "card". You've set it up on the article content type and now you need to copy it over.

I created this helper function as an example:

```
**
 * Utility function to copy a display mode from one entity bundle to another.
 *
 * @param $entity_type
 *   string Entity type to update.
 * @param $source
 *    string Source node bundle.
 * @param $target
 *    string Target node bundle.
 *  @param $view_mode
 *    string view mode to use.
 */
function my_module_copy_display_mode($entity_type, $source, $target, $view_mode) {

    $entity_view_display = \Drupal::entityTypeManager()
    ->getStorage('entity_view_display')
    ->load($entity_type . '.' . $source . '.' . $view_mode);

    if (empty($entity_view_display)) {
      return;
    }

    $items_to_copy = $entity_view_display->get('content');

    $new_entity_view_display = \Drupal::entityTypeManager()
    ->getStorage('entity_view_display')
    ->load($entity_type . '.' . $target . '.' . $view_mode);

    if (empty($new_entity_view_display)) {
      // If it can't load view mode on target type, create it.
      $values = array(
        'targetEntityType' => $entity_type,
        'bundle' => $target,
        'mode' => $view_mode,
        'status' => TRUE,
      );
      $new_entity_view_display = \Drupal::entityTypeManager()
        ->getStorage('entity_view_display')
        ->create($values);
    }

    $arr = $new_entity_view_display->toArray();

    foreach($arr['content'] as $field_name => $field_data) {
      $new_entity_view_display->removeComponent($field_name);
    }

    $definitions = \Drupal::entityManager()->getFieldDefinitions($entity_type, $target);

    foreach($items_to_copy as $key => $value) {
      // Check if they are in the entity field definition array.
      // This prevents adding fields that aren't on this content type.
      if (!empty($definitions[$key])) {
        $new_entity_view_display->setComponent($key, $value);
      }
    }

    $new_entity_view_display->save();
}

```

To use this, I wrote a secondary function with our site's content types:

```
/**
 * Copy a given view mode from article bundle to all other node types.
 *
 * @param $view_mode
 *   string View Mode to copy.
 */
function my_module_copy_view_mode_from_article_to_other_types($view_mode) {
  $source = 'article';

  $targets = [
    'car',
    'gallery',
    'video',
    'listicle',
    // etc.  put all the content types you want to copy to.
  ];

  foreach ($targets as $target) {
    my_module_copy_display_mode('node', $source, $target, $view_mode);
  }

}

```

Then, I just ran this second function from /devel/php, with a handful of view modes I wanted to make sure were consistent across all node bundles.

It's very fast, and what used to take half-an-hour of drudgery, dragging and dropping, is now very fast!

Update: Here's a drush version you can add to a custom module, it also allows you to just copy one field from a display mode to another display mode.

```
    <?php
/**
 * Implements hook_drush_command().
 */
function mymodule_drush_command() {
  $items = array();
  $items['copy_display_mode'] = [
    'description' => 'Copy display mode to another display mode. Example: "drush cdm node article clinical_trial three_up_item three_up_item"',
    'arguments' => [
      'entity_type' => 'Entity type to update',
      'source' => 'Bundle to copy from',
      'target' => 'Bundle to copy to',
      'source_view_mode' => 'View mode to copy from',
      'target_view_mode' => 'View mode to copy to',
      'field_to_copy' => 'Optionally, copy just one field',
    ],
    'callback' => 'mymodule_copy_display_mode',
    'aliases' => ['cdm'],
  ];
  return $items;
}

/**
 * Utility function to copy a display mode from one node bundle to another.
 *
 * @param $entity_type
 *   string Entity type to update.
 * @param $source
 *    string Source bundle.
 * @param $target
 *    string Target bundle.
 * @param $source_view_mode
 *    string view mode to copy.
 * @param $target_view_mode
 *    string view mode to copy to.
 */
function mymodule_copy_display_mode($entity_type = "", $source = "", $target = "", $source_view_mode = "", $target_view_mode = "", $field_to_copy = "") {

  if (empty($entity_type)) {
    drush_print('Missing entity_type. Type "drush help cdm" for arguments.');
    return;
  }

  if (empty($source)) {
    drush_print('Missing source. Type "drush help cdm" for arguments.');
    return;
  }

  if (empty($target)) {
    drush_print('Missing target. Type "drush help cdm" for arguments.');
    return;
  }

  if (empty($source_view_mode)) {
    drush_print('Missing sourced_view_mode. Type "drush help cdm" for arguments.');
    return;
  }

  if (empty($target_view_mode)) {
    drush_print('Missing target_view_mode. Type "drush help cdm" for arguments.');
    return;
  }

  $entity_view_display = \Drupal::entityTypeManager()
    ->getStorage('entity_view_display')
    ->load($entity_type . '.' . $source . '.' . $source_view_mode);

  if (empty($entity_view_display)) {
    return;
  }

  $items_to_copy = $entity_view_display->get('content');

  $new_entity_view_display = \Drupal::entityTypeManager()
    ->getStorage('entity_view_display')
    ->load($entity_type . '.' . $target . '.' . $target_view_mode);

  $updated = "updated";

  if (empty($new_entity_view_display)) {
    // If it can't load view mode on target type, create it.
    $values = array(
      'targetEntityType' => $entity_type,
      'bundle' => $target,
      'mode' => $target_view_mode,
      'status' => TRUE,
    );
    $new_entity_view_display = \Drupal::entityTypeManager()
        ->getStorage('entity_view_display')
        ->create($values);
    // Change verb for output to user.
    $updated = "created";
  }

  $arr = $new_entity_view_display->toArray();

  if ($field_to_copy == "") {
    foreach ($arr['content'] as $field_name => $field_data) {
      $new_entity_view_display->removeComponent($field_name);
    }

    $definitions = \Drupal::entityManager()->getFieldDefinitions($entity_type, $target);

    $output = [];
    foreach ($items_to_copy as $key => $value) {
      // Check if they are in the entity field definition array.
      // This prevents adding fields that aren't on this content type.
      if (!empty($definitions[$key])) {
        $new_entity_view_display->setComponent($key, $value);
        $output[] = ' -- ' . $key;
      }
    }

    $new_entity_view_display->save();
    drush_print("$entity_type.$target.$target_view_mode $updated from $entity_type.$source.$source_view_mode");
  }
  else {

    $definitions = \Drupal::entityManager()->getFieldDefinitions($entity_type, $target);

    if (!empty($definitions[$field_to_copy])) {
      $new_entity_view_display->setComponent($field_to_copy, $items_to_copy[$field_to_copy]);
      $output = [' -- ' . $field_to_copy];
    }

    $new_entity_view_display->save();

    drush_print("copied field $field_to_copy to $entity_type.$target.$target_view_mode from $entity_type.$source.$source_view_mode");
  }

  if (!empty($output)) {
    foreach ($output as $item) {
      drush_print($item);
    }
  }
}

```

---
Tags: 8, configuration, entities
---


# Question
Title: How can I have admin language English and frontend language another?
I would like to create a site to display the frontend of the site in one language and still keep the backend in English (or another language).

Is there a module like "**Administration Language"** or any configuration for Drupal 8?

# Answer
First go to Administration - Configuration - Regional and language - Languages - Detection and selection tab and make sure to have “Account administration pages“ enabled.

Then go to People and edit your user. Go down to the Language settings section. You should now see a Administration pages language dropdown. Select and save.
> 14 votes

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

That information is shown in the blue box on the page that you linked to.

The linked page has also information on how to configure this in Drupal 8.
> 4 votes

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


# Question
Title: Address field module autofill city and state when zip code is entered
In the United States, cities are split up by a unique 5 digit zip codes (postal code). This postal code in turn tells what city and state it is from. Therefore it is redundant to type the city and state.

**Is there a way, with the Address Field module, to autofill the city and state if a postal code is submited?**

This then leads to the second question, **how to force a correct postal code entry**. By default a user can type any text and it will be accepted.

# Answer
Here is Javascript code that uses zipcodeapi.com API:

```
<script type="text/javascript">//<![CDATA[
$(function() {
    // IMPORTANT: Fill in your client key
    var clientKey = "js-9qZHzu2Flc59Eq5rx10JdKERovBlJp3TQ3ApyC4TOa3tA8U7aVRnFwf41RpLgtE7";

    var cache = {};
    var container = $("#example1");
    var errorDiv = container.find("div.text-error");

    /** Handle successful response */
    function handleResp(data)
    {
        // Check for error
        if (data.error_msg)
            errorDiv.text(data.error_msg);
        else if ("city" in data)
        {
            // Set city and state
            container.find("input[name='city']").val(data.city);
            container.find("input[name='state']").val(data.state);
        }
    }

    // Set up event handlers
    container.find("input[name='zipcode']").on("keyup change", function() {
        // Get zip code
        var zipcode = $(this).val().substring(0, 5);
        if (zipcode.length == 5 && /^[0-9]+$/.test(zipcode))
        {
            // Clear error
            errorDiv.empty();

            // Check cache
            if (zipcode in cache)
            {
                handleResp(cache[zipcode]);
            }
            else
            {
                // Build url
                var url = "http://www.zipcodeapi.com/rest/"+clientKey+"/info.json/" + zipcode + "/radians";

                // Make AJAX request
                $.ajax({
                    "url": url,
                    "dataType": "json"
                }).done(function(data) {
                    handleResp(data);

                    // Store in cache
                    cache[zipcode] = data;
                }).fail(function(data) {
                    if (data.responseText && (json = $.parseJSON(data.responseText)))
                    {
                        // Store in cache
                        cache[zipcode] = json;

                        // Check for error
                        if (json.error_msg)
                            errorDiv.text(json.error_msg);
                    }
                    else
                        errorDiv.text('Request failed.');
                });
            }
        }
    }).trigger("change");
});

```

//\]\]\>

You can see an example here - http://www.zipcodeapi.com/Examples#example1

Since the question is how to autofill a valid city and state based on the user entering a zipcode first, the above Javascript code does that. Click on the example above to see how it works.
> 1 votes

# Answer
For this you can develop your own custom module using dependencies on address field .

1. You need to define a server function that will return the city and state in JSON based on a zip code.
2. Subscribe to change, keyup and input events on an input field.
3. Define a JavaScript function that will call the server function using AJAX. On the success function, you set the fields using the response.

Helping code

```
$("#txtZipCode").bind("change keyup input", function (e) {
        var field = $(this);
        if (field.val().length === 5) {
            showLocation(field.val());
        }
        else
            showLocation("");
    });

function showLocation(zipCodeValue) {
    var txtCity = $("#city");
    var txtState = $("#state");
    if (zipCodeValue.toString().length != 5) {
        txtCity.val("");
        txtState.val("");
    }
    else {
        $.ajax({
            dataType: "json",
            url: "Location/GetZipCode",
            data:
                {
                    zipCodeNumber: zipCodeValue
                },
            success: function (data) {
                    txtCity.val(data.City);
                    txtState.val(data.State);
            }
        });
    }
}

```
> 0 votes

# Answer
May be **Entity reference autofill** will help you to achieve this functionality. There is a remark in project page about this.

> **Addressfield**: Addressfield needs some additional processing in order to be loaded. A sub-module is included to make it work. Enable **"Entity reference autofill addressfield"** and you're good to go.

I didnt tested this, just found while searching.

Hope this will help you.
> 0 votes

# Answer
You might check out this new module from Lush and give it a review in the process.

Address Field Lookup: https://www.drupal.org/sandbox/danielmrichards/2580615
> 0 votes

---
Tags: 7, ajax, entities
---


title: Trouble with the menu Block module

text:
# Question
Title: Trouble with the menu Block module
I am trying to build pages with the main menu displayed in multiple locations. A "main navigation" with top-level items A,B,C,D,E; and each of these has children a1,a2,...b1,b2,... etc.

There is a drop-down navbar menu in the header that is on every page (that displays A B C D E and when you click on any one of them, it shows its children); if you click on any child (say a2), it takes you to a url .../A/a2. That page still has the "main navigation" in the header, but also in the left sidebar it has the sub level menu of A (a1,a2,a3...) with a2 highlighted.

Someone directed me to try the menu block module, but i am not able to get it to display just A's children while in A. Depending on the options I choose for depth etc. I can either show all links (A B C D E a1 a2...e1 e2...) or all the children from all the parents (a1,a2,...,b1,b2,...,e1,e2...).

Using twig debugging, I see it's using the same template as the navbar drop-down menu, so I can't write a separate template either (or can I?)

# Answer
Ok, I *sorta* figured this out. It might be a hack, but if I start with initial menu level: 1, maximum menu levels to display: 1 and fixed parent item to be the menu who's children i want displayed, then it sort of works.

Only caveat is I need to make a separate block for each separate child of the menu. Plus, it is still using the same template to display the menu in both places (header + sidebar). Perhaps using custom blocks and changing its name will generate a new template?

I'd love to hear a better answer if there is one.
> 1 votes

---
Tags: 8, navigation
---


# Question
Title: Can a group of fields be added to $form in buildForm()?
I am defining a custom form to be added to the `$build` array of a specific node, using form elements as defined here.

Is it possible to add a field collection to the `$form` array, like `'#type' => 'field_collection'` or something similar?

# Answer
> 3 votes
There is also Details:

> Provides a render element for a details element, similar to a fieldset.

```
$form['author'] = array(
  '#type' => 'details',
  '#title' => $this->t('Author'),
  '#open' => TRUE
);

$form['author']['name'] = array(
  '#type' => 'textfield',
  '#title' => $this->t('Name'),
);

```

Here is a link to more documentation about details. https://www.drupal.org/node/1898824

The documentation suggests:

> When to use Fieldsets over Details
>
> * When they are semantically related like a date field with year, month, day, time.

Here is the change record from D7 to D8. https://www.drupal.org/node/1852020

> All collapsible fieldsets have been replaced with HTML5 details elements

# Answer
> 3 votes
It turns out fieldset is what I was looking for:

> Provides a render element for a group of form elements.

---
Tags: forms, 8
---


# Question
Title: How to delete a particular variable from a configuration created by a custom module
I have created a custom module and a configuration say 'abc\_settings'. This configuration creates a variable for each vocabulary present on the site like vocab1\_options, vocab2\_options, vocab3\_options etc. I want to delete 'vocab1\_options' when vocabulary 1 (vocab1) will be deleted. How to achieve this ?

# Answer
> 8 votes
**Deleting a config *key*:**

Updating per Berdirs comment, deleting/clearing a key *within* a config object, not deleting the entire config object:

```
Drupal::configFactory()->getEditable('abc_settings')->clear($entity->id() . '_options')->save();

```

**Deleting config *objects*:**

I did this within TVI module, anytime a term or vocab is deleted:

```
/**
 * Implements hook_ENTITY_TYPE_delete().
 * Remove TVI settings when vocabularies are deleted.
 * @param EntityInterface $entity
 */
function tvi_taxonomy_vocabulary_delete(EntityInterface $entity) {
  Drupal::configFactory()->getEditable('tvi.taxonomy_vocabulary.' . $entity->id())->delete();
}

/**
 * Implements hook_taxonomy_term_delete().
 * Remove TVI settings when terms are deleted.
 * @param EntityInterface $entity
 */
function tvi_taxonomy_term_delete(EntityInterface $entity) {
  Drupal::configFactory()->getEditable('tvi.taxonomy_term.' . $entity->id())->delete();
}

```

Of course, you would pass your own config name to getEditable(), and the hook names need to have your module name and not *tvi*.

This will delete any config matching that name when a term or vocab is deleted.

I haven't taken the step yet in my own code, but you could go further and implement a method that before a vocabularly entity is deleted, get all of its children, loop and delete config, then delete the vocab and its config.

Example:

```
Drupal::configFactory()->getEditable($entity->id() . '_options')->delete();

```

---
Tags: 8, configuration
---


title: Modular way to work with form elements

text:
# Question
Title: Modular way to work with form elements
When rendering a simple form element:

```
$form['gender'] = array(
  '#type' => 'radios',
  '#title' => 'Are you a boy or a girl?',
  '#options' => array(
    0 => 'Boy',
    1 => 'Girl',
  ),
);

```

We have

```
<!-- THEME DEBUG -->
<!-- THEME HOOK: 'fieldset' -->
<!-- BEGIN OUTPUT from 'core/themes/classy/templates/form/fieldset.html.twig' -->
<fieldset data-drupal-selector="edit-gender" id="edit-gender--wrapper" class="fieldgroup form-composite js-form-item form-item js-form-wrapper form-wrapper">
      <legend>
    <span class="fieldset-legend">Are you a boy or a girl?</span>
  </legend>
  <div class="fieldset-wrapper">

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'radios' -->
<!-- BEGIN OUTPUT from 'core/themes/classy/templates/form/radios.html.twig' -->
<div id="edit-gender" class="form-radios">

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'form_element' -->
<!-- BEGIN OUTPUT from 'core/themes/classy/templates/form/form-element.html.twig' -->
<div class="js-form-item form-item js-form-type-radio form-type-radio js-form-item-gender form-item-gender">

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'input__radio' -->
<!-- FILE NAME SUGGESTIONS:
   * input--radio.html.twig
   x input.html.twig
-->
<!-- BEGIN OUTPUT from 'core/themes/classy/templates/form/input.html.twig' -->
<input data-drupal-selector="edit-gender-0" type="radio" id="edit-gender-0" name="gender" value="0" class="form-radio">

<!-- END OUTPUT from 'core/themes/classy/templates/form/input.html.twig' -->

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'form_element_label' -->
<!-- BEGIN OUTPUT from 'core/themes/classy/templates/form/form-element-label.html.twig' -->
<label for="edit-gender-0" class="option">Boy</label>
<!-- END OUTPUT from 'core/themes/classy/templates/form/form-element-label.html.twig' -->

      </div>

<!-- END OUTPUT from 'core/themes/classy/templates/form/form-element.html.twig' -->

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'form_element' -->
<!-- BEGIN OUTPUT from 'core/themes/classy/templates/form/form-element.html.twig' -->
<div class="js-form-item form-item js-form-type-radio form-type-radio js-form-item-gender form-item-gender">

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'input__radio' -->
<!-- FILE NAME SUGGESTIONS:
   * input--radio.html.twig
   x input.html.twig
-->
<!-- BEGIN OUTPUT from 'core/themes/classy/templates/form/input.html.twig' -->
<input data-drupal-selector="edit-gender-1" type="radio" id="edit-gender-1" name="gender" value="1" class="form-radio">

<!-- END OUTPUT from 'core/themes/classy/templates/form/input.html.twig' -->

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'form_element_label' -->
<!-- BEGIN OUTPUT from 'core/themes/classy/templates/form/form-element-label.html.twig' -->
<label for="edit-gender-1" class="option">Girl</label>
<!-- END OUTPUT from 'core/themes/classy/templates/form/form-element-label.html.twig' -->

      </div>

<!-- END OUTPUT from 'core/themes/classy/templates/form/form-element.html.twig' -->

</div>

<!-- END OUTPUT from 'core/themes/classy/templates/form/radios.html.twig' -->

          </div>
</fieldset>

<!-- END OUTPUT from 'core/themes/classy/templates/form/fieldset.html.twig' -->

```

So we have 5 Twig templates. It's a lot of boilerplate code which I'm looking to get some control over.

Goals:

* Needs to be for a specific form
* Must be able to override these templates

Ideally, I would want to end up something like here:

```
<div class="gender">
  <div>
    <input type="radio" attributes>
    <label></label>
  </div>
  <div>
    <input type="radio" attributes>
    <label></label>
  </div>
  <div>
    <input type="radio" attributes>
    <label></label>
  </div>
</div>

```

Something I would recognise to be good; Is being able to specify some attribute when defining the form element:

```
$form['gender'] = array(
  '#type' => 'radios',
  '#title' => 'Are you a boy or a girl?',
  '#options' => array(
    0 => 'Boy',
    1 => 'Girl',
  ),
  '#theme_type' => 'foobar',
);

```

And then maybe override something like:

```
foobar--fieldset.html.twig
foobar--radios.html.twig
foobar--form-element.html.twig
foobar--input--radio.html.twig
foobar--element--label.html.twig

```

However having to override 5 templates are a lot, if there is anyway to simplify to only override the inputs, and then everything around would be sucifient.

Any ideas on how to accomplish this? I guess I need to use: https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Render!theme.api.php/function/hook\_theme\_suggestions\_alter/8.2.x

```
hook_theme_suggestions_alter

```

But form there I'm actually not sure how to accomplish these kind of suggestions.

```
function custom_test_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {
  if (!isset($variables['element']['#theme_type'])) {
      return;
  }
  if ($variables['element']['#theme_type'] === 'quiz') {
    $suggestions[] = 'foo__bar';
  }
}

```

# Answer
This is unfortunately really hard right now. The form theming is the biggest part that was not refactored, menu templates e.g. got a lot simpler, but forms are still very complex.

Yes, hook\_theme\_suggestions\_alter() is the right way, but first you need to be able to identify your elements there and more importantly, identify the form you're working with. That's not possible without some form alters, see How can we find the id of the parent form in preprocess\_HOOK() or HOOK\_alter() theme functions?

That hook also doesn't allow you to get rid of templates, only provide alternatives, so you still have those templates, the best you can do is remove the HTML so they're not printing out something anymore.

`radios` is also an especially complex case. Just like `checkboxes`, it actually expands itself into N #type radio form elements during rendering, thats why you end up with even more templates than usual.
> 3 votes

---
Tags: forms, 8, theming
---


# Question
Title: How to show available drush commands per module with a drush command?
For example I would like to see all the commands provided by the features module, I know I can do

```
drush help | grep features

```

But I don't feel safe doing this with all modules present there (you never know when you miss a command). And it often looses important "second lines" such as the shortcut for features-revert-all.
Do you know any command / technique to make sure you get it all safely?

# Answer
You can use the `--filter` feature of Drush. For example, you can use `drush --filter=features` to get all the commands available from the Features module, or `drush --filter=views` to get all the Drush commands available from the Views module.

You could then also pipe that output into a file if you wanted (e.g. `drush --filter=views > views_drush_commands.txt`).

You can find the docs on the Drush homepage.
> 11 votes

# Answer
If the module have less than 4 commands you can't use the `drush --filter=MODULE_NAME` because you will obtain the following message:

```
[error]  The specified command category onlyone does not exist.

```

In this case you can use `drush --filter` and select the number that correspond with *Other commands* (usually at the end of the list).

You can read more about this behavior in: How to integrate the drush help --filter option with your custom module?
> 2 votes

---
Tags: drush
---


title: Get a field value in the proper way

text:
# Question
Title: Get a field value in the proper way
In a custom module, I use the following code to get a field value.

```
$value = $user->get('field_value')->getValue();

```

The returned value is an array. To get a scalar value contained in that array, I should use one of the following lines.

```
$value = reset(reset($user->get('field_value')->getValue()));

```

```
$value = $user->get('field_value')->getValue()[0]['value'];

```

Is there a Drupal, simpler way to get the scalar value contained in the array?

# Answer
> 19 votes
The method `getValue()` is used to get an array:

```
$array = $user->get('field_value')->getValue();

```

If you want to get a scalar use:

```
$value = $user->get('field_value')->value;

```

Both methods look similar, but do different things:

* The method `getValue()` is to get the complete array of a field, which is quite useful for multiple value fields or multiple properties.
* The method `->value` gets the property with the same name. Most standard fields use `value` as the main property.

---
Tags: 8, entities
---


# Question
Title: Why book re-ordering is not being saved?
I'm using Drupal 7.38. When I re-order book pages and then hit the `Save` button, the ordering stays the same. If I open individual nodes and change weight of each one then it works, but that will take a lot of time.

Any idea why the re-ordering is not being saved?

# Answer
It's an old bug when you have too many pages, I've been struggling and finally still doing it through MySQL :

```
it's 'menu_links' table and Weight value in DB , and flush cache well

it's from my old question How to reorder Book module menu through Database?

```

Hello, who deleted My Answer?! - This IS ANSWER not Bug report, indeed! You can use my answer about MYSQL data tables! Why joke and delete?!
> 1 votes

# Answer
The page has a lot of hidden input fields for each book you have. You are hitting the max input var limit set in PHP. Increasing the php configuration setting for max\_input\_vars and it should solve your problem. http://php.net/manual/en/info.configuration.php#ini.max-input-vars
> 1 votes

---
Tags: 7, nodes
---


title: How to disable EDIT tab for webform?

text:
# Question
Title: How to disable EDIT tab for webform?
It would be great if anyone tell me how to disable EDIT Tab. I'm using Drupal 7.

I try with role permission, I successfully disable it for other submitter but failed to do the same for some submitter.

At the same time, I want that the submitter be able to change the workflow state, this is why i check all that permissions.

Thanks for the help.

# Answer
I had installed module tabtamer and it worked exactly like i want.

> Tab Tamer is an administration utility that provides easy re-ordering, hiding, and deactivation of tabs and subtabs. You can also rename tab labels.
> 0 votes

# Answer
For the roles in question, remove their ability to edit webform content types and make sure they don't have something like administer nodes checked off. It sounds like they may have too many permissions assigned to the role(s) that would cause the edit tab to appear. Also uncheck permissions pertaining to 'submissions' other than administrative roles.
> 1 votes

---
Tags: 7
---


# Question
Title: Doing a global OR with the db abstraction layer
I have a function that makes a db query using `db_select`. The problem I'm having is that in a function elsewhere, the query object is applied a couple of conditions, and I want to add an OR clause but the final query ends with an `AND` instead of an `OR`.

Simplified example:

```
function a() {
    $q = db_select('table', 't');
    $q->addField('t', 'field1');
    b($q);
    // Here I want to add an OR so that the query
    // Selects the conditions applied in b()
    // or something else
    $q->execute();
}

function b($q) {
    $q->condition('t.field1', 'some val', '=');
    $q->condition('t.field2', 'some val', '=');
}

```

The way this example is, it would compile to something like

```
SELECT field1 FROM table AS t WHERE t.field1 = 'some val' AND t.field2 = 'some val'

```

I want to make it so that it compiles to

```
SELECT field1 FROM table AS t WHERE t.field1 = 'some val' AND t.field2 = 'some val' OR t.field3 = 'some val';

```

And the OR should be added in place of my comment in `a()`. How would I go about that in a proper way?

Right now I'm solving it with

```
$q->where(' 1 = 1) OR (t.field3 = :v', array(':v' => 'some val'));

```

which compiles to:

```
SELECT field1 FROM table AS t WHERE t.field1 = 'some val' AND t.field2 = 'some val' AND (1 = 1) OR t.field3 = 'some val';

```

but I feel that is just ugly, not to mention potentially buggy.

Using db\_or instead of the line above results in this:

```
SELECT field1 FROM table AS t WHERE t.field1 = 'some val' AND t.field2 = 'some val' AND (field1 = 'some val');

```

That because the db\_or crease some sort of combo, and you have to add more than one condition:

```
$or = db_or()->condition(...);
$or->condition(...);

```

Finally, it would be great to go a step further and create a query like

```
SELECT field1 FROM table AS t WHERE (... AND ...) OR ...

```

**Edit**: The example here is very simple, compared to the actual code, and I can't really modify the `b` function. I need to do the `OR` right where the comment is in `a()`

# Answer
> 1 votes
It is possible to nest `db_and()` and `db_or()` calls, and pass the result into a `condition()` call. See Conditional Clauses documentation page for more information.

> The first parameter of condition() can also accept another conditional object. That inner conditional object will be incorporated into the outer conditional, surrounded by parentheses. The inner object may also use a different conjunction than the outer object. That way, one can build complex nested conditional structures by creating and building up conditional objects "bottom up".
>
> The db\_condition() helper function will return a new conditional object. It takes a single parameter that is the conjunction that object will use. In general, the helper methods db\_and(), db\_or(), and db\_xor() will cover almost any expected case. That allows conditionals to be inserted inline in a query for a very compact syntax.

```
function a() {
  $q = db_select('table', 't');
  $q->addField('t', 'field1');
  $q->condition(db_or()->condition(b($q))->condition('t.field3', 'some val', '=');
  $q->execute();
}

function b($q) {
  return db_and()
    ->condition('t.field1', 'some val', '=');
    ->condition('t.field2', 'some val', '=');
}

```

This should produce the query `SELECT field1 FROM table t WHERE ((t.field1 = 'some val' AND t.field2 = 'some val') OR (t.field3 = 'some val'))`.

---
Tags: database
---