# Question
Title: Why can't I uninstall a module if I deleted a field type in a content type?
I have an installation of Drupal 7. I installed Field Collection module. I created a content type (Books), added a collection type field, and created a View showing these data. Now, I deleted the collection type field in Books, and now I am not able to uninstall the module. I have run cron and cache delete to no avail. The message displayed in the modules page is the following.

Field collection

> 7.x-1.0-beta11+13-dev
> Provides a field collection field, to which any number of fields can be attached.
> Requires: Entity API (enabled)
> Required by: Drupal (**Fields pending deletion**)

# Answer
From http://www.drupalwoo.com/content/blog/cant-disable-module-drupal-fields-pending-deletion :

> All of us who have been working with Drupal for a while have run into this issue: you want to disable a module that you are no longer using, but it's grayed-out on the 'Modules' tab, and so you aren't able to disable and uninstall it.
>
> It says Required by: Drupal (Fields pending deletion)
>
> Required by: Drupal (Fields pending deletion)
>
> Well, you know what this means, so you go to the fields list screen at /admin/reports/fields
>
> You delete all the fields that were related to this module, you run cron multiple times (that's what all the replies to this problem say), and still, you cannot disable the module.
>
> If this is happening to you, as it happened to me recently with the Geofield module, here's the quick fix:
>
> Go into the field\_config table in your Drupal database, and look for the field in question. It should say that the field in question has been deleted already:

Try running this query in your database.

```
    DELETE FROM `field_config` WHERE `field_config`.`deleted` = 1;

```

Then, clear the cache.
> 0 votes

# Answer
You can try this process

Log into database and -\>

```
Select * from field_config where type = "field_collection"

```

Delete the rows

Same with field config instance table like

```
SELECT * FROM field_config_instance where entity_type = "field_collection";

```

Delete the rows

You can also check.

> 1.) first remove all the fields inside the Fields Collection.
>
> 2.) Then remove the field collection from the content type
>
> 3.) Run the Cron
>
> 4.) try to disable the module, if you cannot then Go ahead with first query statements above.

Get more details Here.
> 2 votes

---
Tags: entities, installation
---


# Question
Title: How to export menu per role permission in features module?
I added `custom permission` in my menu using menu\_per\_role module. I want to export the permission configuration that I made in my menu. using features module my question is how can I export my menu permission configuration. is `features` module support exporting configuration came from `menu_per_role module`? I also tried to check it in strongarm but I can't see it.

# Answer
> 1 votes
I ended up using this module roles\_for\_menu this module exactly what I need, it allows me to export the configuration in features.

Features module support it.

---
Tags: users, features
---


title: Multisite files folders

text:
# Question
Title: Multisite files folders
In a first try to setup a multi-site configuration, I run into the following problem : anything done with a site (pictures, styles...) is added to `sites/default/files/` directory, and an image added to a content points to `sites/default/files/styles/some_style/.../image.jpg`.

**Is it the expected behaviour ?** I thought any file would stay in sites/site1/files...

This is my sites/sites.php :

```
$sites = array(
  '8083.arbre.dd' => 'arbre.dd', //local devdesktop site
  '8083.site2.dd' => 'site2.dd', //future one
);

```

I have folders `sites/all, sites/default, sites/arbre.dd, sites/site2.dd`. I added a files directory and a `settings.php` file to the future site folder. I notice that the arbre.dd folder added by Devdesktop at initial setting, has a shortcut icon ???

# Answer
Verify your configuration at `admin/config/media/file-system` on the multisites. "Public file system path" may be configured to `sites/default/files`.
> 2 votes

# Answer
In addition, to @Cilefen answer, I'll share here my modest experience : in order to get a **multi-site configuration** :

* I added a first site with the desired profile, which I won't touch nor publish. Just **default profile**, always up to date after performing security updates of the multi-site configuration
* I added then another site with the same sql dump, which is the first real *client* site
* Whenever I wish to add a new site, I'll just have to *dump default profile DB* as a start point, in a new sites folder, and setup "Public file system path" as `sites/newSite/files`

Files, themes or whatever specific to each site is now correctly saved in its directory.

Please comment that answer if I could do a better way
> 1 votes

---
Tags: 7, multi-sites
---


# Question
Title: Why I'm not able to debug twig templates? sites/default/files/php directory is empty
As in question. I'm following this tutorial: https://dev.acquia.com/blog/debugging-drupal-8/debugging-twig-templates-in-drupal-8-with-phpstorm-and-xdebug/25/08/2016/16586

but directory

> sites/default/files/php/twig

is always empty

I'v tried cr all, checked file system page, did drush cron, checked theme page - no errors.

I got some errors related to permissions at theme settings page, but:

> chmod 777 -R sites/default/files

seems to solved those.

Any advices?

# Answer
> 2 votes
Probably the directory `sites/default/files/php/twig` is empty because the container parameter `twig.config.cache` is set to false.

The approach used in the linked article is arguable.. put a breakpoint in every twig compiled template is not a viable solution. For debugging twig templates with xdebug there are better alternatives:

---
Tags: theming, 8, debugging
---


# Question
Title: How to get a fixed picture in the field without affect by responsive effect?
I want to get this picture fixed on original size. Please refer to this picture. There is a picture showing up a drill. I want to make it keep on 100x59px. When I adjust the browser's window, the responsive effect is that I want but the picture will shrink its width. Here is the webpage. I also use this command:`grep -inR image-style-cu-product-list /mydrupalcssdirectory`. I can't figure out why I did't get this specific CSS? Are there any methods to keep this picture fixed on 100x59px. (At least I want the width able to be fixed.) The solving method is not limit in CSS. Wish a help. Thanks.

# Answer
> 0 votes
Tables are by definition "responsive" (quotes intended), meaning they will give more space to the more "filled" cell. You need to tell the browser to reserve a certain amount of space for the cell with the following css:

```
.views-field-uc-product-image {
  min-width: 110px;
  max-width: 110px;
}

```

The extra 10 pixels are to account for the padding around the image. The `max-width: 110px` is added to ensure the cell will also not take more space then needed.

---
Tags: views, theming, entities, ubercart, media
---


# Question
Title: Adjust weight for menu items in different languages
My site will be in English and Arabic. English reads from left to right and Arabic from right to left. Drupal 8 works great with this if you enable all 4 multilingual extentions.

The only problem I have is that I translated the main menu, but I can't find how I can add a different weight to the separate menu items, this since I want the menu to be mirrored on Arabic.

If you go to the separate menu items you can add a weight but above it it is written: Weight (all languages)

How can I adjust the weight per language per item?

**UPDATE**: the answer by *Owais Alam* does not handle the adjustment of menu-items-weight per language in Drupal 8

# Answer
With Drupal 7 core alone, user-defined menu items are not translatable. The Menu translation module, part of the Internationalization (i18n) package, allows users to select a translation mode for each menu (Figure 1).

The following modes are available:

1. No Multilingual Options
2. Translate and Localize
3. Fixed Language

**Translate and Localize Menus**

For most use cases, and especially if the structure of your menus is consistent across languages, Translate and Localize is the preferred method of translating menus. You can create one menu for all languages, and translate or localize each menu item. There are two ways that menu items will be translated:

* You can set a language when creating a custom menu item so that the menu item will only show up for that language (Figure 1). Menu items that link to nodes in a particular language will be treated this way.
* You can localize other custom menu items without a language (for example, menu items linking to Views pages). Use the Translate tab to translate the menu item title and description (Figure 2). Translators can also use the 'Translate interface' pages to translate these menu items (Figure 3).

**Figure 2**

**Figure 3**

**Fixed Language Menus**

If you choose Fixed Language, you'll have to set up a separate menu in each language. This could become tedious if have a lot of languages enabled on your site, but is useful if the content or menu structure is different for each language.

**Menu Items Linked to Nodes**

Useful modules:

A menu item linked to a node will be displayed only when the node language matches the page language. This is due to how the menu system works and the 'Language selection' feature in i18n. Therefore, to get translated menus items that link to nodes, you first need translated content: see Translating content to different languages.
> 2 votes

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


# Question
Title: Commerce License not de-activating when expired
I'm using commerce license on one of my website. And I found out that some of the licenses that are expired didn't get de-activated.

As you can see, in the image below. License 113, 114, 115 should be inactive. But they are still Active (Actief). In the last column you will see that the expiring dates are past today (08/22/2016).

Using the modules Ultimate Cron and View Queue I'm able to see that the Commerce License module is adding the queue.

I also look in my logs but no errors are found. Does anybody know what the problem can be or what my next step in searching for the problem can be?

Thanks in advance, Zeb

# Answer
> 0 votes
For some reason the basic Drupal cron didn't call the license sync. Using Ultimate Cron I was able to make this work.

---
Tags: commerce
---


# Question
Title: How to add and delete a user to another group using the Group module?
I am using Drupal 7 and the Group module. I would like to create reaction rule or some code which automatically signs the user up to group 'blue', when they sign up to group 'red'.

I wouldn't mind using Rules or hard coding it. The only thing is that if the user leaves the first group, I want to be able to cancel their membership in the second group too.

What would be the easiest way? I have of course tried Rules without success and I cannot find a simple way to hard code it.

# Answer
> 2 votes
Found the solution. When using the group module, there are methods which work well. I used a hook\_group\_membership\_insert($group\_membership):

```
function [my_module]_group_membership_insert($group_membership) {

   $grouptest = group_load($group_membership->gid);
   $grouptest->addMember($group_membership->uid);
}

```

The same exists for deleting a member, just use the following function:

```
$grouptest->removeMember($uid);

```

# Answer
> 1 votes
# Add user to another group

To answer 1 of your questions (= "*How to add a user to another group?*"): it is indeed possible to use the Rules module (the Group module has all sorts of out-of-the-box integrations with Rules).

To do so, you can use a variation of what's explained in comment # 5 of the issue about "Bulk adding users to a group". Here is a rule (in Rules export format) that should do the job:

```
{ "rules_create_additional_group_membership" : {
    "LABEL" : "Create additional group membership",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "group" ],
    "REQUIRES" : [ "rules", "group" ],
    "ON" : { "group_membership_insert" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "group-membership:group:gid" ], "value" : "1" } }
    ],
    "DO" : [
      { "entity_create" : {
          "USING" : { "type" : "group_membership" },
          "PROVIDE" : { "entity_created" : { "created_group_mbrship" : "Created group mbrship" } }
        }
      },
      { "data_set" : { "data" : [ "created-group-mbrship:group" ], "value" : "2" } },
      { "data_set" : {
          "data" : [ "created-group-mbrship:user" ],
          "value" : [ "site:current-user" ]
        }
      },
      { "data_set" : { "data" : [ "created-group-mbrship:status" ], "value" : "active" } },
      { "entity_save" : { "data" : [ "created-group-mbrship" ], "immediate" : "1" } }
    ]
  }
}

```

Some more details about this rule:

* Rules Event: After saving a new group membership.
* Rules Conditions: Check that the group for the new membership is `1` (adapt this to fit your "1st group").
* Rules Actions:
    + Create a new entity (Entity type = Group membership).
    + Set a data value for `group` (= `2`, adapt this to fit your "2nd group").
    + Set a data value for `user` (= `[site:current-user]`).
    + Set a data value for `status` (= `Active`, assuming that's the status you want).
    + Save the entity (make sure to use `Force saving immediately`).

If you have the Rules UI (and the Group module) enabled, you should be able to just import the above rule in your own site (after you eventually edited the group IDs `1` and `2` to fit your own needs).

# Remove user from another group

Your 2nd question (= "*... if the user leaves the first group, I want to be able to cancel their membership in the second group too ...*") is really a different question. The major challenge to answer it is that when something happens to the 1st group, you want something to happen in the 2nd group.

Here is a (rather basic) Rules Component that you could use to change such membership to status "blocked":

```
{ "rules_remove_a_single_group_membership" : {
    "LABEL" : "Remove a single group membership",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "group_mbrship" : { "label" : "Group membership", "type" : "group_membership" },
      "user" : { "label" : "User", "type" : "user" }
    },
    "IF" : [
      { "data_is" : { "data" : [ "group-mbrship:group:gid" ], "value" : "2" } }
    ],
    "DO" : [
      { "data_set" : { "data" : [ "group-mbrship:status" ], "value" : "blocked" } }
    ]
  }
}

```

Note the Rules Condition that checks that the group for the membership to be blocked is `2` (adapt this to fit your "2nd group").

The only thing left is to have this Rules Component triggered via a Rules Action of another (extra) rule that is triggered when a user leaves the 1st Group. If you wonder how to do that, and to avoid my answer gets marked as *access only for +15K users*, please use this link.

---
Tags: 7, rules
---


# Question
Title: Does hook_install() get called before or after configuration yml files are loaded?
In Drupal 8, during module install, is `hook_install()` called before or after loading the .yml files in config/install?

I've across a module that's using both (which seems like a bad idea on its own) and I'm trying to run down the cause of an inconsistency in the configuration right after the module is installed.

# Answer
When Drupal install a module, first it installs the default configuration of the module, then it invokes its `hook_install()`. This is evident from `ModuleInstaller::install()`, which contains the following code.

```
  // Install default configuration of the module.
  $config_installer = \Drupal::service('config.installer');
  if ($sync_status) {
    $config_installer
    ->setSyncing(TRUE)
      ->setSourceStorage($source_storage);
  }
  \Drupal::service('config.installer')->installDefaultConfig('module', $module);

  // If the module has no current updates, but has some that were
  // previously removed, set the version to the value of
  // hook_update_last_removed().
  if ($last_removed = $this->moduleHandler->invoke($module, 'update_last_removed')) {
    $version = max($version, $last_removed);
  }
  drupal_set_installed_schema_version($module, $version);

  // Ensure that all post_update functions are registered already.
  /** @var \Drupal\Core\Update\UpdateRegistry $post_update_registry */
  $post_update_registry = \Drupal::service('update.post_update_registry');
  $post_update_registry->registerInvokedUpdates($post_update_registry->getModuleUpdateFunctions($module));

  // Record the fact that it was installed.
  $modules_installed[] = $module;

  // Drupal's stream wrappers needs to be re-registered in case a
  // module-provided stream wrapper is used later in the same request. In
  // particular, this happens when installing Drupal via Drush, as the
  // 'translations' stream wrapper is provided by Interface Translation
  // module and is later used to import translations.
  \Drupal::service('stream_wrapper_manager')->register();

  // Update the theme registry to include it.
  drupal_theme_rebuild();

  // Modules can alter theme info, so refresh theme data.
  // @todo ThemeHandler cannot be injected into ModuleHandler, since that
  //   causes a circular service dependency.
  // @see https://www.drupal.org/node/2208429
  \Drupal::service('theme_handler')->refreshInfo();

  // In order to make uninstalling transactional if anything uses routes.
  \Drupal::getContainer()->set('router.route_provider.old', \Drupal::service('router.route_provider'));
  \Drupal::getContainer()->set('router.route_provider', \Drupal::service('router.route_provider.lazy_builder'));

  // Allow the module to perform install tasks.
  $this->moduleHandler->invoke($module, 'install');

```

The first lines I quoted are for installing the default configuration, while the last one is for invoking `hook_install()`.
> 10 votes

---
Tags: 8, configuration, installation
---


# Question
Title: How to setup reCaptcha to appear on the registration form?
reCaptcha is ported to Drupal 8. I've set up captcha and recaptcha. I've read Readme.txt from recaptcha, I've registered my site and got the API key and paste it, also I've looked at Readme.md from captcha module.

But it does not appear in the user registration form.

All I can see is this

So please, what to do? Where should I set up captcha appears on regform?

# Answer
> 11 votes
In the `CAPTCHA Points` tab, you need to click on the enable button.

---
Tags: 8, captcha
---


# Question
Title: How to grant userpoints only for modifying nodes last changed at least 20 days ago?
I am not sure how to go about this. I use the Userpoints module in Drupal 7 to attribute points to users who create nodes ('reviews'). I also want to allow them to gain some points if they supersede or modify an existing node... but only if the previous creation/mod was done over 20 days before.

How can I do this with Rules? Or else, how should I code it manually?

# Answer
Sorry to say, but the previous answer has some challenges:

* Rules Event `After saving new content` is not the right event.
* I disagree with the "*You will need a custom module ...*", since there is an out-of-the-Rules-box Rules Condition you can use ... Read on for more details on that.

Here is a rule (in Rules Export format) that does what you're asking for:

```
{ "rules_grant_userpoints_after_updating_old_content" : {
    "LABEL" : "Grant userpoints after updating old content",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "userpoints_rules" ],
    "ON" : { "node_update" : [] },
    "IF" : [
      { "data_is" : {
          "data" : [ "node-unchanged:changed" ],
          "op" : "\u003C",
          "value" : "-20 days"
        }
      }
    ],
    "DO" : [
      { "userpoints_action_grant_points" : {
          "user" : [ "site:current-user" ],
          "points" : "123",
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Modify existing node (nid=[node:nid]) that was not updated in the last 20 days.",
          "operation" : "Grant points",
          "display" : "1",
          "moderate" : "default"
        }
      },
      { "userpoints_rules_get_current_points" : {
          "USING" : { "user" : [ "site:current-user" ], "tid" : "all" },
          "PROVIDE" : { "loaded_points" : { "total_points" : "Number of points in all categories together" } }
        }
      },
      { "drupal_message" : { "message" : "You now have [total-points:value] points" } }
    ]
  }
}

```

Some more details about the above rule:

* Rules Event: After updating existing content (you may want to limit it to selected content types only).
* Rules Condition: Token `[node-unchanged:changed]` is at least from 20 days ago.
* Rules Actions:
    + Grant `123` user points (adapt the number and the other options as you want).
    + Load the current userpoints balance.
    + Display a message with the current userpoints balance.

If you have the Rules UI enabled (and the Userpoints Rules module, you should be able to just import the above rule in your own site.

PS: After you're convinced the rule works as you want, you may want to remove the last 2 Rules Actions about the message shown to the user after user points were granted.
> 1 votes

# Answer
# Giving points for adding new Review nodes:

1. Create new Rule; event: `After saving new content` \+ restrict by type: `Review`.
2. Action: `Grant points to a user`.

Note: you need to have `Userpoints rules integration` installed.

---

# Giving points for updating Review nodes after certain period of time

You will need a custom module where you will create a new rule Condition using `hook_rules_condition_info()`.
This condition will check if previous node revision is older than XX days (in your case 20 days).

Here's an example:

```
function YOUR_MODULE_rules_condition_info() {
  return array(
    'YOUR_MODULE_condition_compare_revision' => array(
      'label' => t('Compare date of last revision'),
      'parameter' => array(
        'node' => array(
          'label' => t('Node'),
          'type' => 'node',
        ),
      ),
    ),
  );
}

function YOUR_MODULE_condition_compare_revision($node) {
  $revision = db_select('node_revision', 'r')
    ->fields('r', array('nid'))
    ->condition('nid', $node->nid)
    // Make sure this is not the last revision.
    ->condition('vid', $node->vid, '!=')
    // Make sure this revision is older than your desired period of time.
    ->condition('timestamp', REQUEST_TIME - 20 * 24 * 60 * 60, '<=')
    ->execute()
    ->fetchObject();

  return $revision;
}

```

This could would go to `YOUR_MODULE.rules.inc`.

*Note*: I wrote this quickly and without testing. Should be working fine though.
> 0 votes

---
Tags: 7, nodes, rules, userpoints
---


# Question
Title: apache solr error: HTTP 500; /usr/local/solr/example/solr/data/index/segments_15qc (Permission denied)
I just noticed that my website apache solr doesn't work any more, but I didn't touch my website for a while. When I tried to delete my solr index, I got this error message:

> HTTP 500; /usr/local/solr/example/solr/data/index/segments\_15qc (Permission denied) java.io.FileNotFoundException: /usr/local/solr/example/solr/data/index/segments\_15qc (Permission denied) at java.io.RandomAccessFile.open(Native Method) at java.io.RandomAccessFile.(RandomAccessFile.java:241) at org.apache.lucene.store.FSDirectory$FSIndexOutput.(FSDirectory.java:441) at org.apache.lucene.store.FSDirectory.createOutput(FSDirectory.java:306) at org.apache.lucene.index.SegmentInfos.write(SegmentInfos.java:388) at org.apache.lucene.index.SegmentInfos.prepareCommit(SegmentInfos.java:827) at org.apache.lucene.index.IndexWriter.startCommit(IndexWriter.java:4570) at org.apache.lucene.index.IndexWriter.prepareCommit(IndexWriter.java:3414) at org.apache.lucene.index.IndexWriter.commitInternal(IndexWriter.java:3485) at org.apache.lucene.index.IndexWriter.closeInternal(IndexWriter.java:1873) at org.apache.lucene.index.IndexWriter.close(IndexWriter.java:1812) at org.apache.lucene.index.IndexWriter.close(IndexWriter.java:1776) at org.apache.solr.update.SolrIndexWriter.close(SolrIndexWriter.java:144) at org.apache.solr.update.DirectUpdateHandler2.closeWriter(DirectUpdateHandler2.java:179) at org.apache.solr.update.DirectUpdateHandler2.commit(DirectUpdateHandler2.java:411) at org.apache.solr.update.processor.RunUpdateProcessor.processCommit(RunUpdateProcessorFactory.java:85) at org.apache.solr.update.processor.LogUpdateProcessor.processCommit(LogUpdateProcessorFactory.java:154) at org.apache.solr.handler.XMLLoader.processUpdate(XMLLoader.java:190) at org.apache.solr.handler.XMLLoader.load(XMLLoader.java:79) at org.apache.solr.handler.ContentStreamHandlerBase.handleRequestBody(ContentStreamHandlerBase.java:58) at org.apache.solr.handler.RequestHandlerBase.handleRequest(RequestHandlerBase.java:129) at org.apache.solr.core.SolrCore.execute(SolrCore.java:1376) at org.apache.solr.servlet.SolrDispatchFilter.execute(SolrDispatchFilter.java:365) at org.apache.solr.servlet.SolrDispatchFilter.doFilter(SolrDispatc: /usr/local/solr/example/solr/data/index/segments\_15qc (Permission denied) java.io.FileNotFoundException: /usr/local/solr/example/solr/data/index/segments\_15qc (Permission denied) at java.io.RandomAccessFile.open(Native Method) at java.io.RandomAccessFile.\<init\>(RandomAccessFile.java:241) at org.apache.lucene.store.FSDirectory$FSIndexOutput.\<init\>(FSDirectory.java:441) at org.apache.lucene.store.FSDirectory.createOutput(FSDirectory.java:306) at org.apache.lucene.index.SegmentInfos.write(SegmentInfos.java:388) at org.apache.lucene.index.SegmentInfos.prepareCommit(SegmentInfos.java:827) at org.apache.lucene.index.IndexWriter.startCommit(IndexWriter.java:4570) at org.apache.lucene.index.IndexWriter.prepareCommit(IndexWriter.java:3414) at org.apache.lucene.index.IndexWriter.commitInternal(IndexWriter.java:3485) at org.apache.lucene.index.IndexWriter.closeInternal(IndexWriter.java:1873) at org.apache.lucene.index.IndexWriter.close(IndexWriter.java:1812) at org.apache.lucene.index.IndexWriter.close(IndexWriter.java:1776) at org.apache.solr.update.SolrIndexWriter.close(SolrIndexWriter.java:144) at org.apache.solr.update.DirectUpdateHandler2.closeWriter(DirectUpdateHandler2.java:179) at org.apache.solr.update.DirectUpdateHandler2.commit(DirectUpdateHandler2.java:411) at org.apache.solr.update.processor.RunUpdateProcessor.processCommit(RunUpdateProcessorFactory.java:85) at org.apache.solr.update.processor.LogUpdateProcessor.processCommit(LogUpdateProcessorFactory.java:154) at org.apache.solr.handler.XMLLoader.processUpdate(XMLLoader.java:190) at org.apache.solr.handler.XMLLoader.load(XMLLoader.java:79) at org.apache.solr.handler.ContentStreamHandlerBase.handleRequestBody(ContentStreamHandlerBase.java:58) at org.apache.solr.handler.RequestHandlerBase.handleRequest(RequestHandlerBase.java:129) at org.apache.solr.core.SolrCore.execute(SolrCore.java:1376) at org.apache.solr.servlet.SolrDispatchFilter.execute(SolrDispatchFilter.java:365) at org.apache.solr.servlet.SolrDispatchFilter.doFilter(SolrDispatc

But I didn't find "/usr/local/solr/example/solr/data/index/segments\_15qc" file in the index folder.

Does anyone have any idea? If my setup was wrong, could anyone give some idea that how to set apache solr on drupal 7. I really appreciate it.

# Answer
> 0 votes
Thanks, guys. I found the answer out. I changed the permission for the folder which includes solr-config setting files from 755 to 777. Everything works fine now.

Reference: Solr Exception

---
Tags: 7, debugging, search
---


# Question
Title: HTML / Mail System / SMTP Not sending approval in html
I have a current Drupal site that sends out all emails using the HTML template. Users requests, reset password, webform but does not send out approvals in HTML. Anyone have this issue or know a solution?

# Answer
I believe drupal will only send text emails by default. You will need a module to help you implement HTML emails. I have used Mime Mail in the past to do this.

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

From drupal.org:

> This is a Mime Mail component module (for use by other modules).
>
> * It permits users to receive HTML email and can be used by other modules. The mail functionality accepts an HTML message body, mime-endcodes it and sends it.
> * If the HTML has embedded graphics, these graphics are MIME-encoded and included as a message attachment.
> * Adopts your site's style by automatically including your theme's stylesheet files in a themeable HTML message format
> * If the recipient's preference is available and they prefer plaintext, the HTML will be converted to plain text and sent as-is. Otherwise, the email will be sent in themeable HTML with a plaintext alternative.
> * Allows you to theme messages with a specific mailkey. Converts CSS styles into inline style attributes.
> * Provides simple system actions and Rules actions to send HTML email with embedded images and attachments.
> 0 votes

---
Tags: emails
---


# Question
Title: How to move the login form to the header?
I need help in moving over the User login form to the header of the same page in Drupal 7. I am new to Drupal and I am not very familiar with the Drupal hooks yet. How should I achieve this?

This is what I have tried so far.

### template.php

```
function bklyn_theme() {
  $items = array();
  // create custom user-login.tpl.php
  $items['user_login'] = array(
  'render element' => 'form',
  'path' => drupal_get_path('theme', 'bklyn') . '/templates',
  'template' => 'user-login',
  'preprocess functions' => array(
  'bklyn_preprocess_user_login'
  ),
 );

 $items['user_pass'] = array(
 'render element' => 'form',
 'path' => drupal_get_path('theme', 'bklyn') . '/templates',
 'template' => 'user-pass',
 'preprocess functions' => array(
 'bklyn_preprocess_user_pass'
 ),
 );

return $items;
}

function bklyn_preprocess_user_login(&$vars) {
  $vars['intro_text'] = t('Username');
}

function bklyn_preprocess_user_pass(&$vars) {
  $vars['intro_text'] = t('Password');
}

```

I am not sure how I can integrate the login to show up in the header.

## Before

## After

# Answer
> 1 votes
> from the **website/user**. I need the logon to place on the header content area and be able to style it.

All you have to do is edit your theme's **page.tpl.php**

Since the form gets displayed as the page content:

in the header section of your template file add:

```
<?php if (current_path() == 'user'): ?>
     <?php print render($page['content']);?>
<?php endif; ?>

```

Then find the original `<?php print render($page['content']); ?>` and add:

```
  <?php if (current_path() != 'user'): ?>
     <?php print render($page['content']);?>
  <?php endif; ?>

```

OR... do the `if (current_path() != 'user') {` for everything inside the `#main-wrapper`

OR... use the if statement to add a div class that will colour your #main-wrapper background to red.

# Answer
> 0 votes
You don't need hooks to move the user login block to header. you can move the user login block to any region on the page. From block administer page move the login block to the header region. save and logout to check it working.

---
Tags: 7, forms, users
---


# Question
Title: Screenfly alternative for testing Drupal 8 sites
For Responsive screen testing I am using Screenfly (http://quirktools.com/screenfly/).

Drupal 8 can not be displayed inside an iframe (see link, par. 9). This is the reason why Screenfly can not be used to test Drupal 8 sites by default.

Are there any alternatives to Screenfly for responsive screen testing?

# Answer
With Google Chrome `CTRL` \+ `SHIFT` \+ `I` also known as *right click* \>\> *Inspect*

Once the Developer Tools is open, then `CTRL` \+ `SHIFT` \+ `M` or click the 2nd icon

**With Responsive, you can resize to whatever you want by dragging the right border**
> 0 votes

# Answer
I recommend setting up Seleniums Docker solution. I use that to run Behat tests in, you can define multiple profiles in the behat.yml file. Using Chrome driver, each profile an be a different device emulation mode in Chrome. Then when you run behat - just pass a runtime arg telling it which profile to use.

I also recommend checking out the Drupal Behat Extension.

You may also want to look into visual regression testing as well.
> 0 votes

---
Tags: 8, theming, testing
---


# Question
Title: How to import decimal fields using Feeds?
I'm trying to import a decimal value from an XML feed to a Drupal decimal number field.

For example the XML feed source is: 7,6
Now I want to import it in a Drupal decimal field. So the field value will be the same: 7,6

Thing is, when I import the feed and the nodes are getting created - this field remains empty. Is this a bug or can someone point out what I'm doing wrong here?

# Answer
It could be that the there is an issue with how it's interpreting the value especially if you are in a non-English context. For example, in Drupal's terms if you have a decimal value it's formatted like so "7.6". If you are trying to import a decimal value formatted with "7,6" it may have an issue.

If it is a bug, you could try and import and use a module like Feeds Tamper to rewrite that field output so that Drupal will import it.

I just tested myself and it imports fine using English decimal notation.
> 3 votes

---
Tags: 7, entities, feeds
---


# Question
Title: Alternative to FieldCollection and FieldCollection Table
i have a fieldcollection field in a entity form type with FieldCollection Table display, and its set to unlimited value. In this field collection there are 5 fields. After some research I found that after insert 20/30 items, field collection slows down considerably. Infact, in my entityform, after 40 items of fieldcollection, increases the data loading time.

I'm looking for an alternative to fieldcollection with the ability to display the field in table such as field collection table.

can you help me?

Thanks

# Answer
Oh, good question.

combined with some fancy view work, you could use pretty much any fieldable entity in Drupal to do this.

You could use another content type with entity relationships to link the two. You can render it with an Entity Reference Views Widget and use a views table to format that output.

If you don't want to use a content type, you can also explore custom entities.

Reading:

Now, if you don't want to have to try and do this in code, there is also a great module called ECK (Entity Construction Kit) which allows you to build fieldable entities and use them just like any other all from within the Drupal admin UI.

Hope this helps.
> 0 votes

---
Tags: entities
---


# Question
Title: CRUD operations on site from external application
We have an application behind our firewall that we want to push content to a content type on our external Drupal site. Our internal application will need to create new nodes, update existing nodes, and delete existing nodes as needed. It would also have to have some kind of authentication method that would be used by the application.

What modules/process (services maybe) are best for doing this type of action on the Drupal site? What type of custom programming will need to be done on the Drupal side to allow this?

# Answer
> 0 votes
Services might be your easiest path to success. For custom programming, your custom application would need to be able to make a RESTful (or SOAP) call against an external endpoint.

Services can accept a lot of data input depending on how you set it up. Everything from:

* bencode
* json
* jsonp
* php
* xml
* yaml

You can configure most of this from the UI, but if you want you can extend the services module and create custom resources and tune the data you take in and what variables you expose.

For authentication, you have a lot of options. By default, session authentication comes with it, but you can extend via modules to add things like API key authentication, basic authentication, Oauth and more.

One of many guides: https://www.ostraining.com/blog/drupal/services/

# Answer
> 1 votes
I use a custom module to do this very thing in D7. It works like this:

* The internal applications write to a transaction log (a database table) reflecting changes that will need to be added/edited/deleted on the site.
* A simple API app exposes this transaction log over the Internet, with API keys.
* The Drupal site reads new transaction log entries (it remembers the last log entry it synchronized) from the API then queues and makes the node changes when cron runs.

You could do something similar in D8. Or, considering Drupal 8 has a RESTful API, you could instrument your internal application to make synchronous changes to the Drupal site.

---
Tags: services
---


# Question
Title: How can I force a JavaScript library to load in the <head> of a page?
How do I force a JavaScript library to load in the \< head \> in Drupal 8?

Here's my themename.libraries.yml file:

```
zaccordion:
  version: 1.x
  js:
    js/jquery.zaccordion.js: { header: true }
    js/jquery.zaccordion.min.js: { header: true }
    js/zaccordionUsage.js: { header: true }
  dependencies:
    - core/jquery

```

It still loads in the footer however.

# Answer
`header: true` needs to go under your js declaration, not within each file.

See: https://www.drupal.org/docs/8/theming-drupal-8/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme

> By default, all JS assets are now loaded in the footer. Being loaded in the header is now an opt-in choice, that is only necessary for critical UI elements that cannot be shown unless their corresponding JS has already run.

```
js-header:
  header: true
  js:
    header.js: {}

js-footer:
  js:
    footer.js: {}

```

> You have to set the new header property on asset library definitions to true, to indicate that the JavaScript assets in that asset library are in the critical path, and should therefore be loaded from the header. Note that any dependencies — direct and indirect — of asset libraries marked as being in the critical path are also automatically loaded from the header, so you don't need to worry about dependencies being unavailable.
> 14 votes

---
Tags: 8, javascript
---


# Question
Title: How to load jQuery assets before blocks and regions
I need a jQuery script to load **immediately** before a certain block shows on my Drupal 8 front page. I'm trying to use the following but I get 'TypeError $ is not a function' in code inspector. Here's my script:

```
$(document).ready(function() {
  $("#slideshow").zAccordion({
        ...code...
  });
});

```

The problem is the first line. In Drupal 8 what is the preferred way to write this script to accomplish what I want?

# Answer
You have to wrap the javascript to avoid namespace conflicts.

```
(function ($) {
  $(document).ready(function() {
    $("#slideshow").zAccordion({
        ...code...
    });
  });
})(jQuery);

```
> 4 votes

---
Tags: 8, javascript
---


# Question
Title: Field Collection Data Deletion for particular Content type
I have one senario where 2 for content type i have added field collection field.

Each content type has around 3k plus nodes data. each nodes has 50+ records of field collections. All content creation done through excel import functionality.

For second content type, the field collection records that i imported is wrong. i want delete all the fields collection items only for second content type.

How to do it? i can't manually since it has 3k+ nodes and 50+ records in each nodes.

Any module which handle these kind of scenario? or any coding documentation which help me here.

as i search i got few related links as below. but none of them completely fit my requirement.

Could anyone please let me know or help me achieve this.

Deleting field collection items : As mentioned on this page i can't play with DB.

Field Collection Value field is not deleting correctly(using programmatically) : looks like i can use it deletion of data. but how for particular content type.

And I have to give one interface on the site where a non-technical guy can handle this if the same mistake happens.

If anybody knows please help.

Thanks in Advance.

# Answer
> 1 votes
My suggestion is to do this using code. IF your using D7, try following code in any custom module or in a basic page.

```
//Use a query to get all nodes of your particular content type.

$results = db_query("SELECT nid FROM node WHERE type = 'your-content-type'");
$nids = array();
foreach($results as $result){
  $nids[] = $result->nid;
}

foreach($nids as $nid){ // use for loop for testing
  $node = node_load($nid);
  foreach ($node->field_international_activity[LANGUAGE_NONE] as $key => $value) {
   // Build array of field collection values.
   $field_collection_item_values[] = $value['value'];

   // Unset them.
   unset($node->field_international_activity[LANGUAGE_NONE][$key]);
  }

// Delete field collection items.
entity_delete_multiple('field_collection_item', $field_collection_item_values);
node_save($node);
}

```

For more details please refer link1, link2

This code is not tested, first just try for a single node by using a **for loop** instead of **foreach**.

---
Tags: entities
---


# Question
Title: How to replace current symbols with font awesome icons in every pager?
I want to replace current symbols with font awesome icons in every pager on my site. Problem is, the icon tag is printing as text, not as html. Here's my code:

```
function default_preprocess_pager(&$vars, $hook) {
  if ($vars['quantity'] > 5) $vars['quantity'] = 5;
  $vars['tags'][0] = '<<';
  $vars['tags'][1] = '<';
  $vars['tags'][3] = '>';
  $vars['tags'][4] = '<i class="fa fa-arrow-double"></i>';
}

```

# Answer
If you look at function theme\_pager you see this line:

```
 $li_last = theme('pager_last', array('text' => (isset($tags[4]) ? $tags[4] : t('last »')), 'element' => $element, 'parameters' => $parameters));

```

which eventually leads you via theme\_pager\_last to function theme\_pager\_link which has this bit of code:

```
return '<a' . drupal_attributes($attributes) . '>' . check_plain($text) . '</a>';

```

where check\_plain is the function that converts html to text.

so you need to supply your own version of theme\_pager\_link. Look at this post and others for information on how to do that:

How to override theme functions in Drupal 7
> 1 votes

---
Tags: paging
---


title: Adding (external) javascript to a theme

text:
# Question
Title: Adding (external) javascript to a theme
I'm trying to add external JavaScript to my Drupal 8 theme. Can someone tell me what I'm doing wrong here? This function is in my MYTHEME.theme file:

```
      function MYTHEME_preprocess_page(&$variables) {
      $vars['ext_js'] = array(
        '#attached' => array(
          'data' => 'http://cdn.somelibrary.com/library/2.3.1/js/jslibrary.min.js',
          'options' => array(
            'preprocess' => TRUE,
            'every_page' => TRUE,
            'group' => 'NONE',
            ),
        ),
      );
}

```

Then in the theme I'm rendering it with:

```
{{ ext_js }}

```

# Answer
> 3 votes
Try adding `'type' => 'external'`, to the `options` array index.
By default, the type is considered to be a reference to a file hosted on your Drupal site; by using `'type' => 'external'`, you are specifying that `data` is a reference to a file hosted on a different host.

# Answer
> 3 votes
The simplest way I find is to just so something like this in your theme .libraries.yml:

```
name_of_library:
  js:
    base:
      'https://path.com/to/js.js': { external: true }

```

Then call it using your .info or .theme file.

# Answer
> 1 votes
This is no Drupal 7, some things have changed, the easiest way to add an external library tested on my local is the following:

locate your MYTHEME.libraries.yml

here you are declaring the new library, change the values for yours.

add the following lines to the file:

```
bootstrap:
  version: 1.0
  header: true
    js:
      https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js: {}

```

Spacing is really important.

Then simply call the library from you twig template file: example:

```
{{ attach_library('MYTHEME/bootstrap') }}

```

don't forget to cache:rebuild

# Answer
> 0 votes
Refer to *Inline JavaScript* mentioned in Drupal Community Documentation about how to Adding stylesheets (CSS) and JavaScript (JS) to a **Drupal 8 theme**, you can put it in either a custom block or even directly in a **Twig template**.

Take a look on this documentation on how to locate the current twig filename, say your twig file is.: \[DRUPAL8\_ROOT\_FOLDER\]/themes/\[THEME\_NAME\]/templates/html.html.twig
then modify the html as below:

```
<!DOCTYPE html>
<html{{ html_attributes }}>
  <head>
    <head-placeholder token="{{ placeholder_token|raw }}">
    <title>{{ head_title|safe_join(' | ') }}</title>
    <css-placeholder token="{{ placeholder_token|raw }}">
    <js-placeholder token="{{ placeholder_token|raw }}">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta name="HandheldFriendly" content="true" />
    <meta name="apple-touch-fullscreen" content="YES" />
    <script scr="PUT-YOUR-EXTERNAL-SCRIPT_URL-HERE"></script>
  </head>
  <body{{ attributes }}>
    <a href="#main-content" class="visually-hidden focusable">
      {{ 'Skip to main content'|t }}
    </a>
    {{ page_top }}
    {{ page }}
    {{ page_bottom }}
    <js-bottom-placeholder token="{{ placeholder_token|raw }}">
  </body>
</html>

```

I've put an external script for sharing button on the twig file in my theme. Then Install Drush to *rebuild* the cache using `drush cache-rebuild`. Seems it works. You may check it on *my drupal site*.

---
Tags: theming, javascript, 8
---


title: How to show pricing attributes in View

text:
# Question
Title: How to show pricing attributes in View
I'm using Pricing Attributes module, but i don't know how to show its in line item view, in shopping cart view and in shopping cart form view.

How do it?

Thanks

# Answer
You need to edit the following view: Shopping cart form (Commerce Order). And add a the field: Commerce Line Item: Product Attributes, this will show the product with the extra attributes.
> 0 votes

---
Tags: commerce
---


# Question
Title: Pass php variables to js without drupal behaviour
I stand on the following tricky situation:

I have a node with geofield coordinates attached. I am constructing an array of points. Something like:

```
Array
(
[86] => Array
    (
        [0] => Array
            (
                [lat] => 39.1641410477
                [lon] => -2.633972168
            )

        [1] => Array
            (
                [lat] => 41.0420738489
                [lon] => -2.633972168
            )

        [2] => Array
            (
                [lat] => 41.0420738489
                [lon] => 1.2524414063
            )

        [3] => Array
            (
                [lat] => 39.1641410477
                [lon] => 1.2524414063
            )
        [4] => Array
            (
                [lat] => 39.1641410477
                [lon] => -2.633972168
            )
    )

[85] => Array
    (
        [0] => Array
            (
                [lat] => 39.1641410477
                [lon] => -2.633972168
            )

        [1] => Array
            (
                [lat] => 41.0420738489
                [lon] => -2.633972168
            )

        [2] => Array
            (
                [lat] => 41.0420738489
                [lon] => 1.2524414063
            )

        [3] => Array
            (
                [lat] => 39.1641410477
                [lon] => 1.2524414063
            )
        [4] => Array
            (
                [lat] => 39.1641410477
                [lon] => -2.633972168
            )
    )
)

```

I want to pass this to my-googlemaps.js in order to be used by google's init map Google map is defined as:

```
my-map:
  header: true
js:
  js/my-googlemaps.js: { }
  https://maps.googleapis.com/maps/api/js?key=my_key&callback=initMap: {type: external, attributes: {defer: true,async: true}}
dependencies:
  - core/drupal
  - core/drupalSettings

my-googlemaps.js:
  console.log(Drupal.settings);
  function initMap() {}

```

This way I get Drupal.settings undefined, which makes sense I guess. On the other hanve if I place initMap into a behavior It can not be seen as a callback as defined in googleapis.com before.

Has anyone stumbled with this before? Any idea how to attack the problem?

# Answer
You can follow document.

> Attaching configurable JavaScript
>
> In some cases, you may want to add JavaScript to a page that depends on some computed PHP information.
>
> In this case, create a JavaScript file, define and attach a library just like before, but also attach JavaScript settings and have that JavaScript file read those settings, via drupalSettings (the successor to Drupal 7's Drupal.settings). However, to make drupalSettings available to our JavaScript file, we have to do the same work as we had to do to make jQuery available: we have to declare a dependency on it.
>
> So that then becomes:

```
cuddly-slider:
  version: 1.x
  js:
    js/cuddly-slider.js: {}
  dependencies:
    - core/jquery
    - core/drupalSettings

```

> and

```
$build['#attached']['library'][] = 'fluffiness/cuddly-slider';
$build['#attached']['drupalSettings']['fluffiness']['cuddlySlider']['foo'] = 'bar';

```

Where 'bar' is some calculated value.

> Then cuddly-slider.js will be able to access drupalSettings.fluffiness.cuddlySlider.foo (and it will === 'bar').

In your case. You need use hook\_preprocess\_node() to add array geofield.

```
function YOUR_MODULE_preprocess_node($vars) {
  // You nedd process to get $geofield
  $vars['#attached']['drupalSettings']['geoField'] = $geofield
}

```

and file js/my-googlemaps.js you need code.

```
(function($, Drupal, drupalSettings) {
  Drupal.behaviors.yourbehavior = {
    attach: function (context, settings) {
       var geoField = drupalSettings.geoField.
      // You can init map here.
    }
  };
})(jQuery, Drupal, drupalSettings);

```
> 12 votes

---
Tags: 8, javascript
---


# Question
Title: How to track and notify employees when their certifications have expired?
I am creating a Drupal 7 site where it tracks an employee's certification status, and notifies them if it has expired/is about to expire.

Currently, I have a content type called "Employee Info," where different types of certifications (under the "certifications" field, a list type) can be checked off for each employee, depending on which certs their job requires them to have.

For example, say I'm entering Billy John as a new employee who was certified in CPR, Cycling, but not Swimming. The CPR certification only lasts one year, and the Cycling cert lasts two. I would like it so the user can enter that Billy was certified for CPR on say, 1/1/15, and Cycling on 6/1/15, once their respective box is checked. Then, when 1/1/16 has rolled around, they get the notification that their CPR certification has expired (and likewise on 6/1/17 for their Cycling cert).

However, I am unsure how to do this, or if this is even the best approach to the problem.

Any help or guidance would be greatly appreciated!

# Answer
Your question doesn't specify *how* such notifications should be implemented. Though there are at least 2 possible implementations:

* Send an eMail to such employee when the time is right.
* Create some type of alert when the employee visits the site.

Read on for more details about either implementation.

# Create an alert

Enable the Menu Badges module, which can be used to add notifications to any **menu item** and/or **menu tab** of your choice. Here are some details about it (from its project page):

> Provides a method for adding iOS-style badges to menu items. (see screenshot)

Because of how it integrates with the Views module, you basically reduce the solution specific to your question here to something like this:

* Create an appropriate view about "*expired certifications*" (as in your question).
* And create a menu item or menu tab for it.
* Perform the required Menu Badges configuration to tell it which menu item/tab you used for it in your view.

Refer to the video Defining Menu Badges with Views in Drupal (from the module maintainer) for more details.

# Send an eMail

You could use the Rules module to send an eMail when the time is right. To do so, have a look at the question about "Rule to store user's last post date and scheduled rule based 30 day reminder", which may be considered as a variation of this question here. My answer to that question should be pretty close to what you're looking for.

If you'd replace `field_next_article` by an "expiration date" of a certificate, you already have what's suggested in "Step 1". You should be able to reuse most of the Rules Component included in Step 2, and the Rule included in step 3, with only some minor changes.
> 0 votes

---
Tags: 7, notifications
---


# Question
Title: What is the actions table for and can I delete orphaned actions?
I just ran

```
$ drush cc all -v

```

and it tells me I have orphaned actions. I'm curious to what the actions table is for in Drupal 7 and if it's safe to just drop all the data in the actions table?

# Answer
> 3 votes
There is no button or link or even an indication that orphans exist when going to `/admin/config/system/actions`.

I don't really get why, but when I visit `/admin/config/system/actions/orphan` the orphaned actions are removed. I'm watching the Drupal log when I go to that path and it systematically removes all the orphans.

# Answer
> 2 votes
If you visit `/admin/config/system/actions` you will see a list of the actions currently on your system. These actions are declared in the modules (named under *Action Type*), and may be orphaned if a module is de-activated.

Clearing orphaned actions is fine, but if you drop the table, you will break your site.

# Answer
> 1 votes
If you're using Devel module then you can simply go to `your-site/devel/php` and then execute the below code:

```
actions_synchronize(TRUE);

```

Your question indicates you have `drush` so you could evaluate the command with that;

`drush eval 'actions_synchronize(TRUE)'`

If you need to do this on a remote install where you don't have access to `drush` you can add this to a custom module's `.install` file with a hook\_update\_n()

```
/**
 * Implements hook_update_n().
 * actions_synchronize().
 */
function yourmodule_update_7001() {
  actions_synchronize(TRUE);
}

```

and then execute `yoursite/update.php`. You can test this locally using `drush updb` as well.

---
Tags: 7, actions
---


# Question
Title: How much memory and storage does a website take on a server?
Hello Drupal community!

This is my first time working with Drupal and AWS. I would like to know if an AWS t2.micro instance would be good enough for running a new Drupal 8 website with moderate requirements. My main goal with this is to stay within the AWS free tier, i.e, spend no money for one year whatsoever. The EC2 information page states that a t2.micro instance has 1GB of memory and "EBS only" storage (bear in mind that this is the storage for the *server*). After looking into this I found that EBS has 30GB's of storage. Will that much be sufficient?

Totally I have to run a Drupal 8 site, an AWS RDS MySQL database and AWS S3, all on this instance comfortably (which obviously means a good amount of people should be able to view the website at the same time too). Any requirements for Drupal 8 would be welcomed.

Please get me out of this jam. Thanks a bunch!

# Answer
> 0 votes
You should be fine with 1GB server ram, and 256M set for PHP. Keep in mind you won't be running a huge site with it, so also invest in getting caching like memcache and something like varnish going as well. I'm not sure if memcache is PHP7 ready yet - but using php7 will gain some performance increase as well.

However if you're looking for free hosting, I think you could also try Acquia Cloud Free.

---
Tags: 8
---


# Question
Title: Why file name and uri of the file in database are different?
I am uploading the files to the folder by using `file_save_upload` and `file_move` to achieve this. Its working fine but a problem arises while saving in database. I have used `FILE_EXISTS_RENAME` argument, so in `file_managed` table `filename` column and `uri` column file name is not same. In `filename` column its not appending the integer value, but in uri column its appending the integer value since the file is already exist. Below is my code:

```
  for ($i = 0; $i < $num_files; $i++) {
      $file = file_save_upload($i, $validators, FILE_EXISTS_RENAME);
      if ($file) {
        $file->status = FILE_STATUS_PERMANENT;
        if ($file = file_move($file, 'public://feed-files/' . $foldername, FILE_EXISTS_RENAME)) {
          $form_state['values']['file'][$i] = $file;
        }
        else {
          form_set_error('file', t('Failed to write the uploaded file to the selected folder.'));
          return FALSE;
        }
      }
      else {
        form_set_error('file', t('No file was uploaded.'));
        return FALSE;
      }
    }

```

below is the database values:

So how can achieve that `filename` and `uri` column file name should be same. Any suggestions will be appreciated.

# Answer
> 0 votes
The reason for difference is that multiple files with same name can be uploaded in Drupal, so when you upload a file, it adds a counter at the end of filename so that if a file with same name is uploaded again, then it doesn't replace another one.

Also the filename column contains the exact name of the uploaded file as it is used while downloading the file (the file will be downloaded with this name).

---
Tags: 7, database, files
---


# Question
Title: PHP fatal error on server after deactivating modules
Today our site went down with only white pages showing. The logs from the nginx server looks like this:

```
[01-Sep-2016 10:33:15] WARNING: [pool www0] child 26970 said into stderr: "NOTICE: PHP message: PHP Fatal error:  Class 'MigrateSimpleFieldHandler' not found in /srv/www/mysite/public_html/sites/all/modules/entityreference/entityreference.migrate.inc on line 18"
[01-Sep-2016 10:33:15] WARNING: [pool www0] child 26970 said into stderr: "NOTICE: PHP message: PHP Fatal error:  Class 'MigrateUIWizard' not found in /srv/www/mysite/public_html/sites/all/modules/migrate_d2d/migrate_d2d_ui/migrate_d2d_ui.migrate.inc on line 18"
[01-Sep-2016 10:33:20] WARNING: [pool www1] child 26712 said into stderr: "NOTICE: PHP message: PHP Fatal error:  Class name must be a valid object or a string in /srv/www/mysite/public_html/includes/common.inc on line 8026"
[01-Sep-2016 10:33:24] WARNING: [pool www1] child 26710 said into stderr: "NOTICE: PHP message: PHP Fatal error:  Class name must be a valid object or a string in /srv/www/mysite/public_html/includes/common.inc on line 8026"
[01-Sep-2016 10:34:27] WARNING: [pool www1] child 27190 said into stderr: "NOTICE: PHP message: PHP Fatal error:  Class name must be a valid object or a string in /srv/www/mysite/public_html/includes/common.inc on line 8026"
[01-Sep-2016 10:34:40] WARNING: [pool www1] child 26712 said into stderr: "NOTICE: PHP message: PHP Fatal error:  Class name must be a valid object or a string in /srv/www/mysite/public_html/includes/common.inc on line 8026"
[01-Sep-2016 10:34:56] WARNING: [pool www0] child 23319 said into stderr: "NOTICE: PHP message: PHP Fatal error:  Class name must be a valid object or a string in /srv/www/mysite/public_html/includes/common.inc on line 8026"

```

This happens as soon as I try to update the database, I also get a "502 Bad Gateway" message from the server just before the screen turns white.

Should I activate the deactivated modules again or uninstall them?

EDITED: I can also mention that according to the status report there are database updates waiting to be run, but when I do that locally (wamp) I get the message that no database update is required. When I try to do this db update on the web server (nginx) I get 502 bad gateway error and then the pages go blank.

# Answer
> 0 votes
Finally the problem is solved thanks to this thread. The database update wasn't possible for the Field collection module (but it could have been any number of modules), but with the help of all the people that contributed to the solution in the thread above, I was able to get the db update to run as expected. After that everything seems to work.

---
Tags: 7, migrations
---


# Question
Title: How to complement eMail notifications with a notification bar?
I am building a Drupal 7 website, and I noticed that you can install a facebook-like chat. This made me wonder if it is possible to implement something related to notifications that works something like Facebook. I simply want the notification "bar" to tell me if a user is posting a comment on my website, or if a new user has signed up. At this moment I just get an email about users trying to sign up.

I looked at the Notifications module for D7, but I am not sure this is what I am looking for. Or maybe I just don't know how to use it.

# Answer
> 5 votes
You may be looking for Heartbeat module:

> Heartbeat displays user activity on a website. This module is an API to log activity. The logged data contains message structures, attributes and variables. Once the activity messages exist in the database, they will be parsed and build into activity streams.
>
> (...)
>
> Heartbeat has global configuration for display, message template configuration and stream configuration.

# Answer
> 3 votes
Since you already get a notification when users sign up, for comment notification you can use Comment notify module

> Notifies administrator (site\_mail) of new user registrations. Starting with Version 1.2 you can now define both the address it goes to and the subject and messages emailed. Starting with 1.8 you can get emails when someone updates their profile as well. Starting with 1.11 you can use actual profile pieces not just a list of them all. Example if you have a profile\_name you would insert in the template !profile\_name and the value of profile\_name will be inserted.

Any other notifications can be achieved using rules

# Answer
> 2 votes
You should go for Message module which is an advanced module for messaging and notification and maintained actively.

> Message module is Drupal 7's answer to activity-streams and a flexible Messaging & Notifications system.

# Answer
> 0 votes
The combination of Rules, Messages to Block and Menu Badges modules does the trick.

# Answer
> 0 votes
You could use the Menu Badges module for such notifications, which you can add to any **menu item** and/or **menu tab** of your choice. In your case something like "***New comments***" seems like one, out of a few, appropriate menu item (or menu tab).

Here are some details about it (from its project page):

> Provides a method for adding iOS-style badges to menu items. (see screenshot)
>
> ### Adding Badges to Menus
>
> Once enabled, go to `Administration > Structure > Menus`, and click "list links" next to the menu containing the target item. Click "edit" next to the item and select the badge to display with the Display Menu Badge select box.
>
> ### Adding Badges to Tabs
>
> For adding badges to menu tabs, there is a tab under `Administration > Structure > Menus` called "Tab Menu Badges". Search for the menu router path of the tab you want to alter, then select a badge from the corresponding select box.
>
> ### Badge Types
>
> The module includes five example badges, and new badges can be created easily with Views. Modules can also supply their own badges with a hook implementation. See the README.txt file for details.

Because of how it integrates with the Views module, by using this integration you basically reduce the solution for any type of notification to something like "Just create an appropriate view of it".

However, there is a small caveat: if you really want the actual number (shown in the red circle) to be accurate, make sure you have some field in your view that will actually correspond to the "`new`" part of your question. To better explain this: have a look at the "`tracker`" view (disabled by default), which has the field "***Content:Has new content***" (or variation: "***Content:Has new comments***"). This is a perfect field to use if you want to use Menu Badges to get notified whenever there is new content (or variation: new comments).

If you don't have such "new" indicator, then you basically have 2 variations to get around that:

### Video tutorials:

---
Tags: 7, notifications
---


# Question
Title: How to preserve kint output upon form submit redirection?
I've attached a custom submit handler to node add/edit form for the article content type:

```
$form['actions']['publish']['#submit'][] = 'my_module_node_edit_submit';

```

In the handler, I am trying to inspect the form state values with **kint** (via the devel module):

```
kint($form_state->getValues());

```

Upon submission of the form, I'm able to briefly see the **kint** output on the screen, but I am also presented with this message:

> Redirecting to http://localhost/example.com/node/123

The page then redirects back to view the node, and the kint output is gone. How can I preserve the kint output so it is available after the redirection?

# Answer
Use *ksm()* instead of *kint()*.

I ran into the same issue when I want to inspect the entity after saving, using drupal's hook\_entity\_presave and **kint**

I found this article on how to print variables using kint() which explains that *ksm()* prints the output inside the drupal page (not before as kint()) does.

So this example prints the entity without redirecting:

```
function mymodule_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  ksm($entity->toArray());
}

```
> 10 votes

# Answer
That is the normal behavior of the submit function, to process the form and redirect. If you want to debug this without any tools, then do a `var_dump()` and then stop the php with `die`. But debugging without tools is of course not very productive. When you want to do serious work, use xdebug and an IDE of your choice.

**Edit:** Another way would be to use the message area, for example with drupal\_set\_message or dpm() from devel. This puts the debugging information in a session and you can see it after the redirect.
> 0 votes

---
Tags: 8
---


# Question
Title: how to automatically select entity reference field value from url when adding a node
I have a content type "Students" which has an entity reference field "Course".

Course field shows a list of course nodes titles from a view.

When adding a new student node, I need the course field to be automatically selected as per the URL value.

I will pass the course ID in the URL like this.

```
/node/add/student/COURSEID

```

Any idea how to get this done ? thanks

# Answer
You could use Entity Reference Prepopulate module

> Allow prepopulating any Entity reference field via URL

README.txt

> **Usage**
>
> In order to pre-populate an entity reference field you have to supply the parameter in the URL.
>
> The structure is node/add/article?\[field\_ref\]=\[id\]
>
> Where \[field\_ref\] is the name of the entity reference field and \[id\] is the id of the entity being referenced.
>
> Examples:
>
> node/add/article?field\_foo=1
>
> node/add/page?field\_bar=1,2,3
> 1 votes

# Answer
I think the easiest way would be to use hook\_form\_alter() and set a default value for the field. You can use arg() to get the course ID
> 1 votes

# Answer
Another jQuery quick and dirty way.

```
jQuery( document ).ready(function($) {

    var the_url  = window.location.href;
    var nid_from_url = the_url.substr(the_url.lastIndexOf('/') + 1);
    //change the selected value of the select list of courses.
    $('.page-node-add-offline-course-pictures #edit-field-offline-course-reference2-und').val(nid_from_url);
    });

```
> 0 votes

---
Tags: 7, nodes
---


title: The machine name of custom view

text:
# Question
Title: The machine name of custom view
I created my own view thanks to Views module. How can I check the machine name of that view?

# Answer
Go to the edit screen for your view. At the top right, just under **Displays** you will see a button labelled *Edit view/name/description* (right under the Save and Cancel buttons). This is a drop down. Click on it and choose *export view*.

The second item in the export is the machinr name of the view:

```
$view = new view();
$view->name = 'your_view_name';
$view->description = ...

```
> 8 votes

# Answer
Hope this will help you.

* In Drupal 7 if you want to know whats your view MACHINE name.

To get **VIEWS machine name**

* Edit your **VIEW**, in the **URL** you can see machine name `sitename/admin/structure/views/view/**machine_name**/edit`

To get **Display Machine Name**

* Go to **VIEWS \> ADVANCED TAB \> Machine Name**
> 4 votes

# Answer
You can also hover over the 'edit' button for the view in the views list (admin/structure/views) to see the view machine name in a browser tooltip - may be a little easier than exporting the view?
> 1 votes

# Answer
I found the way to check that is used machine\_name was using the following function for an a page:

```
$current_view = views_get_page_view();
$machine_name_current = $current_view->current_display;
print $machine_name_current;

```

Saludos.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Am I able to use dynamic parameters in libraries configuration files?
I have hard coded GMaps API key in URL inside in the libraries.yml file.

Would I be able to use a dynamic parameter for this key?

# Answer
You should be able to use `hook_library_info_build()`. It's a new (to D8) hook that allows you to define libraries at runtime.

Here's the change record that talks about it's introduction. It's unlikely to go anywhere, but here's the description from the change record:

> There was no way to dynamically register libraries. Using hook\_library\_info\_alter() to register new library is possible but doesn't end well in alter/weight.
>
> Therefore a new hook is created namely hook\_library\_info\_build()

Alternatively; you could potentially add the hook as normal in your `example.libraries.yml` file, and then use `hook_library_info_alter`.
> 3 votes

---
Tags: 8
---


title: Create an SVG using data from Views

text:
# Question
Title: Create an SVG using data from Views
I am looking for a way to create a dynamically-generated SVG graphic based on data returned in a view from the Views module. Since Views creates lists and SVG is ultimately XML and therefore DOM-based, they seem perfectly well-suited to work together.

I have seen a few posts around saying that SVG support/integration in Drupal is very limited, and I have only ever seen Javascript used to create an SVG and then manipulate it's DOM. There are some popular javascript libraries already in use, such as Raphaël and svgweb.

Has anyone seen PHP used to do this as well? I have seen the SVG Embed module but it's very new, hasn't been updated since July, and almost nobody is using it.

Does anyone know of a better way to integrate SVG and Drupal Views?

# Answer
Without knowing your exact use case (I'm assuming you want to just use Views to use the results to build an SVG); it sounds like building a custom Views display style plugin might be in order.

There's a tutorial on Drupal.org (for Drupal 8, but the premise is the same), although I must confess I've only skim read it; and haven't tried implementing it: Building a Views display style plugin for Drupal 8.
> 0 votes

---
Tags: views, javascript
---


# Question
Title: Deleting field revisions directly from the database
With full recognition that this is not considered a best practice (and is generally considered a worst practice) does anyone know if it is safe to delete field revisions directly from the DB via a DELETE query assuming I can guarantee that only the latest revision is being used/referenced everywhere on the site.

I ask this question because I have a particular field that has grown so large the our update hook is taking too long. I'm looking to cheat and seeing if anyone has had experience with this.

# Answer
> 0 votes
There was a module in 7 that tried to solve this, Field SQL No Revisions. I am not sure how far along a Drupal 8 port is, but this is where you might want to start. However, that module keeps those tables empty, instead of just the 'latest' record.

Previously (7.x), I used to have hook\_cron routines that would purge revision tables of any old data not being used to keep size down. We had some DBs that were huge due to that, which made backups and dev syncing take forever and be cumbersome. It really helped. You'll want to be careful and use the respective API over a database query, so the rest of Drupal is informed about what is happening and can take action (or if your site has no dependencies it might not matter, but it is always, always safer).

---
Tags: entities, 8
---


title: Feeds and PHP 7.0

text:
# Question
Title: Feeds and PHP 7.0
I am using Drupal 7 on Ubuntu 16, Apache 2.4.20, and PHP 7.0.9.

When attempting to use a Feed importer on PHP 7.0, I receive a 500 AJAX Error that gives no Response Text.

Additionally, nothing is shown in the error logs.

However, when switching my Apache PHP version back to 5.6, it works just fine.

Is there any support for Feeds on PHP 7.0 this yet? Or should I stay away from PHP 7 for a while?

# Answer
As suggested in the comments, I reported this issue and found the solution.

The issue was the feeds tamper module. Updating from Feeds Tamper version 7.x-1.1 to 7.x-1.x-dev solved the issue.

So if you are using PHP 7.0, I recommend using Feeds version 7.x-2.0-beta2 and Feeds Tamper 7.x-1.x-dev.

Here is a link to the issue I opened: https://www.drupal.org/node/2790355#comment-11571211

I hope this helps others with this situation.
> 0 votes

---
Tags: 7, feeds
---


title: Simplesamlphp Auth Role Assignment

text:
# Question
Title: Simplesamlphp Auth Role Assignment
I've set up my Drupal installation as a Service Provider using Simplesamlphp and the Drupal Module Simplesamlphp Authentication (https://www.drupal.org/project/simplesamlphp\_auth). I'm successfully able to login using the www.example.com/saml\_login method provided, but I haven't been able to setup the automatic role assignments.

From this page: https://www.drupal.org/node/1931394

I've attempted comment #3 but was unable to get it to use the friendly name. Here is what is being sent to me from my IDP:

```
<saml2:AttributeStatement>
         <saml2:Attribute FriendlyName="uid"
                          Name="urn:oid:0.9.2342.19200300.100.1.1"
                          NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"
                          >
             <saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                                   xsi:type="xs:string"
                                   >landy</saml2:AttributeValue>
         </saml2:Attribute>
         <saml2:Attribute FriendlyName="eduPersonAffiliation"
                          Name="urn:oid:1.3.6.1.4.1.5923.1.1.1.1"
                          NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"
                          >
             <saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                                   xsi:type="xs:string"
                                   >member</saml2:AttributeValue>
             <saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                                   xsi:type="xs:string"
                                   >staff</saml2:AttributeValue>
             <saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                                   xsi:type="xs:string"
                                   >employee</saml2:AttributeValue>
         </saml2:Attribute>
         <saml2:Attribute FriendlyName="eduPersonPrincipalName"
                          Name="urn:oid:1.3.6.1.4.1.5923.1.1.1.6"
                          NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"
                          >
             <saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                                   xsi:type="xs:string"
                                   >landy@uab.edu</saml2:AttributeValue>
         </saml2:Attribute>
     </saml2:AttributeStatement>

```

But I'm unable to get it to automatically populate the role. As an example, I've tried this: 3:uid,=,landy

It's never assigned him to RoleID 3. I've been able to do this from the Rules module, but I'd like to be able to use it in this module if possible because the eventual plan is to use those Affiliation attributes as well which Rules cannot use. Thanks for any help!

# Answer
> 0 votes
I've figured out the issue.

From here: https://simplesamlphp.org/docs/stable/simplesamlphp-authproc

I had to rename the attributes to friendly names so I could use them in the assignment feature of the module. The previous URL attempted to do that, but it wasn't quite as easy as the one line. I had to add each URN to change to the friendly name that I wanted.

---
Tags: 7
---


title: Possible to add form elements via js?

text:
# Question
Title: Possible to add form elements via js?
Is it possible to add/remove form elements with clientside js? I am using ajax, but it is a bit too slow for the kind of dynamic elements I need.

# Answer
> 1 votes
You can hide and unhide form elements with js. For example you can prepare a popup and deliver it with the main form and then trigger it in js.

You can't generate new elements, because they will be ignored when submitted.

You could build your own form solution with custom js and php code. But this is probably not the best way on the long term.

The best answer to your question, how to build dynamic form solutions, is to investigate, what you can do with a js framework and Rest API.

---
Tags: forms, 8, javascript
---


title: How to use RegexConstraint with field?

text:
# Question
Title: How to use RegexConstraint with field?
I'm defining a base field for my custom content entity:

```
$fields['machine_name'] = BaseFieldDefinition::create('string')
  ->setLabel(t('Machine name'))
  ->addConstraint('UniqueField')
  ->addConstraint('Regex', ['pattern' => '[^a-z0-9_]+'])
  ->setTranslatable(false)
  ->setRequired(true);

```

However RegexValidator throws `UnexpectedTypeException` complaining that passed value is of type `FieldItemList`. This is obvious since in Drupal 8 even single value fields are lists (with one item).

So how can I use Regex validator with entity fields? Or do I have to write my own regex validator that will handle `FieldItemLists`?

# Answer
You do not need to create your own Validator. Instead, use setPropertyConstraints instead of addConstraint to attach the Regex validator to the individual property of the field rather than the FieldItemList. For a string field, add the constraint to "value." For a link field, you may want to add it to "URI," etc. Here is an example:

```
->setPropertyConstraints(
  'value', ['Regex' => [
    'pattern' => '/^[0-9]+$/',
    'message' => t('Please use numbers only in the blah field.'),
  ]]
);

```
> 5 votes

# Answer
I ended up writing my own Validator and Constraint classes.

`FieldRegexValidator` class:

```
class FieldRegexValidator extends RegexValidator {

  /**
   * @inheritDoc
   */
  public function validate($value, Constraint $constraint) {
    // When dealing with FieldItemLists we have to check all of it's items.
    if ($value instanceof FieldItemList) {
      foreach ($value as $item) {
        parent::validate(reset($item->getValue()), $constraint);
      }
    } else {
      // This is the default behavior of parent class.
      parent::validate($value, $constraint);
    }
  }

}

```

`FieldRegexConstraint` class:

```
/**
 * Regex constraint for fields.
 *
 * Extends the core Drupal validation to handle FieldItemList correctly.
 *
 * @Constraint(
 *   id = "FieldRegex",
 *   label = @Translation("Field regex", context = "Validation")
 * )
 */
class FieldRegexConstraint extends RegexConstraint {

  public $message = 'This value does not match requested pattern.';

  /**
   * {@inheritdoc}
   */
  public function validatedBy() {
    return 'Drupal\gaps\Plugin\Validation\Constraint\FieldRegexValidator';
  }
}

```
> 2 votes

---
Tags: entities, 8
---


title: Set minimum quantity in product

text:
# Question
Title: Set minimum quantity in product
I'm looking for a way to set a minimum quantity per product in a Drupal Commerce store.

I found this module which claims to do just this, but I can't get it working and the project seems abandoned:

I found this one which is useful if you need to set a minimum in the order but it doesn't help to set a minimum in products.

Is there any other way to do this?

# Answer
> 0 votes
I believe there's a quiet simple solution using rules. More specific based on the existing commerce\_stock by default enabled rules : \- Stock: validate add to cart \- Stock: validate checkout These rules have both an action "Set the state of the checkout process (called once per item)", preventing add to cart or checkout when the stock conditions are not met.

In order to check line item quantity with on product level defined minimum order quantities, you can clone these rules and alter the rule conditions. There's a way to implement a custom rule condition using hook\_rules\_condition\_info().

Example implementation could be :

```
/**
* Implements hook_rules_condition_info().
**/
function my_custommodule_rules_condition_info() {
  return array(
    'minimum_product_qty_applied' => array(
      'group' => t('Commerce Line item'),
      'label' => t('Min. product qty selected'),
      'parameter' => array(
        'commerce_line_item' => array(
          'type' => 'commerce_line_item',
          'label' => t('Commerce line item'),
        )
      ),
    ),
  );
}

function minimum_product_qty_applied($line_item) {
    return _check_minimum_product_qty($line_item); //returns TRUE or FALSE
}

```

---
Tags: commerce
---


# Question
Title: How do I create a multi-select checkbox field in a content entity?
Trying to figure out how to have 'Desktop', 'Mobile', and 'N/A' as check boxes on a config entity form in drupal 8, where I can select one or more options.

# Answer
This configuration worked for me:

```
 $fields['device'] = BaseFieldDefinition::create("list_string")
      ->setSetting('allowed_values', ['desktop'=>'Desktop', 'mobile'=>'Mobile', 'na'=>'N/A'])
      ->setLabel('Device')
      ->setDescription('Select associated devices')
      ->setRequired(TRUE)
      ->setCardinality(-1)
      ->setDisplayOptions('form', array(
        'type' => 'options_buttons',
        'weight' => 6
      ))
      ->setDisplayConfigurable('form', TRUE);

```
> 6 votes

---
Tags: 8, entities
---


# Question
Title: Why doesn't my code for passing a PHP variable to JavaScript work?
I am using the following code, but the JavaScript console prints `undefined` instead of the value of `settings.api_key`. What is wrong in the code I am using?

### libraries.yml file

```
stripe_files:
  version: 1.x
  js:
    https://js.stripe.com/v2/: { type: external, minified: false }
    js/custom_stripe.js: {}
  dependencies:
    - core/jquery
    - core/drupal.ajax
    - core/drupal
    - core/drupalSettings
    - core/jquery.once
  css:
    theme:
      css/custom_stripe_integration.module.css: {}

```

### JavaScript file

```
(function ($) {
    Drupal.behaviors.stripe = {
      attach: function (context, settings) {
        alert('hello4');
         console.log(settings.api_key);
      }
    };
})(jQuery);

```

### Form class

```
/**
 * @file
 * Contains \Drupal\amazing_forms\Form\ContributeForm.
 */

namespace Drupal\custom_stripe_integration\Form;
use Drupal\Core;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\user\SharedTempStore;
use Drupal\Component\Utility\Html;
use Drupal\Component\Utility\Unicode;
use Drupal\Core\Locale;

require_once 'modules/custom/donate_gateway/vendor/autoload.php';

/**
 * Contribute form.
 */
class StripeSponsorForm extends FormBase {
  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'stripe_sponsor_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state,$nid = 0) {
    $config = $this->config('custom_stripe_integration.settings');
    $api_key = $config->get('stripe_api_key');

    $form['#attached']['library'][] = 'custom_stripe_integration/stripe_files';
    $form['#attached']['drupalSettings']['api_key'] = $api_key;

    return $form;
  }
}

```

# Answer
For anyone coming here looking for a simple example of stashing data in `drupalSettings` and pulling it back out on the js side. Here's an example in a form.

In `buildForm` or `form_hook_alter` etc:

```
$form['#attached']['drupalSettings']['foo'] = 'bar';

```

Then in the js file of your choice (in your theme) be sure to wrap your code in a function and provide the things you want. In this example, I'm providing jQuery and drupalSettings.

```
(function($, drupalSettings) {

  console.log(drupalSettings);

})(jQuery, drupalSettings);

```

You should see in your console that the `drupalSettings` object has the key 'foo' on it alongside some other internal ones. That's why Kevin suggests putting your data a level deeper with `['drupalSettings']['my_module']['foo']`, but it's not necessary. Additionally, you don't need to specify `core/drupalSettings` as a dependency in your `libraries.yml` or do anything else to make `drupalSettings` available. You get it for free.

---

As for actually answering the question . . . I'm not sure what @kiamlaluno is talking about when he says to replace `drupalSettings` with `settings`. I can, however, show you (@harshal) what your function should look like based on my example:

```
(function ($, drupalSettings) {
    Drupal.behaviors.stripe = {
      attach: function (context) {
        alert('hello4');
        console.log(drupalSettings.api_key);
      }
    };
})(jQuery, drupalSettings);

```

If you're still having trouble, try just adding a couple of lines to be sure things are sane:

```
(function ($, drupalSettings) {

    // What's going on?
    console.log('function is loading!');
    console.log(drupalSettings);

    Drupal.behaviors.stripe = {
      attach: function (context) {
        alert('hello4');
        console.log(drupalSettings.api_key);
      }
    };
})(jQuery, drupalSettings);

```
> 7 votes

# Answer
First, add the name of your module as an array item to drupalSettings in your form class so it is like \['drupalSettings'\]\['mymodule'\]\['api\_key'\].

Second, it needs to be passed into your function:

```
(function($, Drupal, drupalSettings) {
...
})(jQuery, Drupal, drupalSettings);

```
> 1 votes

---
Tags: javascript, 8
---


# Question
Title: JavaScript loading but not being applied in Drupal 8 theme
I'm using this javascript to create a 'zaccordion' on my Drupal 8 site. However, it's not working. My 'slideshow' just appears as a bulleted list of images.

Here's what I've got so far:

A block on my page with the following content:

```
<ul id="slideshow">
<li>image</li>
<li>image</li>
</ul>

```

I've also got the required javascript files from the download link (above) in themename/js. I've also got my own instantiation of the zaccordion in another js file in that same folder and it targets #slideshow like so:

```
(function ($) {
  $(document).ready(function() {
    $("#slideshow").zAccordion({
      settings here
    });
  });
})(jQuery);

```

Then, in my libraries.yml file I have this:

```
zaccordion:
  header: true
  version: 1.x
  js:
    js/jquery.zaccordion.min.js: { }
    js/jquery.zaccordion.js: { }
    js/zaccordionUsage.js: { }
  dependencies:
    - core/jquery

```

I put that in the 'header' because it wasn't working in the footer. I can confirm the files are being pulled into the page because I see links to the scripts in the `<head>` of the html.

Finally, I have the javascript library being placed into the page with this call near the top of page--front.html.twig:

```
{{ attach_library('themename/zaccordion') }}

```

Are all these settings correct?

I have this same slideshow functionality working easily on a Jekyll site I created so I assume it's something to do with the way my block is trying to reference the javascript files or something.

*Note: yes, I have JavaScript aggregation unchecked (Performance \> Aggregate Javascript)*

# Answer
The dumbest of all possible mistakes was the answer. I had a `<div>` wrapping my insertion of the page block, like so:

```
{% if page.slideshow %}
{{ attach_library('themename/zaccordion') }}
    <div class="col-xs-12" id="slideshow">
        {{ page.slideshow }}
    </div>
{% endif %}

```

I thought if I put the `attach_library` line there it would load it 'closer' to the actual code needing it (don't try to understand what I was thinking). At any rate, I noticed that I have an `id="slideshow"` here as well. So I had TWO `id="slideshow"` \- one on this `<div>` and another on the `<ul>` in the block...that was causing the slideshow not to work. So I just changed the id of this `<div>` to something else and it worked.
> 2 votes

---
Tags: 8, javascript
---


# Question
Title: How to use FilterProcessResult::createPlaceholder (#lazy_builder) in an input filter?
The FilterProcessResult::createPlaceholder method suggests that I can set a PHP callable that will allow me to return a render array. However my callable is not being called when visiting a node using Drupal 8.0.x.

I do not see any error messages in watchdog or in the PHP log.

What should I be doing in order to get FilterProcessResult::createPlaceholder() to call my callable?

### Code

```
  public function process($text, $langcode) {
    $matches = [];
    $result = new FilterProcessResult($text);

    $count = preg_match_all('/\[processing\](?P<code>.*)\[\/processing\]/is', $text, $matches);

    if ($count) {
      $i = 0;
      foreach ($matches['code'] as $i => $code) {
        $args = [$code, $this->settings['render_mode']];
        $markup = $result->createPlaceholder('\Drupal\processing\Plugin\Filter\FilterProcessing::build', $args);
        $text = preg_replace('/\[processing\](?P<code>.*)\[\/processing\]/is', $markup, $text);
      }
      $result
        ->setProcessedText($text)
        ->setAttachments(['library' => ['processing/drupalprocessing']])
        ->setCacheTags(['processing']);
    }

        return $result;
      }

  static public function build($script, $mode) {
    $id = uniqid('processing-');
    $canvas_classes = ['processing-js-canvas', 'processing__canvas'];
    $render = [
      '#type' => 'container',
      '#attributes' => [
        'class' => ['processing-wrapper']
      ],
      'canvas' => [
        '#theme' => 'processing_display',
        '#rendermode' => $mode,
        '#unique' => $id,
        '#code' => $script,
        '#attributes' => [
          'class' => $canvas_classes,
          'id' => $id,
        ],
        '#attached' => [
          'drupalSettings' => [
            'processing' => [
              'drupal.processing' => [
                'elementId' => $id,
                'renderMode' => $mode,
              ]
            ]
          ]
        ],
      ],
    ];
    return $render;
  }

```

See commit 9d84e9477515bce1b7dd15f9724da1c6c0bd0fc2

### HTML Output

```
<drupal-filter-placeholder callback="\Drupal\processing\Plugin\Filter\FilterProcessing::build" arguments="0=%0A%20%20%20%20%20%20%20%20size%28200%2C%20200%29%3B%0A%20%20%20%20%20%20%20%20background%28200%29%3B%0A%20%20%20%20%20%20&1=source" token="bd5dbeba"></drupal-filter-placeholder>

```

I am running a settings.local.php with cache disabled on a local VM, but I got the same result without it.

# Answer
After several months, I looked at the code again and found the issue. The `createPlaceholder` method calls `addAttachments`, but then I call `setAttachments`, which removes the previous attachment.

I should always use `addAttachments` as that will *merge* instead of *overwrite*.

```
foreach ($matches['code'] as $i => $code) {
  $args = [$code, $this->settings['render_mode']];
  $markup = $result->createPlaceholder('\Drupal\processing\Plugin\Filter\FilterProcessing::build', $args);
  $text = preg_replace('/\[processing\](?P<code>.*)\[\/processing\]/is', $markup, $text);
}
$result
  ->setProcessedText($text)
  ->addAttachments(['library' => ['processing/drupalprocessing']])
  ->setCacheTags(['processing']);

```
> 1 votes

---
Tags: 8, input-formats, theming
---


# Question
Title: How to print the search results after form_submit, in a custom search module?
I am creating a custom search block, I have created a form in the block. Here is my form\_submit. I need to print a html table of some of the fields in the $result array. I am using Drupal\_set\_message(), I need to show the results in a table instead, so that user can print the page

```
$text = $form_state['values']['text'];
$query = db_select('table_1', 'n');
$query->fields('n', array('id'));
 $query->fields('n', array('phone'));
$query->fields('n', array('name'));
$query->condition('n.p_id', $text, '=');
$column_name = $query->execute();

```

# Answer
> 0 votes
I used an if statement in the form to check if submit is pressed and gave the results in the if block.

```
function hook_form($form, &$form_state) {
if (!empty($form_state['values']['text'])) {//here i am checking if the text field is empty
    $header=array('one'=>t('one'),'two'=>t('two'));//your header
 $query=db_query();//query
$column_name = $query->execute()->fetchAssoc();//fetchAssoc to get results in an associative array.
//here get the fields from $column name into rows
$row = array(
    array(
    'one'=>$column_name[""],
    'two' => $column_name[""],
    );
//your form elements after submit is pressed.
 $form['table']=array(
 '#theme'=>'table',
 '#header'=>$header,
 '#rows'=>$row,
 );

}
else {
//your original form here.
 $form['text'] = array(
'#type' => 'textfield'
 );
$form['buttons']['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit Button'),

);
  }
 return $form;
}

```

in you form submit add this

```
$form_state['rebuild']=true;

```

---
Tags: forms, database, blocks, search
---


title: How to show all autocomplete results ?

text:
# Question
Title: How to show all autocomplete results ?
I have a node reference field and the auto-complete widget. Right now, It only returns/suggests 10 nodes maximum.

How can i increase the number of nodes suggested by the auto-complete? (Or) better yet make it return **all** the suggestions?

# Answer
You need to create a custom module and also you need a .info file change 20 to the number you want

```
function custom_tweaks_menu_alter(&$menu) {
  if (isset($menu['nodereference/autocomplete'])) {
    $menu['nodereference/autocomplete']['page callback'] = 'custom_tweaks_nodereference_autocomplete';
  }
}

function custom_tweaks_nodereference_autocomplete($field_name, $string = '') {
  $fields = content_fields();
  $field = $fields[$field_name];
  $match = isset($field['widget']['autocomplete_match']) ? $field['widget']['autocomplete_match'] : 'contains';
  $matches = array();

  $references = _nodereference_potential_references($field, $string, $match, array(), 20);
  foreach ($references as $id => $row) {
    // Add a class wrapper for a few required CSS overrides.
    $matches[$row['title'] ." [nid:$id]"] = '<div class="reference-autocomplete">'. $row['rendered'] . '</div>';
  }
  drupal_json($matches);
}

```

Taken from this source
> 1 votes

# Answer
Apply this patch: https://www.drupal.org/node/2185019#comment-11573163 for EntityReference with autocomplete widget.
> 0 votes

---
Tags: 7, nodes, ajax
---


title: How do I disable a form?

text:
# Question
Title: How do I disable a form?
I want to disable a form in Drupal 8.

In D7 you could've done it in an alter hook like this.

```
$form['form'] = ['#value' => 'the form you are looking for is gone!']

```

What can I do in Drupal 8?

What I tried so far:

```
function hook_form_FORM_ID_alter () {
  $form[] = []; // $form[] or $form both will not work.
  $form['dunnoWhatToWriteHere'] = [
    '#type' => 'markup',
    '#markup' => t('The form is gone),
  ];
}

```

What I suggested is that I would overwrite the $form array with an blank one but as I run my xdebug drupal seems to just ignore it because the $form array in its native status exists although I tried to overwrite it with a blank one.

Do I also have to call a Formbuilder?

```
 $form = [];
 $form['error'] = [
   '#type' => 'html_tag',
   '#tag' => 'p',
   '#value' => t('The form is gone'),
 ];

```

That one worked for me :)

# Answer
> What I suggested is that I would overwrite the $form array with an blank one but as I run my xdebug drupal seems to just ignore it because the $form array in its native status exists although I tried to overwrite it with a blank one.

What you describe does look like caching. Drupal returns what is cached, without running the code to build the form again.

You don't give much information, but you did tell in the comments, the form is part of a rendered page. If the form would be a page on it's own, then this is about access. If you only want control if a part of the page is displayed, then this is about blocks. The first thing to try is to configure the visibility of the form block. If you can't configure it in ui, then there are several ways to put custom code in block or page level to remove the block. This depends when and where the block should be displayed.
> 2 votes

---
Tags: forms, 8
---