# Question
Title: Is there a way to safely downgrade modules after installing a version that has a database update?
I have a site with a lot of modules running Drupal 7. I just installed a bunch of module updates, ran `update.php`, and then started running some tests, upon which I noticed that one of the module updates broke an important function on my site.

After some more testing, I discovered which module update broke the function (an update from rc1 to rc2). Reverting this module back to the previous version (rc1) restores the function on my site. However, when I installed rc2, there was an update to the database for that module which was performed when I ran `update.php`.

I'm going to wait for rc3/a 1.0 release of this module to update again. However, is it safe to simply re-install the old rc1 version over rc2? Or could this cause major problems down the line and should I instead revert from a backup?

I'm not giving specific module names because I'd like to know what the general best practice (if any) is for "downgrading" modules.

# Answer
> 6 votes
I think the answer is that "it depends".

If the `hook_update_N` just added indexes, then you should be safe. If it added or changed columns, then you could have the instance were particular parts of the module work but others will fail (eg, parts that save to the database). Or, worse, you could start getting inconsistent data in the database for the custom tables. You should also see an error about the database on the status report.

I would look at the module in question, search for the `hook_update_N` definitions and see what changed. It may be documented in the changelog, but I don't always trust that everything was logged. Then make a judgement call about what to do.

# Answer
> 5 votes
I'm using a module called `Backup and Migrate` having set it to backup everyday so I will have a backup when I forget to backup before doing an module update.

I think the answer is yes if you made a backup, and No you can try to use the code with the updated database but if it's gonna work depends on the update. But also mosts database updates add fields or make fields bigger so that won't be a problem. Also the changes are included in the module update so you can easily see what the update did. And even reverse the update manually if you feel like poking around.

The real risk is there if fields or tables are deleted or renamed.

I haven't researched this though. It's just my experience installing modules, and writing own module updates / install files.

While having Backup and Migrate not installed it took me half a day to get everything back to normal ( I hope this helps anyone who is ( a bit ) new to drupal or hasn't found this module yet )

# Answer
> 0 votes
I realize this post is old but it is still active but I had to look for a way to rollback when I updated a bunch of modules when updating from Drupal 7.41 =\> 7.43. I received a php error: `Fatal error: Class 'EntityCacheUserController' not found in /var/www/html//includes/common.inc on line 7999`

I also backed up the files and DB but was looking for a less time intensive way to resolve.

I ran the drush command rebuild-registry (not a standard option). Running the command followed by drush cc all - brought the site back online.

I hope this helps.

/r

---
Tags: 7, updating
---


title: How to update Blob data in users table?

text:
# Question
Title: How to update Blob data in users table?
I am trying to update data filed in users table.

Please suggest a way how to update this field data with help of query or need to follow some other approach ?

```
$old_user_id = 123;
$new_user_id = 456;

$account_old = user_load($old_user_id);
$account_new = user_load($new_user_id);

if ($account_old && $account_new && !empty($account_old->data['uc_stripe_customer_id'])) {
  user_save($account_new, array('data' => array('uc_stripe_customer_id' => $account_old->data['uc_stripe_customer_id'])));
}

```

Thanks!

# Answer
I think this would be a good way to do it. You depending what's currently in the data you might want to merge that with the new data. Easy to remove if that's not important.

```
<?php

$old_user_id = 123;
$new_user_id = 456;

$account_old = user_load($old_user_id);
$account_new = user_load($new_user_id);

// Check to make sure accounts are loaded.
if (empty($account_old) == FALSE && empty($account_new) == FALSE) {

  // make sure account data is populated before trying to act on it.
  if(empty($account_old->data) == FALSE) {

    // unserialize the blob from the user object.
    $account_new_data = unserialize($account_old->data);

    // make sure the key exists. maybe other checks.
    if(array_key_exists('uc_stripe_customer_id', $account_new_data) == TRUE) {

        // merge any existing data with the new data.
        $account_new->data = array_merge($account_new, account_new_data);

        user_save($account_new);
    }
  }
}

```
> 0 votes

# Answer
It's a serialised PHP array.

You would, in my humble opinion, be nuts to try to parse this with SQL.

Use PHP to `unserialize`, make your changes, `serialize` it again, and write the result to the database.
> 1 votes

---
Tags: 7, entities, users, updating
---


title: Drush backup of multisite platform

text:
# Question
Title: Drush backup of multisite platform
Is there Drush command that can backup whole multisite platform:

* database dump of each site
* code of each site
* backup of sites/all or complete core with sites/all
* and all that in just ONE tar.gz

There is a archive-dump command which can backup whole platform code and database, but it does that for each site, and omitting other sites from its archive. And that is a problem because if you want to use that backup, and let's say you have 3 sites in platform, you would have to untar 3 backups of each site, and then merge those so your /sites folder has all three sites there, instead only one per archive.

Second, less annoying problem with that command is, if you provide it argument @sites, it will try to backup default site as well, which is not used on Aegir.

# Answer
> 3 votes
You can try `drush archive-dump default,example.com,foo.com` command to archive the DB and codebase. If it is not possibel through it, then you can create a shell script, which creates backup of the codebase and database.

---
Tags: drush, backups, aegir
---


# Question
Title: Help with $base URL path in settings.php
Since I created my site (long time ago!) I have added content and changed many settings. My URL has always been www.domain.com/'drupalfolder'/(content)

I want to remove the drupal folder from the URL and just have my domain name (www.domain.com/content)

I have moved (manually) all the contents of the drupal folder on the 'public' folder but when I try and log in I get **not found page** or **access denied**. I have tried to clear the caches before and after but still nothing. I had to change the main menu urls manually... I want all the URLs to change automatically!

Am I doing it properly? is there a process I can follow to save me time?

**UPDATE: I do not have access to the .htaccess file as only my host has access to it ---- I am using cPanel**

# Answer
> 0 votes
All URL will be changed automatically, if u have not provide static URL in it. For further checking what is causing the issue, check your apache log (if your server is Apache2)

```
cd /var/log/apache2
tail -100 error.log

```

See the latest error which is showing, or paste it here.

---
Tags: 7, uri, configuration
---


# Question
Title: How do I show 2 images on row 1 and 3 images underneath on row 2 with Views?
I need to create a page on my Drupal website which shows colleague images (colleague profile pics).

I want to position 2 colleagues pics next to each other on row 1 then underneath show 3 images on row 2, as shown in this picture:

I have set up a content type called **Colleagues**, which has fields of `Title` and `Image`. And I have set up a View to read that content and display the images, and the title underneath.

I can display them in whatever order I need, but how do I display them so that there are 2 at top and 3 underneath?

The only way I can think of is to add a field called Row Number, and create 2 Views for each row and display them accordingly, but that seems messy.

Can anyone help?

# Answer
You can define attachment display of view, in which u can display only 2 images with offset 0 under Pager section. and in page you can define image to show as 3, with offset as 2.

As attachment loads above the page, so it will show the structure accordingly.
> 1 votes

# Answer
Maybe you could get what you want by modifying the theming files for your specific view.

If you go to your view edit page, in **Advanced** \>\> **Other** \>\> **Theme: information** you can take a look at which files are being used to construct your view.

Then, if you look at the *Style output* default file, you can see how the table is being made.

You can implement your own template for the table, by adding the corresponding file *views-view-table--your-view-name--displayname.tpl.php* to your module/theme folder.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Views Rss - How to set pager options / items to display via URL argument
I have a RSS feed being built by the Views RSS module. I can configure the pager to display a certain number of items; however, some consumers of my feed only want a few of my latest items from my feed. So I need to pass a limit in the URL to the number of items in my feed. something like this:

www.mywebsite.com/rsslatestnews/50 - For 50 items.
or
www.mywebsite.com/rsslatestnews/2 - For 2 Items.

I've tried implementing the hooks:

* hook\_views\_pre\_build
* hook\_views\_post\_build
* hook\_views\_pre\_execute
* hook\_views\_post\_execute
* hook\_views\_pre\_render
* hook\_views\_post\_render

To no avail, I think the RSS Views module is in some way skipping the typical order views hooks are triggered.

My question is this:

Which hook can I use to set the limit of items displayed by my RSS view?

# Answer
> 0 votes
```
/**
 * Implements hook_views_query_alter.
 *
 * If we have an rss feed view we need to set pager settings from url.
 * If no pager number specified in the url do nothing and use view pager   settings.
 * Otherwise get the items_per_page options from the first argument in the url.
 */

function rss_feed_length_views_query_alter(&$view, &$query) {

  $rss_views = array(
    'rss',
  );

  if (in_array($view->name, $rss_views)) {
    $limit = arg(1);
    if ($limit !== NULL) {
      $view->set_items_per_page($limit);
    }
  }
}

```

SUGGESTED IMPROVEMENT:

> "i'd have used GET parameters rather than path elements - since it's not a different resource, rather it's an option"

I'll accept as an answer anything that implements the suggested improvement. :)

---
Tags: views
---


# Question
Title: Parent term suggestion on entering the child term in term reference field?
I have a term reference field which has the widget `Autocomplete term widget (tagging)`. I want the functionality like, when a user type a child term in that autocomplete field, the system should return a suggestion of the parent term that did you mean `[parent term]`.

Suppose `A` is a parent term and its child term is `B`. So when a user type `B` in the field, it should show a suggestion of did you mean `A`?

# Answer
> 0 votes
I think you'll need to override the taxonomy autocomplete path. Here's what you will need:

1. `hook_menu_alter()` implementation, so your custom module takes over the taxonomy autocomplete suggestions. See `hook_menu()` implementation, specifically `$item['taxonomy/autocomplete']` item in `/modules/taxonomy/taxonomy.module` for more information.
2. You'll need to re-create the core `taxonomy_autocomplete()` function, which is in `/modules/taxonomy/taxonomy.pages.inc`.
3. You'll have to perform a check and see for which vocabulary you need to show suggestions:
    * If it's the vocabulary where you want to have child -\> parent functionality, add the code for fetching the parent term and provide additional suggestions.
    * If it's some other vocabulary, make sure you return the same output as the core function would.

You'll need to add this in a custom module.

```
function YOUR_MODULE_menu_alter(&$items) {
  // This will re-route this path to your custom module, so you can have any
  // additional logic.
  $items['taxonomy/autocomplete']['page callback'] = 'YOUR_MODULE_taxonomy_autocomplete';
}

function YOUR_MODULE_taxonomy_autocomplete($field_name = '', $tags_typed = '') {
  // Copy the content of taxonomy_autocomplete() function here, and add necessary
  // modifications at the end of it.
}

```

Hope this helps.

# Answer
> 0 votes
You can use below code for computing the parent.

```
function demo_pane_taxonomy_autocomplete($field_name = '', $tags_typed = '') {
  // Copy the content of taxonomy_autocomplete() function here, and add necessary
  // modifications at the end of it.

  // If the request has a '/' in the search text, then the menu system will have
  // split it into multiple arguments, recover the intended $tags_typed.
  $args = func_get_args();
  // Shift off the $field_name argument.
  array_shift($args);
  $tags_typed = implode('/', $args);

  // Make sure the field exists and is a taxonomy field.
  if (!($field = field_info_field($field_name)) || $field['type'] !== 'taxonomy_term_reference') {
    // Error string. The JavaScript handler will realize this is not JSON and
    // will display it as debugging information.
    print t('Taxonomy field @field_name not found.', array('@field_name' => $field_name));
    exit;
  }

  // The user enters a comma-separated list of tags. We only autocomplete the last tag.
  $tags_typed = drupal_explode_tags($tags_typed);
  $tag_last = drupal_strtolower(array_pop($tags_typed));

  $term_matches = array();
  if ($tag_last != '') {

    // Part of the criteria for the query come from the field's own settings.
    $vids = array();
    $vocabularies = taxonomy_vocabulary_get_names();
    foreach ($field['settings']['allowed_values'] as $tree) {
      $vids[] = $vocabularies[$tree['vocabulary']]->vid;
    }

    $query = db_select('taxonomy_term_data', 't');
    $query->join('taxonomy_term_hierarchy', 'h', 't.tid=h.tid');
    $query->addTag('translatable');
    $query->addTag('term_access');

    // Do not select already entered terms.
    if (!empty($tags_typed)) {
      $query->condition('t.name', $tags_typed, 'NOT IN');
    }
    // Select rows that match by term name.
    $tags_return = $query
      ->fields('t', array('tid', 'name'))
      ->fields('h', array('parent'))
      ->condition('t.vid', $vids)
      ->condition('t.name', '%' . db_like($tag_last) . '%', 'LIKE')
      ->range(0, 10)
      ->execute()
      ->fetchAll();

      $tags_new_return = array();
      $parent_array = array();

      foreach($tags_return as $tag_key=>$tag_val) {
        if($tag_val->parent != 0) {
          $parent_array[] = $tag_val->parent;
        }
      }

      unset($tags_return);
    $query_1 = db_select('taxonomy_term_data', 't1');
    $query_1->addTag('translatable');
    $query_1->addTag('term_access');

    // Do not select already entered terms.
    if (!empty($tags_typed)) {
      $query->condition('t.name', $tags_typed, 'NOT IN');
    }
    // Select rows that match by term name.
    $tags_return = $query_1
      ->fields('t1', array('tid', 'name'))
      ->condition('t1.tid', $parent_array, 'IN')
      ->range(0, 10)
      ->execute()
      ->fetchAllKeyed();

    $prefix = count($tags_typed) ? drupal_implode_tags($tags_typed) . ', ' : '';

    foreach ($tags_return as $tid => $name) {
      $n = $name;
      // Term names containing commas or quotes must be wrapped in quotes.
      if (strpos($name, ',') !== FALSE || strpos($name, '"') !== FALSE) {
        $n = '"' . str_replace('"', '""', $name) . '"';
      }
      $term_matches[$prefix . $n] = check_plain($name);
    }
  }

  drupal_json_output($term_matches);
}

```

Be sure to apply the check of field\_name in it, I have not applied that check.

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


# Question
Title: How do I create a custom content entity?
There are already some resources describing how to write a custom content entity for Drupal 8. Perhaps the most useful one is the one included in the Examples module. I'd like a super-basic example that introduces Drupal 8 and PHP5 OOP concepts step-by-step, without throwing me in the deep end.

# Answer
# Building a basic content entity type in Drupal 8.

In this case we create a Drupal 8 content entity to match a node from our Drupal 7 site, in preparation for migrating this data.

The entity does not implement the Field API so remains in code throughout. Nevertheless it can be a useful skeleton for building out Content Entities.

### Background.

This stems from the need to build a basic custom drupal 8 content entity to hold data coming in from a migration. Elsewhere we will explore writing tests to drive our field code and plugins for field constraints For the time being it is suffice to say:

Our new Drupal 8 advertiser content entity will have basetable fields:

* UUID
* ID
* Advertiser Name

### Defining a Content Entity in Drupal 8.

First all our custom entities now live at `web/modules/custom`. Inside our custom entity the file structure that we will end up with looks like this:

```
web/modules/custom/advertiser$
├── advertiser.info.yml
└── src
    ├── Entity
    │   └── Advertiser.php

```

We start by defining our custom module in `module_name.info.yml`. This is self explanatory:

```
name: Advertiser
type: module
description: 'Barebones advertiser entity'
package: custom
core: 8.x

```

Meanwhile The basic Advertiser entity class and associated schema is defined in `src/Entity/Advertiser.php`.

We start with an annotation that describes the class that our file contains.

```
/**
 * @file
 * Contains \Drupal\advertiser\Entity\Advertiser.
 */

```

The next thing we do is define a namespace for our Advertiser Entity Class. This will come in handy whenever we want to use our classes. `namespace Drupal\advertiser\Entity`;

Now it is time to define our entity, which we do in an annotation! - **TIP:** This is the actual definition of the entity type it is read and cached so be sure to clear the cache after any changes.

```
/**
 * Defines the Advertiser entity.
 *
 * @ingroup advertiser
 *
 * @ContentEntityType(
 *   id = "advertiser",
 *   label = @Translation("Advertiser"),
 *   base_table = "advertiser",
 *   entity_keys = {
 *     "id" = "id",
 *     "uuid" = "uuid",
 *   },
 * )
 */

```

Because this is a barebones entity we only use a few properties and no handlers (like access). For a comprehensive list of available options for your entity see the docs here: https://www.drupal.org/node/2192175

At this point we have a functional module that defines our custom content entity, however if we go ahead and enable the module we will see that the 'advertiser' table has not been created in the database.

```
drush sqlc
SHOW TABLES;

```

This is because our class doesn't have any methods that explicitly interact with the database. Furthermore we need a description of the bare minimum of methods needed for an entity to interface satisfactorily with the Database.

Generally we can add classes by adding something like `use Drupal\Core\Entity\ContentEntityBase;` after our namespace defintiion at the top of our script. This makes these methods available to our own class, which can *extend* them or in the case of Interfaces, *implement* them.

We do two things, we *extend* an existing **ContentEntityBase** class that already has the necessary methods to interact with the DB, and *implement* an **ContentEntityInterface** to describe...

> the methods that we need to access our database. It does NOT describe in any way HOW we achieve that. That's what the IMPLEMENTing class does. We can IMPLEMENT this interface as many times as we need in as many different ways as we need. We can then switch between implementations of the interface without impact to our code because the interface defines how we will use it regardless of how it actually works. - https://secure.php.net/manual/en/language.oop5.interfaces.php

All this means is that we end up with the following: **Tip** Remember to add any new classes through a `use` statement at the top of our script:

`class Advertiser extends ContentEntityBase implements ContentEntityInterface {`

But we still need use these new useful methods to put something in the database, we start with the basic fields for our entity.

The method baseFieldDefinitions comes from ContentEntityBase class that we are extending.
It takes two parameters:

> The entity type definition. Useful when a single class is used for multiple, possibly dynamic entity types.

And it returns

> An array of base field definitions for the entity type, keyed by field name.

So we implement it like this:

```
public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {

  // Standard field, used as unique if primary index.
  $fields['id'] = BaseFieldDefinition::create('integer')
    ->setLabel(t('ID'))
    ->setDescription(t('The ID of the Contact entity.'))
    ->setReadOnly(TRUE);

  // Standard field, unique outside of the scope of the current project.
  $fields['uuid'] = BaseFieldDefinition::create('uuid')
    ->setLabel(t('UUID'))
    ->setDescription(t('The UUID of the Contact entity.'))
    ->setReadOnly(TRUE);

  return $fields;
}

```

So altogether we have this:

```
<?php
/**
 * @file
 * Contains \Drupal\advertiser\Entity\Advertiser.
*/

namespace Drupal\advertiser\Entity;

use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\ContentEntityInterface;

/**
 * Defines the advertiser entity.
 *
 * @ingroup advertiser
 *
 * @ContentEntityType(
 *   id = "advertiser",
 *   label = @Translation("advertiser"),
 *   base_table = "advertiser",
 *   entity_keys = {
 *     "id" = "id",
 *     "uuid" = "uuid",
 *   },
 * )
 */

class Advertiser extends ContentEntityBase implements ContentEntityInterface {

  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {

  // Standard field, used as unique if primary index.
    $fields['id'] = BaseFieldDefinition::create('integer')
      ->setLabel(t('ID'))
      ->setDescription(t('The ID of the Contact entity.'))
      ->setReadOnly(TRUE);
 // Standard field, unique outside of the scope of the current project.
    $fields['uuid'] = BaseFieldDefinition::create('uuid')
      ->setLabel(t('UUID'))
      ->setDescription(t('The UUID of the Contact entity.'))
      ->setReadOnly(TRUE);
  return $fields;
  }
}

```

Now when we run `drush en advertiser -y; drush sqlc` we can see the advertiser basetable has been added to the database!
> 11 votes

---
Tags: 8, entities
---


# Question
Title: How to hide the text format field set using css?
I followed several recommendations and decided to go with using CSS to hide the text format. I don't want to use another module to do something minor like this. Just want to hide text format for this particular form.

When I look at source I see:

```
<fieldset class ="filter-wrapper form-wrapper" id="edit-conditions-format">
blah blah blah
</fieldset>

```

Then on top of my form render function I do:

```
drupal_add_css('
        #edit-conditions-format {
            display: none;
        } ',
      array('group' => CSS_THEME, 'type' => 'inline'));

```

I have cleared cache and the text format is still available. Any tips?

# Answer
Your code is correct. Just add it to a custom module, and it will work. Most likely it doesn't work because the admin theme is not the same as your front end theme.

Your module would take as little as this:

`YOUR_MODULE.info`:

```
name = Your module.
description = Description.
package = Custom
core = 7.x
version = 7.x-1.0

```

`YOUR_MODULE.module`:

```
function YOUR_MODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'ID_OF_THE_FORM_YOU_WANT_TO_ALTER') {
    drupal_add_css('
      #edit-conditions-format {
          display: none;
      } ',
    array('group' => CSS_THEME, 'type' => 'inline'));
  }
}

```

That's it. You can fetch the empty boilerplate here or if you want to do it properly, have a main custom module where you do all the extra customizations. You can have a look at mine here.

Or you could create a child theme of the admin theme, but that will likely take as much effort as creating a custom module.
> 2 votes

# Answer
i guess you don't use the same theme for everything, and you're using a custom theme. so - this code won't affect the 'backend'.

> you need to alter the admin theme, or the theme you use to edit content.

*so hack your admin theme*, or better sub-theme it, and add your css there. then set this to your new admin theme here: **admin/appearance**
> 1 votes

---
Tags: theming
---


title: Using Webform To Create Page Contnet

text:
# Question
Title: Using Webform To Create Page Contnet
I'm trying to update a website that I didn't create where the entry of anonymous user submissions creates a page once approved by an admin level user. In this approval process you get the chance to review the initial submission, click add/edit submission, and then provide final approval.

**In the step "Add/edit submission" one of the field submissions from the webform submission doesn't carry over while all the rest do.**

I've done a lot of reading on this site to try and find the possible answer, but at this point I'm running out of options of how to update this.

The site uses the following Modules for the form:

* HubSpot Integration
* Webform Webform Clear
* Webform Email Reply (currently off)
* Webform Link
* Webform Rules
* Webform Tokens
* Webform Validation

The form is not using any default fields to pull over the information, nor can I see any tokens being called out that carry over the data anywhere in the WYSIWYG. Additionally, I've checked the currently made templates for incorrect field callouts to draw in the information, and nothing there seems incorrect.

**My question: Using the setup of modules above and the latest cover version of drupal how would I make sure that the anonymous user missing field submission is carried through correctly in the approval process?**

I understand that there are other ways of doing this, and I may eventually go that route, but for now I'm trying to avoid breaking the current user experience for admins to approve the process.

Thanks for the brainstorming session!

# Answer
This is being managed by a JS Injection.
> 0 votes

---
Tags: webforms
---


# Question
Title: Flickr-like responsive photo gallery for Drupal 8
Is there a good Drupal 8 module to display a responsive photo gallery, a la Flickr (example: https://www.flickr.com/photos/tags/red)?

I tried Views Photo Grid but it's not working for me, when I go to create a view type of "Photo grid" per the instructions that option is not listed.

If there's no Drupal 8 module, what'd be the easiest way to go about creating this feature? Creating a photo content type, then a view? Is there a way to pull in the viewport size then dynamically size the thumbnails accordingly?

Thanks.

# Answer
> 1 votes
Drupal 8 has built-in Picture module with support of responsive images. So you need to create new content type "Photo" with image field. Add some photos of new content type. Create new view of type "Grid List" and add Photo image field to display. Or create new view of type "Unformatted", add Photo image field to display, then remove default field formatting, modify CSS.

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


# Question
Title: Ajax button in list to delete row entry - submit function is called instead of callback
I have a themed table on a form. To delete entries in this table I render buttons for each row having a special idx and an ajax callback for each button.

The buttons are rendered perfectly, but when I click on the button, the standard submit routine is called instead of the assigned callback routine. Is there anything I missed?

```
// build header for table
$pheader = array('Name','Action');
// build data array for table
$aPersonsTable = array();
foreach ($aPersons as $key => $value) {
  $form_button['button'.$key] = array(
    '#id' => 'del-p-'.$key,
    '#name' => 'del-p-'.$key,
    '#idx' => $key,
    '#type' => 'submit',
    '#value' => 'Delete',
    '#submit' => 'delete_auction_person_ajax_callback_submit',
    '#attributes' => array('class'=>array('ajax-processed')),
    '#ajax' => array(
      'callback' => 'delete_auction_person_ajax_callback',
      'progress' => array('type' => 'none'),
      'effect' => 'fade',
    )
  );
  $deleteButton = drupal_render($form_button['button'.$key]);
  $row = array($value['dname'],$deleteButton);
  $aPersonsTable[]=$row;
}

$form['persons']['ptable'] = array(
  '#theme' => 'table',
  '#header' => $pheader,
  '#rows' => isset($aPersonsTable)?$aPersonsTable:null,
  '#disabled' => TRUE,
  '#title' => 'Users currently assigned',
  '#empty' => t('No users assigned yet!'),
  '#prefix' => '<div id="ptable_wrapper">',
  '#suffix' => '</div>',
);

```

# Answer
> 2 votes
Remove the `'#submit' => 'delete_auction_person_ajax_callback_submit'`, it does not seem necessary. Adding `ajax-processed` class on the button doesn't seem necessary either. The function `delete_auction_person_ajax_callback` receives $form and $form\_state, and will tell you what input was clicked that triggered the callback, from there you can do whatever it is you need to do.

I built a lot of tables this way, but I don't think I had the form items as a submit type. If I recall, I used buttons.

# Answer
> 1 votes
You set `#executes_submit_callback` to `false` on your submit button to prevent that the submit callback is executed.

```
$form_button['button'.$key] = array(
    '#id' => 'del-p-'.$key,
    '#name' => 'del-p-'.$key,
    '#idx' => $key,
    '#type' => 'submit',
    '#value' => 'Delete',
    '#submit' => 'delete_auction_person_ajax_callback_submit',
    '#executes_submit_callback' => false,
    '#attributes' => array('class'=>array('ajax-processed')),
    '#ajax' => array(
      'callback' => 'delete_auction_person_ajax_callback',
      'progress' => array('type' => 'none'),
      'effect' => 'fade',
    )
  );

```

# Answer
> 0 votes
If you want to prevent submit, use #ajax\['prevent'\] attribute:

```
'#ajax' => array(
  'callback' => 'delete_auction_person_ajax_callback',
  'progress' => array('type' => 'none'),
  'effect' => 'fade',
  'prevent' => 'submit',
)

```

---
Tags: forms, ajax
---


# Question
Title: How can I have the URL path (node slug) be different from the Title?
It seems like this should be super simple, but I can't seem to figure it out...

I have layouts with headings and subheadings, (shown below) where the highlighted/top heading is the page/node's title.

So the issue I'm having, is that the system then makes the slug "*stay-connected-with-campus*" but I want it to be "*parents*" and "*parents*" is just redirecting to "*stay-connected-with-campus*"

Where or how can I control that?

My URL path Settings:

And there are no redirects set:

Thanks!

# Answer
It turns out the site was configured to set URL aliases automatically by default, so as page titles were being changed, the url changed. This created a mess with multiple aliases being assigned to a given URL. Removing the automatic alias setting and cleaning up all of the redirects fixed these issues.
> 0 votes

# Answer
If you want control over the generated URL, then you need to enable the Path or Pathauto modules. Once these are enabled, Edit the piece of content for which you want to set a specific URL path, and go to "URL Path Settings" to do this.
> 1 votes

---
Tags: uri
---


# Question
Title: How can I set a 'global' Exposed filter rewrite for taxonomy terms on a view
How would I go about settings a rewrite for display taxonomy (Rewrite filter options), but as a 'global', instead of having to set each individual value for exposed filter?

I can see the there is place to add individual value overrides for the filter display, but my taxonomies are many and may update occasionally.

So the issue is two-fold; The taxonomies to be displayed on the exposed filter are quite long in some cases (which is needed). And they will be adjusted on the fly by content maintainers.

Instead of:
1 | Display 1
2 | Display 2
3 | Display 3

I would be perfect if I can do:

`[vocabulary:original:name]|[vocabulary:original:description]`

But for some reason it's not working for me.

The additional application of this is that the short tax term can be used on the csv import, but front-end displays the complete long version tax.

So if I can get the actual term to be a 'keyword' and display to front-end users a long term, the back-end user will have a better experience as well.

Currently working with Better Exposed Filters and D7. Thanks

# Answer
> 0 votes
Found a excellent module Token formatters. Can be used in various places, but for this application it's spot on.

Once installed, the formatter for a entity reference field on a view gets and addition in the dropdown 'Tokenized Text'. That in turn allow for a a wider range of token us. \[see all your tokens at Admin -\> Help -\> Token \].

Drop the Token of your choice and swap out between fields or Taxonomies.

In my case I has an additional field on my Taxonomy terms. All the regular places I tried to reference it only gave termID or termLabel as options. Now I can use the build in features of taxonomy terms, but on one of their custom text fields.

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


# Question
Title: How to add order status to commerce_line_item_table view in same way as in the commerce_user_orders view?
I am trying to add user's order status to commerce\_line\_item\_table view same as it is present in commerce\_user\_orders view. When user click on order no in commerce\_user\_orders view and it goes to commerce\_line\_item\_table view here the order status is not present i want to add order status in this view. Any Help please

# Answer
> 1 votes
Well, you can add the `Commerce Order: Order ID` relationship to the view and then add the `Commerce Order: Order status` field and it'll provide the line item's order's status in the view.

Add the relationship:

Then, add the field:

Now, your view will have order status on the line items:

---
Tags: views, commerce
---


title: Connecting Panels with Views

text:
# Question
Title: Connecting Panels with Views
Forgive the obtuse explanation.

I have a content type, called SHOW. this show type has a title and client and supervisor and a number of other fields associated with it.

I have an employee of the company fill out the SHOW information on the website. then, this information is available to all employees - it's an intranet.

I have another content type. It's called REQUEST. The first field in this form is a relate-able auto complete list of the SHOW titles that have been created on our site. This content type has some other fields as well, none that are related to anything else.

I have a panel that displays pertinent information from a show, the stuff I want like title and some of the other fields. All is good. In panels I've overridden the node panel for this content type to do this.

Now here's my problem.

I created a view as a table to show the REQUEST content types. I want to show this view in the SHOW panel. I've managed to do this. BUT, i only want to show the view for the corresponding SHOW that I'm in the panel for. I have 3 shows (these are TV shot titles) and each show has like 6 REQUEST content types filled out for it. Again, I only want to show this view on this panel for this specific show.

I'm so lost. Can anyone help?

# Answer
In your view settings, sound like you just need to (under Advanced) add a CONTEXTUAL filter of Nid and use Content ID from URL.
> 0 votes

# Answer
I don't understand the question but a key thing to do when using panels and views is to add a views content pane and then add arguments from Context in the view settings. It's in the middle of the settings above "allow settings". Any node contextual filters won't work without that.
> 0 votes

---
Tags: views, panels, entities
---


title: Get Route Name from Path

text:
# Question
Title: Get Route Name from Path
I am building a module on drupal 8 to make a redirection after a form is submitted

```
function form_redirect_form_alter(&$form, FormStateInterface $form_state, $form_id) {
    $form['actions']['submit']['#submit'][] = 'ptt_contact_form_blocks_submit';
}

function ptt_contact_form_blocks_submit($form, FormStateInterface $form_state) {
    $form_state->setRedirect($route_name);
}

```

but for the setRedirect, it needs to have the route name. Like if i want to redirect to node/24, then how can i find the route name of the node?

Thanks!

# Answer
check this one

```
function ptt_contact_form_blocks_submit($form, FormStateInterface $form_state) {
    $form_state->setRedirect('node/24'); // node/$node->nid
}

```
> 1 votes

---
Tags: 8, redirection
---


# Question
Title: Ask Drush to list which modules have database updates available
I specifically want Drush to list, of the modules that have available updates, which of those contain database updates. Is this possible with Drush?

**Edit for clarification:** I know `drush up` will list all modules that have available updates, yes, but not all of those updates will have database updates that go along with them. I strictly want a list of updates that have associated database updates.

# Answer
> 14 votes
`drush updatedb --no` (shorthand: `drush up -n`) will list them and take no further action.

# Answer
> 2 votes
This is a feature request; please post it in the drush issue queue. Note that this is not a terribly easy thing for Drush to do; it would have to download all of the projects to be updated and inspect them prior to prompting you.

# Answer
> 1 votes
"drush pm-update" will give you a list of modules that have updates available.

# Answer
> 0 votes
There is a drush command that will be better for you than `drush updatedb --no`, as it will not clear the cache (which could really affect performance on a production site):

```
drush8 --uri=www.example.com updatedb-status --format=json
[
    {
        "module": "Metatag",
        "update_id": 7104,
        "description": "Remove the entity revision ID from the translation strings. "
    },
    {
        "module": "Metatag",
        "update_id": 7105,
        "description": "Fix the output translation strings. "
    }
]

```

Documentation is at http://drushcommands.com/drush-8x/core/updatedb-status/

---
Tags: drush, updating
---


title: Complex Validation

text:
# Question
Title: Complex Validation
How can I do complex validation on the forms for adding content? An example of what I want to do, is ensure that either one field or another is filled out. It is fine if both are filled out, or if either one is filled out, but not if neither is filled out. I'm interested in the best way of doing this kind of more complex (beyond just a single required field) validation in general, but the specific case above can serve as the specific answerable question here. Links to appropriate documentation/resources also appreciated.

# Answer
The field validation module allows advanced validation rules without having to write custom code.

It includes (emphasis mine):

> The following validators are currently included (7.x-2.x):
>
> * Regular expression
> * Numeric values (optionally specify min and / or max value)
> * length (optionally specify min and / or max length)
> * number of words (optionally specify min and / or max words )
> * Plain text (disallow tags)
> * Must be empty (Anti-Spam: Hide with CSS)
> * Words blacklist
> * number of selections (optionally specify min and / or max selections )
> * Unique
> * Match against a field
> * Match against a property
> * Specific value(s)
> * **Require at least one of several fields**
> * Equal values on multiple fields
> * Unique values on multiple fields
> * PHP Code (powerfull but dangerous)
> * URL (support internal path and external url validation)
> * Email
> * Pattern (Regular expression lite)
> * Date range2
>
> Following validators are included in sub module field validation extras:
>
> * Color(HTML5)
> * Date(ISO)
> * EAN number
> * Field collection unique
> * Integer values
> * IP Address
> * Numeric(HTML5, with the option to specify min/max/step)
> * Regular expression (Perl-Compatible)
> * Phone
> * Required field
> * Require some of several fields
> * Postal code(depend on Postal Code Validation, support Address Field)
> 3 votes

# Answer
If you are creating forms using webforms module you can easily set all these dependencies. Without even writing code.
> 1 votes

---
Tags: 7, forms
---


# Question
Title: Defining a Complex Sort (by stripping out a pre-defined set of words) with Views
I'd like to do a more complex sorting on my Drupal 7 View. Specifically, I'd like to sort by a particular field alphabetically (easy - that's the default). **However, before the View sorts the field I want it to strip out (a predefined) set of words at the beginning of the field (if they exist) such as the word 'the' or 'a' and sort based on the words that follow**.

Does anyone know if this is possible?

My workaround will be to just create a 'sort by' field in the content type.

# Answer
Have you tried Views Natural Sort -module?

> Provides a views filter that sorts node titles by a more natural manner by ignoring articles like "The" and "A."

Not sure if it matches your needs because of *"sorts node titles"* and in your question you talk about particular field. But maybe you should try it?

At least you can get base for custom module if you need to build one.
> 3 votes

---
Tags: views
---


title: How to set/get base_path in D8?

text:
# Question
Title: How to set/get base_path in D8?
How do I get the base\_path in Drupal 8? When I use the `base_path()` function it always returns just the `/`. I know in Drupal 7 you could set the base\_url in the settings.php file, but how do I set it in Drupal 8?

I'm trying to create an absolute url for social media sharing.

# Answer
> 6 votes
You're looking for `$base_url` global:

```
global $base_url;

```

If you want to have this in a preprocess function, you'd have to call it *within* that function; for example:

```
function YOUR_THEME_preprocess_whatever(&$variables) {
  global $base_url;
  // Now you can use it.
  $variables['base_url'] = $base_url;
}

```

---
Tags: 8
---


# Question
Title: How to implement a calendar based system for loaning of equipment?
I have looked MERCI over and it appears to be a great module but sort of like swatting flies with sledgehammers. We are a public library support agency and, among other items, we offer month long loans of 3D printers.

I'm looking for a way to implement a simple item registration system, that is calendar based so monthly calendars can be printed.

I like Basic Cart but need more of a library loan approach than a sales approach.

Any suggestions?

# Answer
> 2 votes
Below is a summmary of the modules you may want to look at. These modules have a stable release for D7, and also for D6 (quotes are from their project pages):

* Availability Calendars.

> ... allows you to add an availability calendar to entities. Example use cases are tourist accommodation, e.g. bed and breakfast, holiday homes or self catered apartments, and car or motor bike rental.
>
> An availability calendar shows your customers at what dates your accommodation is still available and at what dates it is already booked.
* Simple Reservation.

> ... provides a simple and easy way to reserve items which can be created by the administrator. Examples for it's usage can be hotel rooms, boats, cars, airplanes, basically anything you can think of which can be reserved by one individual.
>
> The module provides the possibility to create reservations for other users (dependend on the permissions), and provides also restrictions in the maximum number of reservations a user can make and a maximum time a reservation can be made in advance.
>
> There is NO support for payment, booking and what ever one could imagine beyond the pure and simple reservation, and it is also NOT intended to create more than this simple functionality.
* MERCI.

> ... can extend any content type into a list of unique reservable items (like studios) or buckets of interchangeable items (like DV cameras). We followed the approach used by Organic Groups, Feed API, and Scheduler and added MERCI's configuration to the Edit tab of those content types.
* Resource Conflict.

> ... allows for users to book resources for use during events. For example, a student can book a microscope for use within their lab.

# Booking Systems Comparison

Refer to Comparison of Booking System modules for a comparison of various modules related to bookings / reservations.

This comparison contains some other modules (not mentioned in my answer here) that might be worth considering also, e.g. in case of requirements that are slightly different (as compared to those in the question here).

# How to pick the module that fits best

I've ordered my recommended shortlist above by number of reported installs. Though that is often a good first indicator, it should not be used as the only criterium to pick a module.

So do your homework to pick the right one for you. E.g. by using criteria such as those I often use for selecting module, as mentioned in the community documentation about Maintenance Scorecards.

Here is the intro about it (from that page):

> ... contains a list of 23 criteria (=28-5) that might help to evaluate the maintenance and support of contributed modules. Below is an attempt to apply those criteria to each of the native charting modules ...

Obvious, these scorecards are related to "charting modules", but the same criteria are applicable, IMHO, wheneven you need to decide between multiple modules.

**Disclosure**: I'm the author of that community documentation page (partially inspired by the 28 criteria in the issue linked near the beginning of the scorecards paragraph).

# Answer
> 1 votes
MERCI was designed to make the most efficient use of interchangeable items by creating a reservation for a type or item instead of a specific item. It also allows limiting the type of equipment a user can reserve based on role. This prevents several short reservations from blocking longer reservations of any item, but it creates a lot of unnecessary overhead if you are only making long reservations for specific items.

While it is a little dated, https://groups.drupal.org/node/137544 is still the best comparison of Drupal based reservation and booking systems I know of.

Based on what you've described, https://www.drupal.org/project/resource\_conflict is probably all you need.

Good luck!

---
Tags: 7, datetime
---


# Question
Title: image share issue for single variant product
I am using Service Link module. On product display page, one of the product variant is displayed. The products having more than 1 variant, sharing proper image \[shows meta property="og:image" content="..." in view source \]. But single variant product is not producing og meta tag.

I am using token \[node:field-product:1:field\_images\] in Images input field of 'Open Graph' meta tags.

# Answer
> 1 votes
Use the 0 instead of 1 in node image token

1) Go to : Site setting -\> configuration -\> Metatag

2) Edit the “Node”

3) Click On Open Graph field set

4) Add “\[node:field-product:0:field\_images\]” in Image

Hope this will solve your issue

---
Tags: commerce
---


# Question
Title: Can't get Corresponding node references to work
I installed the 'Corresponding node references' module to avoid double editing between nodes that should point to each other (by means of node reference fields). I have followed the instructions to first create nodes with node reference fields and manually editing these fields so that node A point to node B. Then I checked the box in the modules settings page on admin/config, that indeed showed this correspondance. But I still have to double edit nodes of these same types. The "other" node is not automatically updated with a reference... Any suggestions? The site is Drupal 7.42.

# Answer
Solved! It turns out that CNR does not support other languages than English in the stable version. I just installed the dev version and now it works wonderfully. Thanks for maintaining this useful module!
> 0 votes

---
Tags: nodes
---


# Question
Title: Programmatically creating multivalue field with a button of add another
In the field ui, we can create a textfield with unlimited values. Which has button of add another, which when clicked added another field with a remove button.

I want the same functionality in my custom form. How will I create a textfield with unlimited values?

# Answer
Here is a nice article on how to do it using Form API http://rapiddg.com/blog/use-ajax-support-multiple-item-values-custom-drupal-7-forms

Hope this helps.
> 1 votes

# Answer
Use Ajax. Here you have an example where an Ajax action will change the values of a select field.

Change the disabled status of a form element via Ajax

You can adapt the code in order to add fields instead of just replacing them. The method would be similar to that done with simple pure AJAX, but you will benefit from using the Drupal FORM API.
> 0 votes

---
Tags: 7, entities
---


# Question
Title: Display Suite code field – how to use another image field conditionally
In my content type I want to show the main image if the thumbnail field is empty. So I use the Display Suite code field and I enter the following code:

```
<?php
dsm($entity);
if(empty($entity->field_thumbnail)){
    print_r('Thumbnail missing');
    // What code to put here to enable or render another image field
}
?>

```

When the tumbnail is missing the above code works, but instead of text I want to display another image field, when the thumbnail is missing. I have tried everything I can think of, but the main image dose not show :-(.

# Answer
> 1 votes
It's because you have nothing in renderable format yet.

Look at function field\_view\_field

> Returns a renderable array for the value of a single field in an entity.

Then change your code like this:

```
<?php
dsm($entity);
if(empty($entity->field_thumbnail)){
    $renderable = field_view_field('node',$entity,'field_main_image',array('settings' => array('image_style' => 'thumbnail')));
    print drupal_render($renderable );
}
?>

```

Note that this is not the only way to get html from field values. You can use theme functions and load that with values you find on $entity object and print that if you wish.

---
Tags: 7, theming, display-suite
---


# Question
Title: Why does the "admin/modules" page show up in the wrong language?
The error appears on a single language page with just one other language than English enabled (here: German) and set to default. All other admin pages show the the right language. Admin theme is "seven". I know, this is probably to broad or localized, but I can't wrap my head around this one...

**Update:** I have installed "Administration Toolbar" and this fixes at least language error in the toolbar. If i deliberately enable the "better toolbar" - option (that means 2 toolbars, one is drupal core and the other from "Administration Toolbar" at the same time), one shows up in German as it should and the drupal core one still in English.

But all the other text strings are still in English. Although they are present and properly translated on the "translate interface"-page (admin/config/regional/translate/translate).

I have installed the latest .po (7.43) file for German, cleared cache several times but to no avail.

Any hint where to look?

**UPDATE II:** Bug is related to Features module (https://www.drupal.org/node/2636140) That one was hard to track down.

**UPDATE III:** The bug was fixed in the latest Feature module update (7.x-2.8)

# Answer
> 1 votes
The bug described in my question is related to the Features module. I found this by chance, when updating modules on another drupal-site, when afterwards the same error appeared. So I disabled every updated module one after another. After disabling Features everything went to normal. A quick scan of the modules issue queue revealed some other people with the same symptoms. Reference:

Enable feature module cause modules listing page into English.

\_features\_set\_export\_language is clearing drupal static cache too aggressively breaking search and possible many other modules

# Answer
> 3 votes
I did a similar verification in one of our sites, which has 3 languages (EN, NL and FR). I disabled the "module\_filter" module, so that I could see what the result would be if I look at what's shown on `admin/modules`. I also use "admin menu", but for my verifications I've not experimented with anything related to that menu (I just wanted to check what the CONTENT of `admin/modules` actually is, depending on the language I used. And I experimented with EN and NL (=Dutch), assuming that FR would give similar results like NL. And I've been using the (same) Seven theme for admin

To actually do my experiments, I've enabled the "language switcher block" so that it is shown within my theme used for Administration. I have this block shown in the "Content" region above the block "Main Content Page" (so that I can switch between EN and NL for my experiment). BUT: nowhere in the question here it says anything about using that "language switcher block". So that's already something for you to check: you are aware I assume about how to use that block for switching languages, right?

Anyway, when I then use that language switcher block to switch from EN to NL, PARTs of what is shown on that page is in NL (Dutch), though other parts remain in EN. E.g.:

* the descriptions for my modules (from the .info files) are shown in Dutch
* but the strings like "Requires" and "Required by" are NOT translated in Dutch. Though the values like "(enabled)" or "(disabled)" or also translated to NL, like to "(ingeschakeld)" or "(uitgeschakeld)".
* the (hardcoded) tekst near the top, like "Download additional ..." is NOT translated.
* typical messages (in green, yellow or red) near the top are translated to NL also.
* Module names, like "Color" are not translated (to something like "Kleur").
* links like "configure" are also translated to "instellen".
* module groups like "Core" are translated to "Kern".

With all this, I have the impression that by using the "language switcher block" and setting it to the NL-language, this `admin/modules` page gives me an "as good as it gets" translated version of that entire page. But if you don't use that "language switcher block" (to switch to NL), then everything remains in EN (of course). And for things that are not translated, I guess that's because it's either not using the typical `t()` function, or the required translated string is still missing (for NL in my case).

Not sure to what extend it will actually answer your question, but at least it should help to understand what is happening, and how the "language switcher block" seems to be part of the puzzle.

But, don't worry ... D8 has a lot of improvements for multi-language stuff (not sure yet about this specific "issue" however ...).

# Answer
> 1 votes
To get rid of the dual toolbars, just disable the toolbar module from modules and you'll just have adminstration menu toolbars left enabled.

As for the language issue, please check the link url, as I assume you're using admin overlay, then the overlay part has it's own language tag as such:

http://dev.mysite.com/**en**/blog/lalala#!=&overlay=**en**/admin/modules

Notice the two language "variables"?

# Answer
> 1 votes
@Pierre.Vriens I have some slightly different results. Language detection had to be set to "Determine the language from the URL (Path prefix or domain)." though. I have enabled dutch to test. Enabled is just the basic i18n module.

# Answer
> 0 votes
Use that module (admin\_menu) also after disabling toolbar module it will display menu links when you hover the parent items which eases navigation to internal pages by just one click.

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


# Question
Title: Should I use the Rules module to implement custom code when performing state transition?
I need to run some custom code when I go from state A to state B (using the workflow module).

Should I implement this with the Rules module and call my function from there or implement all of it in `hook_workflow` from a custom module?

**In short, what is the Drupal approach?**

# Answer
Using the Rules module for this is indeed an option, whereas you should be able to implement your "custom code" using the **Rules Action** to "**Execute custom PHP Code**". If you do, make sure to not forget the PHP filter (otherwise you'll run into "Rules "Execute custom PHP Code" option not available ...").

Of course, that required 'PHP filter' might be your show-stopper. BUT: are you sure you need "custom code" at all? There may be alternative (site building only) techniques to even not need that "custom code" (and hence you'd avoid the need for that PHP filter also). And/or as a variation, you could write your own (custom) Rules Actions also ...

Not to forget these benefits also:

* Less custom code (= easier to maintain and/or upgrade to future Drupal versions).
* Possible out-of-the-box integrations with other modules, such as Flag, VBO etc.
> 1 votes

# Answer
If I understand your question correctly, both are Drupal approaches. Here are the main differences:

1. If you do this through Rules, you will allow site builders / administrators to change, enable and disable this without touching the code. Also, adding new actions later on will be much easier, because you can just use the admin panel.
2. If you do this through code, you will be able to track the changes through CVS, you will probably have no limitations on what you want to achieve, and there will be less chances that whoever manages the site does something wrong.

Ultimately, it's up to you and your client. If you don't see this changing in the future, or if it's something complex, do it in the code. Otherwise, Rules might be an easier option.
> 0 votes

# Answer
Thank you both for you answers. I now see that there are pros and cons between the both approaches.

I used the workflow approach with the motivation that the triggers and conditions I set up will be easier to migrate to other Drupal versions (I also tried to implement it with a custom module but the result was all but satisfying)
> 0 votes

---
Tags: 7, rules, workflows
---


# Question
Title: Drupal 8 custom block with html and javascript
In Drupal 8 what is the process for creating blocks with html and javascript?

Here is my sample code for creating the block

```
class TopNewsBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
     //Fetch data
     return array(
      'type' => 'markup',
      '#markup' => '<table id="example_table"></table>',
      '#attached' => array(
        'library' =>  array(
          'custom_cms_blocks/dataTables.dataTablesjs',
          'custom_cms_blocks/top-news-library'
        ),
      ),
     );
  }

}

```

It works but the problem I have is - I want to seperate out the html code from the php code. Is it possible to include a html file within the block just like the way a javascript file is attached as a library?

# Answer
You need to use `hook_theme()` in your module, and declare a new Twig template that you want to use for your block.

Here's an example that needs to go to `YOUR_MODULE.module` file:

```
function YOUR_MODULE_theme() {
  return [
    'YOUR_TEMPLATE_KEY' => [
      // Here you can pass any variables you want, if necessary.
      'variables' => ['var1' => NULL],
    ],
  ];
}

```

Then create a folder called `/templates` in your custom module, and `YOUR_TEMPLATE_KEY.html.twig` file where you can have any markup you want. See below how to use the variables you pass to the template:

```
<div id="your-block">
  {{ var1 }}
</div>

```

Finally, to use it:

```
public function build() {
  return [
    '#theme' => 'YOUR_TEMPLATE_KEY',
    '#var1' => 'Variable one passed here',
  ];
}

```

Hope this helps.
> 15 votes

---
Tags: blocks, 8
---


# Question
Title: How to prepopulate the currency of a commerce_price field
I want to prepopulate the currency (select list of available currencies) of a commerce\_price field.

(edit – specify my question):

I don't want to prepopulate any value (e.g. EUR) for my field as a default value for all new content. I need to have different currency values prepopulated through content-create links out of different views.

Example (I know the syntax doesn't work, that's my problem):

1st Link: http://www.example.com/node/add/contenttype?\[curreny-value\]=USD

2nd Link: http://www.example.com/node/add/contenttype?edit\[title\]=EUR

The curreny value should be visible but disabled (not editable) in any prepopulated forms.

Is that possible with the prepopulate module or do I need a hook?

# Answer
> 1 votes
You can use Commerce Multi Currency module.

> This module enhances some of the multi-currency capabilities of Drupal Commerce.
>
> Current features:
>
> UI for fine granular definition of exchange rates. (Every currency combination can be defined separately if needed) Synchronization of currency exchange rates directly from the European Central Bank (ECB). UI to specify which rates shall be synchronized and which are handled manually. Generation of currency specific price fields inclusive generation of rule-set to handle them. hooks for easy integration of custom currency exchange rate sources.

This will give you a 'Price with currency' widget for your field.

And you will have a dropdown with all active currencies next to the price.

---
Tags: commerce
---


# Question
Title: Taxonomy manage fields wrong field edit url
I have updated my project to the latest updates available using drush and suddenly found no field names and wrong field form url in

```
 admin/structure/taxonomy/%taxonomy_name/fields

```

As in the picture, have that issue happened before and how to fix

**Edit:** I coudn't also be able to add new fields and fatal error occurs

```
FieldException: Attempt to update an instance of a nonexistent field . in field_update_instance() (line 557 of /modules/field/field.crud.inc

```

despite being able to add/edit/delete terms

manage display return error

```
Fatal error: Unsupported operand types in /modules/field_ui/field_ui.admin.inc on line 1025

```

The issue is reported in issue nr 1275900.

It only happened with taxonomy and other entities work fine.

# Answer
The problem solved by simply patching the field module file-\> field.module function named **field\_extract\_bundle**

```
function field_extract_bundle($entity_type, $bundle) {
  if (is_string($bundle)) {
    return $bundle;
  }

$info = entity_get_info($entity_type);
if (is_object($bundle) && isset($info['bundle keys']['bundle']) &&     isset($bundle->{$info['bundle keys']['bundle']})) {
return $bundle->{$info['bundle keys']['bundle']};
}
//ADDED THAT ELSE
else{
  return $bundle->machine_name;
 }
}

```

the function tries to return the machine name of the entity as appeared above.

By doing some debugging I realized that the the object sent in the calling function **field\_ui\_field\_overview\_form** file-\>field\_ui.admin.inc is n't the same as sent in drupal script before our continuous development in that project.

We added many other modules and edit configuration but the most related that **I think caused that issue is features exporting the taxonomy vocabulary** as the bundle object is the same exported in features so it may be some missing or conflict happened when deploying vocabularies with features

Please contribute your ideas!
> 1 votes

# Answer
I had the exact same issue, and the cause turned out to be a bug in the Commerce Services module. There is a working patch for this in the module issue queue: https://www.drupal.org/node/2024813#comment-7718289
> 0 votes

# Answer
Re-install website if possible.

You can find the solution for `field_ui.admin.inc` here: Manage Custom Display: Unsupported operand types in field\_ui/field\_ui.admin.inc

> Edit field\_ui.admin.inc line 1026:

```
$settings += field_info_formatter_settings($formatter_type);

```

> to

```
$settings .= field_info_formatter_settings($formatter_type);

```

> Open the error page, save it and then change back the code.
> -1 votes

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


# Question
Title: Git making code changes in local branch 'develop' and push to Acquia Cloud Dev
I cloned *Drupal 8 core and modules* from my Acquia Cloud distro into my local repo.

In my local repo I have 2 branches `* develop`and `master`. Currently I am in `develop` branch. I made some small changes to the `.gitignore` file and in `sites/default/settings/php`

(in the `develop` branch i want to make all my changes to code, themes and add contributed modules).

Currently i am in `develop` branch. When i try from *Dev desktop*: **Push code to Cloud Dev** I get this message:

> NOTE: Your locally deployed branch 'develop' doesn't match 'master' deployed in the Cloud environment 'dev'. You will have to deploy 'develop' in the Cloud to see your code changes.

I know I get this message because I am currently in `develop` branch. But what do I have to do exactly before **Push code to Cloud Dev** to avoid this error message? What is the recommended procedure exactly to make changes to my code locally (on another branch) and **Push code to Cloud Dev**? And is it advisable to make those changes to code on another branch e.g. `develop`?

**Update:**

1. I select `develop` in Acquia Cloud dev environment after `git push
origin develop`. Till when? When do i have to choose `master` again?
2. In my local repo i have added branch `develop` to add all my contributed modules and to develop the frontend etc. When do i have to merge it to `master` exactly? Or do i have to stay on `develop` all the time?

# Answer
> 1 votes
This simply means you need your `develop` branch to be pushed to the remote Acquia Cloud repository.

`$ git push origin develop`

Once you do so, just select `develop` in your Acquia Cloud dev environment. You'll now by in synch between your local and remote branch and will be able to push code as you expect.

UPDATE:

1. Using the `develop` branch can be permanent or not, it's up to you. You can, say, have `develop` always checked out in dev, `master` in stage, and a git tag in prod. `develop` would then be your cutting-edge branch while `master` would be safer and primarily for QA. Sometimes, you'd have to delete `develop` and create it again from `master` to clean things up. It's part of a normal workflow.
2. Don't be mistaken between a feature branch and a regular branch. `develop` isn't a feature branch, it's an integration branch. This means that you could have a feature branch locally called, say, `twig-fixes` that you would merge with `develop` when you're happy with the changes. You would then test your feature one last time in the `develop` branch locally and/or on Acquia Cloud, and then would take it from there.

NOTE: always create feature branches from `master` as it's your stable branch.

Example workflow:

```
$ git checkout master
$ git pull
$ git checkout -b twig-fixes

```

Do your work and commit changes to the feature branch, and, when you're ready to test your changes on the Acquia dev environment, merge your branch into the `develop` branch and push it to origin:

```
$ git checkout develop
$ git pull origin develop
$ git merge twig-fixes
$ git push origin develop

```

If all looks good, merge the feature branch into `master` using the `squash` option, to compact all commits into one commit only.

```
$ git checkout master
$ git merge --squash twig-fixes
$ git commit -m "Squashing twig-fixes"
$ git push origin master

```

If all looks good again in `master`, then you're free to delete your feature branch.

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


title: Adding list of nodes to another node

text:
# Question
Title: Adding list of nodes to another node
I have a content type (named "Category") and another content type ("Article"). I want to "Category" nodes have similar functionality as taxonomy term in a way of option to assign "article" nodes to them and display list of "article" nodes teasers on the "Category" page too.

For example: Lets say I have "Category" node named "People". And several "Article" nodes ("Joe", "Frank", "Peter") somehow (part of my question) assigned to "People". When I go to "People" page, I want to see this node content and below also teasers of all assigned "Article" nodes. And I want this not only for a specific node, but for all nodes of content type "Category". How to attain this? Maybe something like taxonomy terms view, but adapted to nodes instead of taxonomy terms?

I know it's easy with taxonomy, but I want to avoid that way - because of buggy taxonomy menu and other things. Thanks

# Answer
You can use Entity Reference module to create relations between the nodes you need.

https://www.drupal.org/project/entityreference

And it works well with Views (for both forward and backward references)
> 1 votes

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


title: Using the same hook more than one times

text:
# Question
Title: Using the same hook more than one times
I have several custom modules and each one of them serves different functionalities. Each module contains from few to many hook implementations and inevitably there are cases where I have to use a hook more than one times between the modules, hook\_menu for example.

What are the downsides (if any) of using the same hooks more than one times in different modules ? Is that recommended ? What about performance?

Thanks!

# Answer
That's exactly how it is supposed to work. Hooks are functions defined by Drupal for you to add functionality to the system through your modules. Hooks are like open doors for you to add things.

From Drupal's documentation:

> To extend Drupal, a module need simply implement a hook. When Drupal wishes to allow intervention from modules, it determines which modules implement a hook and calls that hook in all enabled modules that implement it.

Obviously, the more hooks defined in different modules, performance gets hit. But you can't avoid that. You shouldn't stop adding functionality to your modules through hooks because of this.
> 2 votes

---
Tags: hooks
---


# Question
Title: Facebook scraper ignores default language
I have a Drupal 7 setup with an internationalized site. The default languages is English but the content is also available in German. However the site focuses on a German audience. As in Drupal you cannot switch the default languages without messing up all string translations, we have a custom language negotiation rule implemented (`hook_language_negotiation_info()`) that makes sure if no session or query parameter (like `lang=en`) is set, the site is shown in German. So, to make it short: If an user accesses our site like this:

http://www.example.com

it will be shown in German. Nevertheless Facebooks open graph scraper scraps the site always in English, as it would add programmatically `lang=en` to all URLs. How can that be? we have the following language specific meta tags:

```
<link href="https://www.example.com/node/581?lang=en" rel="alternate" hreflang="en" />
<link href="https://www.example.com/task/581" rel="alternate" hreflang="de" />
<meta property="og:locale" content="de_DE" />
<meta property="og:locale:alternate" content="en_US" />

```

Does anybody know, what I could do, to convince Facebook open graph scraper to scrape the German version as default?

# Answer
Without knowing exactly how the following tags are generated I cannot provide the exact solution to your issue, but only to point out what causes the Facebook to grab EN version.

```
1. <link href="https://www.example.com/node/581?lang=en" rel="alternate"
> hreflang="en" />

2. <link href="https://www.example.com/task/581"
> rel="alternate" hreflang="de" />

```

Tags 1 & 2 have `rel` attribute set to `alternative`, which tells facebook that both links from tag 1 & 2 can be used for fetching info. Therefore it grabs the first one in line.

Each page should have `rel="canonical"` tag that will tell facebook and all other crawlers, that it is a primary url for that page that should be used for fetching info.

I do not know if you have a link tag with `rel="canonical"` in your source code, as you only copied a portion of your meta tags. I suggest you check if it is present, and what page version it points to. If it is not present, add it.

Also, meta tag og:url should point to the right version of the page.

```
<meta property="og:url" content="https://www.example.com/task/581" />

```

Test your tags by fetching new meta info via Facebook Open Graph Debugger.
> 1 votes

---
Tags: 7, i18n-l10n, social-network
---


title: How do I generate a form knowig its ID?

text:
# Question
Title: How do I generate a form knowig its ID?
Using Drupal 8, I want to use registration form outside user/register.

I can generate the user login form but I couldn't find how to get the `user.register` form.

So my question is, how can I render the user registration form?

# Answer
> 2 votes
The user register form is located in `Drupal\user\RegisterForm`. Check the annotation on the User class.

```
/**
 * Defines the user entity class.
 *
 * The base table name here is plural, despite Drupal table naming standards,
 * because "user" is a reserved word in many databases.
 *
 * @ContentEntityType(
 *   id = "user",
 *   label = @Translation("User"),
 *   handlers = {
 *     "storage" = "Drupal\user\UserStorage",
 *     "storage_schema" = "Drupal\user\UserStorageSchema",
 *     "access" = "Drupal\user\UserAccessControlHandler",
 *     "list_builder" = "Drupal\user\UserListBuilder",
 *     "views_data" = "Drupal\user\UserViewsData",
 *     "route_provider" = {
 *       "html" = "Drupal\user\Entity\UserRouteProvider",
 *     },
 *     "form" = {
 *       "default" = "Drupal\user\ProfileForm",
 *       "cancel" = "Drupal\user\Form\UserCancelForm",
 *       "register" = "Drupal\user\RegisterForm"
 *     },
 *     "translation" = "Drupal\user\ProfileTranslationHandler"
 *   },
 *   admin_permission = "administer users",
 *   base_table = "users",
 *   data_table = "users_field_data",
 *   label_callback = "user_format_name",
 *   translatable = TRUE,
 *   entity_keys = {
 *     "id" = "uid",
 *     "langcode" = "langcode",
 *     "uuid" = "uuid"
 *   },
 *   links = {
 *     "canonical" = "/user/{user}",
 *     "edit-form" = "/user/{user}/edit",
 *     "cancel-form" = "/user/{user}/cancel",
 *     "collection" = "/admin/people",
 *   },
 *   field_ui_base_route = "entity.user.admin_form",
 *   common_reference_target = TRUE
 * )
 */

```

\_entity\_form: user.register pulls from here.

# Answer
> 1 votes
As users are entities in Drupal 8, best way to render user registration form is to render entity form of user.

So here is an answer:

```
$entity = \Drupal::entityTypeManager()->getStorage('user')->create(array());

$formObject = \Drupal::entityTypeManager()
  ->getFormObject('user', 'register')
  ->setEntity($entity);

$form = \Drupal::formBuilder()->getForm($formObject);

print  \Drupal::service('renderer')->render($form);

```

This way you can render `user.register` form anywhere.

---
Tags: forms, 8
---


# Question
Title: Access to referencing entity field from referenced entity template in Drupal 8
I'm building a custom block type with referenced nodes, on the "**view**" of the block type I configured to show the full node instead just links. And I want to access from the `node--type.html.twig` to some of the fields of the parent block (when the block is rendered). How we can do that?? is there any other good approach to doing this??

# Answer
> 0 votes
When you are inside the children node, you don't see what is around you. The children node is build and cached on its own. The entity reference is a n:m relationship. There can be more than one parent. So from the data modelling there is no easy solution. Better look for a solution from parent to children, not backwards.

# Answer
> 0 votes
You can do it with a bit of custom code but as 4k4 said, you need to take care of caching.

In preprocess of the block template, you have the rendered fields available and for the reference field , you can put something additional in it (\`$variables\['elements'\]\['content'\]\['yourfield'\]\[0\]\['#something'\] = $your\_stuff). That should then again be available preprocess/templates for the block template.

If you do that, you likely need to disable render caching, you can do so by removing the #cache keys in the same place. `unset($variables['elements']['content']['yourfield'][0]['#cache']['keys'])`.

Entirely untested.

---
Tags: theming, 8
---


# Question
Title: Render image programmatically based on field content
I am templating a resource page that has 5 different types of resources. I want to display a specific icon based on the type of resource. I want to do this programmatically so that later, users can upload a document, choose what type of resource it is, and the icon will automatically be displayed.

Now I'd like to be able to complete the logic of this inside the node--resource-asset.html.twig template using a for or if statement.

This is the kint display for the field\_resource\_type array. I want to generate the icon based on the markup string. This is what I've tried

```
{% for markup in content.field_resource_type %}
{% if markup == 'Datasheet' %}
<img class="icon" src="/img/icon_datasheet.png">
{% elseif markup == 'Whitesheet' %}
<img class="icon" src="/img/icon_whitepaper.png">
{% else %}
<img class="icon" src="/img/icon_casestudy.png">
{% endif %}
{% endfor %}

```

Nothing renders. Any suggestions on what I should be using as the key to call the correct part of the field?

# Answer
> 1 votes
You have two primary things avaiable in a node template.

`content`: That contains rendered markup. Use it to print stuff.

`node`: This contains the node object with the raw values. Use this for comparisons and accessing the unformatted values. The same raw values would also be accessible through #items in content, but it's much more complicated to access.

So in your case, access the value with `node.field_resource_type.value`.

Note that this contains the key of the list field, and not the displayed label. I would recommend to always specify explicit keys (e.g., put datasheet|Datasheet in the allowed values field). Then you can also reliably translate those labels if you have a multilingual site and your template doesn't break.

Unless you actually have multiple values in there, you also don't need a loop. But if you do, you can loop over it with `for item in node.field_resource_type` and then use `item.value`.

See also http://wizzlern.nl/drupal/drupal-8-entity-cheat-sheet

---
Tags: theming, entities, 8
---


title: Can't use core/jquery

text:
# Question
Title: Can't use core/jquery
I created my libraries.yml as shown in Drupal 8 CSS/JS.

### .libraries.yml

```
 general:
  version: 1.x
  css:
    theme:
      css/materialize-custom.css: {}
      css/main.css: {}
  js:
    js/materialize.min.js: {}
    js/main.js: {}
  dependencies:
    - core/jquery

```

My problem is that my main.js need jQuery to work.

### main.js

```
$( document ).ready(function() {
  // Initialize collapse button
    $(".button-collapse").sideNav();
});

```

I get this error.

>

I don't understand why I have this error. What is wrong with my code?

# Answer
> 5 votes
Drupal doesn't provide you with an alias for jQuery, because these days it'll inevitably interfere with another library sometime later.

If you want `$` as an alias, you'll need to create it yourself:

```
(function($) {
  // your code...
})(jQuery);

```

---
Tags: theming, 8
---


# Question
Title: Creating specific taxonomy terms the Drush way
is there a way to create specific taxonomy terms the drush way?

the docs mention only a number argument to generate dummy terms.

http://www.drushcommands.com/drush-7x/devel-generate/generate-terms

i have around 150 terms (city - country (parent) - region (parent)) in one location taxonomy vocabulary. would be great if i can write the syntax in a text editor and use this to populate the vocabulary.

thx for any suggestions!

# Answer
Try the taxonomy manager module.

https://www.drupal.org/project/taxonomy\_manager

It allows for mass insertion of terms.

There's also a taxonomy csv module which allows for import/export of taxonomies to file. That might be worth a try too: https://www.drupal.org/project/taxonomy\_csv

Else you can try and write your own module... But that's a rather tougher route.
> 2 votes

# Answer
For one-offs, a mass insertion module may not be suitable.

Upset that there was no existing simple way to add content in Drush, I created the drush create-content command set, which allows for the one-off creation of vocabularies, nodes and terms.

https://github.com/djcf/drush-create
> 0 votes

---
Tags: taxonomy-terms, drush
---


title: Delete entities in batches

text:
# Question
Title: Delete entities in batches
Is there a way to organized entity deletion by braking into different batches? I have 700.000 entities associated with pictures that I would like to delete and I would like to perform that into batches. Any how to?

# Answer
You can install Views Bulk Operations, create a View of those entities, and set up a delete operation. It should have configuration options to execute in batches. I have done this before to delete 100,000 records.

https://www.drupal.org/project/views\_bulk\_operations
> 2 votes

---
Tags: database, entities, batch-operations
---


# Question
Title: Configure inline images upload path per content type
There is a core feature that lets you configure where to save inline images uploaded using `CKEditor`:

Here you can specify the path where you want store inline images.

But this is global configuration, which works for all content types.

I want to have ability to control directory path per content type.

There is a module called File (Field) Paths which gives you ability to configure paths for only file fields under any content type but not for inline images.

Is there any module or a way to implement this?

# Answer
Not directly. The only approach that I could think of right now is that you create a text format for each node type and then use a module like Allowed Formats or Better Formats to limit the allowed formats of each node type to that.

Maybe you can also alter the settings at runtime with some custom code based on the page that you're on right now, but I'm not sure.
> 0 votes

---
Tags: 8, media, uri, wysiwyg
---


title: Warning of the permission in Aegir

text:
# Question
Title: Warning of the permission in Aegir
I'm trying to add a site with Aigir and i'm getting this warning:

## Warning in features rebuild of permessi. No module defines permission "create article content".

## Warning in features rebuild of permessi. No module defines permission "create slides content".

## Warning in features rebuild of permessi. No module defines permission "delete any article content".

## Warning in features rebuild of permessi. No module defines permission "delete any slides content".

## Warning in features rebuild of permessi. No module defines permission "delete own article content".

## Warning in features rebuild of permessi. No module defines permission "delete own slides content".

## Warning in features rebuild of permessi. No module defines permission "delete terms in tags".

## Warning in features rebuild of permessi. No module defines permission "edit any article content".

## Warning in features rebuild of permessi. No module defines permission "edit any slides content".

## Warning in features rebuild of permessi. No module defines permission "edit own article content".

## Warning in features rebuild of permessi. No module defines permission "edit own slides content".

## Warning in features rebuild of permessi. No module defines permission "edit terms in tags".

all permissions are exported with features & features\_roles\_permissions. the problem is on the new created site this permissions are not set for any of the roles set in the module. any idea? thanks

# Answer
> 1 votes
It looks like the issue is that the permissions are created before there are defined (since you need to have the content types created before the permissions are created).

This could be fixed with proper dependencies (since the feature with the permissions depends on the feature(s) with the content types.

---
Tags: users, features, aegir
---


title: Add a class to images in drupal

text:
# Question
Title: Add a class to images in drupal
I have more than thousand images on my site. adding a class to each image manually is very time consuming process is there any way to add the class "adaptive-image" to all images already uploaded automatically.

# Answer
> 1 votes
Few ways to do this:

1. JavaScript. Not the best one, but fastest:

```
$('img').addClass('adaptive-image');

```
2. For styling field images, see the response by Manoj Bisht.
3. For styling images added through WYSIWYG you will have to write a custom text filter and add classes. Depending on the WYSIWYG editor you use, you might be able to create a plugin / set configuration so that all images inserted automatically get certain CSS class.
4. Ultimately, you can just adjust the CSS of `.adaptive-image`, or clone the styles and apply them for all `img` tags.
Example source:

```
.adaptive-image {
  /* Whatever. */
}

```

Change to, or add this:

```
img {
  /* Copy styles from .adaptive-image. */
}

```

# Answer
> 0 votes
You can write function `theme_preprocess_image`, like the one give below

```
theme_preprocess_image(&$variables) {
  $variables['class']['adaptive-image'][] = "true";
}

```

It will apply adaptive-image class to all images irrespective of style.

---
Tags: theming, media
---


title: Exporting Blocks from Drupal 6 to 7

text:
# Question
Title: Exporting Blocks from Drupal 6 to 7
Can anyone tell me the best way to export blocks from Drupal 6 to 7?

Boxes? Features? A Straight field for filed export?

# Answer
> 0 votes
Assuming they are straight up Blocks with body content (not View blocks or other contrib generated blocks), I would create a module that scripts and creates them on install. If you have many blocks, do them in small batches (breaking them up across update\_n hooks).

That way you can also test them in small batches and get it right. Once up, you can disable the module and remove it.

See:

---
Tags: 6, blocks, importing-exporting
---


title: xautoload not loading class

text:
# Question
Title: xautoload not loading class
I have a PHP class that I have developed to mediate the interactions with a client's SSO web service. The class needs to be used by both a Symfony site and a Drupal 7 site. On the Drupal side, I've dropped a copy of the class inside the SSO module I'm developing, and I'm attempting to use xautoload to load it, but I was getting a class not found error when attempting to instantiate an object from it.

Now I'm just dumping the output of get\_declared\_classes() to the message area with dpm(), and I don't see that it has loaded the class.

Here's the structure of my module

```
client_sso/
|
--client_sso.info
--client_sso.module
--includes
  |
  --ClientSSO.php

```

My client\_sso.info looks like this

```
name = Client SSO
description = Integrate Drupal with Client SSO service
package = AARP
core = 7.x
dependencies[] = xautoload (>= 7.x-5.0)
files[] = includes/*.php

```

I disabled and re-enabled the module to rebuild the module registry and cleared all caches, but it appears to be cheerfully ignoring the file with the class.

I have verified that I can directly load the class with

```
module_load_include('php', 'client_sso', 'includes/ClientSSO');

```

What should I try next?

# Answer
Several things to consider.

`*.php` only looks in the folder itself. `**/*.php` also looks in subdirectories recursively. This seems ok in this case, but I want to mention it for other visitors.

---

The `files[] = ..` always requires clearing the cache.
If you have problems with this, `drush rr` (Registry Rebuild) is useful.

---

The core class registry with `files[] = ..` does *not* work for classes in namespaces.
xautoload does not change this.

The Registry Autoload module makes namespaced classes work with the core registry. But I don't know how well it works with the `*.php`-style wildcards.

Or, you can use hook\_xautoload() to register additional namespace directories.
> 1 votes

---
Tags: 7
---


title: My battle with drupal's form

text:
# Question
Title: My battle with drupal's form
In the ancient times when things were easy, you just had to code a form in html and then your php would typically have a if($\_REQUEST\['some\_value'\]) to handle the request. But now with Drupal, nothing is easy... Here is once more my latest battle to understand how Drupal thinks.

Context: I have a list of news (content type "news") shown on a page with paging system. Each news title links to the news details page. This works fine. There is a new requirement that each news must have one or more "tags". The goal is to show a list of checkboxes on top of the news list to allow the user to filter in/out news with the selected tags.

EDIT: After being defeated by Drupal's form I decided to completely bypass the Form API and generate my own fully flexible form.

There is only one thing remaining, Drupal is forcing some div wrappers around each of my input fields. I want to get rid of them (and stop Drupal to think at my place).

In my\_news\_list.tpl.php I coded:

```
<form action="" method="post"> <!-- recall same page on submit -->
<?php
foreach($tags as $tag){
    ?><input type="checkbox" name="tags[]"
        value="<?php echo $tag['id'] ?>"
        onchange="form.submit();"
        <?php if(isset($tag['checked'])){?>checked="checked"<?php }?>
      /><?php echo $tag['value'] ?><?php
}
?>
</form>

```

Result(!):

```
<form action="" method="post">
    <div class=" ui-checkbox"> <!-- Why those div wrappers?! -->
        <input type="checkbox" name="tags[]" value="15" onchange="form.submit();">
    </div>
    Acquisitions
    <div class=" ui-checkbox">
        <input type="checkbox" name="tags[]" value="14" onchange="form.submit();">
    </div>
    Corporate
    <div class=" ui-checkbox">
        <input type="checkbox" name="tags[]" value="18" onchange="form.submit();">
    </div>
    Investor News
    <div class=" ui-checkbox">
        <input type="checkbox" name="tags[]" value="16" onchange="form.submit();">
    </div>
    Products and Services
</form>

```

# Answer
Drupal's Form API is complex but gives you lot of things: is secure, is extensible, is themeable. Indeed is more difficult than coding a simple HTML form, but with a simpel HTML form you have a simple functionality: just that simple HTML form.

Form API generates the form HTML element and handles the POST requests, and validate and submithandlers, you don't and you shouldn't code your own HTML form.

I recommend you to read the Drupal 6 Form API Quickstart Guide. Drupal 7 form handling is pretty the same, but check the Drupal 7 Form API Reference and Form API Internal Workflow Illustration.

In the other hand you may prefer to use a module that address what you need without coding, that's a faceted search: Facet API. From its documentation page:

> Faceted search allows our search results to be filtered by defined criteria like category, date, author, location, or anything else that can come out of a field. We call these criteria facets. With facets, you can narrow down your search more and more until you get to the desired results.
> 1 votes

# Answer
The issue here is theme\_wrappers around your form elements.

// @see: https://drupal.stackexchange.com/a/193587/58635
> 0 votes

---
Tags: 7, forms, theming
---


title: Organic Groups Mass Subscribe

text:
# Question
Title: Organic Groups Mass Subscribe
I'm using organic groups 7.x-2.x, as well as admin\_views for administering users. I have a field that I'm able to sort users on depending on what department they are in using Views Bulk Operations at admin/people.

My question involves subscribing people in bulk to a specific organic group. Is there a way to achieve this using Views Bulk Operations?

# Answer
Users can now be added in bulk to organic groups using Views Bulk Operations out of box. The simplest way to do this is to take the following steps:

1. Download Admin Views
2. Edit the people listing page view at /admin/structure/views/view/admin\_views\_user/edit
3. In the view under fields, select "Bulk operations: User" Under "Modify entity values", be sure that either "All" or at least "Group Membership" is selected
4. Save the view if needed
5. Go to /admin/people and filter the users as desired Select "Change value" and click *Execute*
6. Under "Fields", select "Group membership", and select the group(s) you wish to assign the users to.
7. **Be sure the "Add new value(s) to Group membership, instead of overwriting the existing values" checkbox is checked or your users will lose their existing membership settings.**
8. Click *Next* to complete the operation.
> 1 votes

# Answer
There is a module called Organic Groups Mass Add that uses VBO to add people en mass. http://drupal.org/project/og\_massadd

The unfortunate part of this answer is that the module doesn't seem to be working with OG 2.x. I installed it yesterday and had issues (reported in the issue queue).

I'm not quite at the point where this feature must be implemented, but will be in a couple weeks. So, I'll be looking at the module closer to see if there are any bug fixes I can do to make it work.
> 0 votes

# Answer
I made an action for this that works. It can be used with Views Bulk Operations and also works for users that don't have the "administer organic groups" permission so they can add in bulk members to the groups where they are administrator of.

In a first screen of VBO you can select the users, in the second screen you get checkbox list of the groups where you are administrator of.

Unfortunately VBO forces users to have the "administer users" permission set for the acting user to be able to do actions on the $user which is needed here. So the patch https://www.drupal.org/files/issues/views\_bulk\_operations-execute\_as\_user\_one-1334088-41.patch of https://www.drupal.org/node/1334088 and then setting the checkbox "Skip permission step" is needed.

```
    /**
     * Get the groups where a certain user is administrator of
     *
     * @param $uid
     * @return mixed: array with gid and groupname to be used as options in the checkboxes
     */
    function MYMODULE_get_group_ids_current_user_is_admin_of($uid) {
      $query = db_select('og_users_roles', 'og');
      $query->condition('rid', '3', '=');
      $query->condition('uid', $uid, '=');
      $query->fields('og', array('gid'));
      $result = $query->execute();
      while ($record = $result->fetchAssoc()) {
        $gid = $record['gid'];
        // $groupname = node_load($gid)->title; // looks cleaner but is slower in this case
        $groupname = db_query("SELECT title from {node} where nid = :nid", array(':nid' => $gid))->fetchField();
        $groups[$gid] = $groupname;
      }
      return $groups;
    }

    /**
     * Implements hook_action_info()
     */
    function MYMODULE_action_info() {
      return array(
        'MYMODULE_add_user_to_ogs_action' => array(
          'type' => 'user',
          'label' => t('Add users to Organic groups'),
          'configurable' => TRUE,
          'behavior' => array('changes_property'),
          'triggers' => array('node_presave', 'node_insert', 'node_update'),
        ),
      );
    }

    /**
     * Generates settings form for action_example_node_sticky_action().
     */
    function MYMODULE_add_user_to_ogs_action_form($context) {
      // Get the current uid
      global $user;
      $uid = $user->uid;

      $groups = MYMODULE_get_group_ids_current_user_is_admin_of($uid);

      $form['add_to_groups'] = array(
        '#type' => 'checkboxes',
        '#title' => t('Add to groups where I am administrator of'),
        '#description' => t('Select the groups where you want to add these users to'),
        '#options' => $groups,
      );

      return $form;
    }

    /**
     * Submit handler for MYMODULE_add_user_to_ogs_action
     */
    function MYMODULE_add_user_to_ogs_action_submit($form, $form_state) {
      return array('gids' => $form_state['values']['add_to_groups']);
    }

    /**
     * Action function for MYMODULE_add_user_to_ogs_action.
     *
     * Add the user to the selected organic groups
     *
     */
    function MYMODULE_add_user_to_ogs_action($user, $context) {
        // The account is the user where we do the action on
  $account = $user;
  $uid = $account->uid;

  $newref = array();

  // Get an array of all gids
  if (isset($context['gids'])) {
    $group_ids = $context['gids'];
  }

  $group_type = 'node';
  $field_name = 'og_user_node';

  foreach ($group_ids as $gid) {
    // make sure its an integer
    $gid = (int) $gid;

    // Groups that are not selected in the checkboxes have gid 0
    if (isset($gid) && ($gid!=0)) {
      // Set the og membership
      $group_type = 'node';
      $values = array(
        'entity_type' => 'user',
        'entity' => $account->uid,
        'field_name' => FALSE,
        'state' => 1,
      );
      $og_membership = og_group($group_type, $gid, $values);

      // Build an array with the new gids in the format that is needed for the entity reference field
      $newref[] = array(
        'target_id' => $gid,
      );

      $group = entity_load_single('node', $gid);
      watchdog('ogbulk_add_user',
        t('The user %username has been added to the group %group-title (%gid).'),
        array(
          '%gid' => $gid,
          '%username' => $account->name,
          '%group-title' => $group->title,
        )
      );
    }
  }

  // Why is saving $og_membership not enough to store the gid's?
  // Remove this part when $og_membership would save the gids as expected
  // For now as a fix we need to get all gids and save them in the user
  $existing_gids = og_get_groups_by_user($account);

  // Build an array with the existing gids in the format that is needed for the entity reference field
  $ref = array();
  foreach ($existing_gids['node'] as $existing_gid) {
    $ref[] = array(
      'target_id' => $existing_gid,
    );
  }

  // Merge the existing gids with the extra gids
  $ref = array_merge($ref, $newref);
  $data['og_user_node'][LANGUAGE_NONE] = $ref;
  user_save($account, $data);

  return;
}

```
> 0 votes

# Answer
You can also use the https://www.drupal.org/project/og\_bulkadd module which has a different approach: A 'Bulk adding users' tab is added to the 'Add members' tab on the group managment section.
> 0 votes

---
Tags: organic-groups, views
---