title: LEFT JOIN issues

text:
# Question
Title: LEFT JOIN issues
I have a views to display a list of company nodes. The company content type has one boolean field 'field\_company\_exclude\_jobs\_home'. This field is to indicate whether this company should be excluded from this views list.

If this field has been checked, then the company should be removed from result. The easy way is to add a filter for this boolean field in views. The thing is by default this field doesn't have value. So the configuration from views filter is not a good solution.

The raw views sql look like this.

```
        SELECT node_field_data.nid AS nid, RAND() AS random_field
        FROM
        {node_field_data} node_field_data
        LEFT JOIN {node__field_company_exclude_jobs_home} node__field_company_exclude_jobs_home ON node_field_data.nid = node__field_company_exclude_jobs_home.entity_id AND (node__field_company_exclude_jobs_home.deleted = '0' AND node__field_company_exclude_jobs_home.langcode = node_field_data.langcode)
        WHERE (( (node_field_data.status = '1') AND (node_field_data.type IN  ('company')) AND (node__field_company_exclude_jobs_home.field_company_exclude_jobs_home_value <> '1') ))
        ORDER BY random_field ASC

```

What I need is when company doesn't have a row record at table node\__field\_company\_exclude\_jobs\_home, this company should also returned.

Is this something possible to be done at views sql query alter level? Btw, this can be done at views\_pre\_render() level to exclude companies already. I'm just curious is this possible for a sql query level.

# Answer
> 0 votes
There's something my colleague has figured out to make this work in a query level.

Add two filters in view ui.

```
WHERE (( (node_field_data.status = '1') AND (node_field_data.type IN  ('company')) AND (node__field_company_exclude_jobs_home.field_company_exclude_jobs_home_value <> '1' or node__field_company_exclude_jobs_home.field_company_exclude_jobs_home_value is '') ))

```

Views ui doesn't have option for filter to allow NULL value. So the second condition "is ''" is made through views\_query\_alter() level.

```
$query->where[2]['conditions'][1]['value'] = NULL;
$query->where[2]['conditions'][1]['operator'] = 'IS';

```

---
Tags: views
---


title: Add uid to existing menu link

text:
# Question
Title: Add uid to existing menu link
I have a custom menu MyMenu and I have four menu items. What I want to do is to add the current uid as a parameter at the end of the link.

In D7 I could use menu\_tokens module which is not available on D8.

I tried to create a routing file in my custom module.

So in my routing file MY\_MODULE.routing.yml I added :

```
MY_MODYLE.my_applications_redirect:
  path: '/my-applications'
  defaults:
_controller: '\Drupal\MY_MODULE\Controller\MyApplicationController::redirect_to_my_applications'

```

And in MyApplicationController.php :

```
namespace Drupal\MY_MODULE\Controller;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\RedirectResponse;

/**
 * A controller that redirects to the my applications page.
 */
 class MyApplicationController extends ControllerBase {

  /**
   * {@inheritdoc}
   */
  public function redirect_to_my_applications() {

    global $base_url;
    $user = \Drupal::currentUser();
    $path = '/my-applications/'. $user->id();

    $response = new RedirectResponse($base_url . $path);
    $response->send();
  }

}

```

Also in the menu I have set the path to /my-applications.

Do I miss something?

PS. The "my-applications" page is a panel page.

# Answer
> 0 votes
As i can see from the menu token that the module has a pre-released version for drupal 8 as development release, so maybe you could try it out or at least search in its code to find a way to accomplish your needs.

I have recently built a drupal 7 website and i have used the menu token to create a hover over drop down usermenu with username and profile picture.

See image below (i drawed in black on top of it because the site in not yet online)

If you like, i can right back small tutorial on how i achieved that !

---
Tags: 8, redirection, navigation
---


# Question
Title: I need help grouping links under one title
So this is how my webpage looks at the moment.

However, I need to group each of these links under a certain title. The titles are the following (bolded):

How do I get each of those links, for ex "Bon Appetit", "Brubakers" to be under the title "Eateries" and so on. How do I create the Group titles? I just want to know how to get started on it. Do I have to do some coding? (I have no experience on this, by the way.)

# Answer
I'm assuming that each of these items are nodes, that have a field referring to the group they're a part of. In your view settings, look for 'FORMAT'. I'm guessing you're using an unformatted list. If you click 'Settings' next to that you should see a 'Grouping Field Nr.1' dropdown box. There you can choose what field to group all the items by and it will automatically group your results with the group title at the top. You have to make sure that you have the group field listed in fields section first.
> 0 votes

# Answer
1) You can use views accordion

From the module page:

> Views Accordion provides a display style plugin for the Views module. It will take the results and display them as a JQuery accordion, using the first field as the header for the accordion rows.

After installing the module, create a view with format style: **accordion** and adjust its settings.

2) You can do it without extra module by going to your view and under the **format settings** link, you will find selectbox field called: **Grouping field Nbr.1**

Note that the views format should be ***Unformatted list***
> 0 votes

---
Tags: views, blocks
---


# Question
Title: How can I export a multistep webform from an environment to another one?
How can I export a multistep webform from an environment to another one in Drupal 8?

# Answer
> 0 votes
Webforms are configuration and you can use the tools D8 provides for this.

Additional to that webform has a unique feature. The form arrays are stored in the yaml format and you can simply copy and paste this from one environment to another.

---
Tags: 8, webforms, importing-exporting
---


# Question
Title: Implement a product discount based on a dynamic value
I am new to Drupal CMS and i would like to add a "discount field" on my product so when i am adding/updating a product, i can set an "integer value" inside this "discount field" and so the "product price" will be discounted based on the "value" of this field.

Example:

I want to create a product "A" with original price of "120$", now while adding this product to my store, i want to add the value of "20" inside the "discount field" and so the price will be displayed for users as: (120$ x 20%) = 96$

Thank you,

# Answer
> 0 votes
I had similar question a while ago... this involve creation of 4 separate discount Rules via Commerce Discount UI and then modifying each created discount rule via Rules UI.

Have a look to this answer here: Dynamic Discount using taxonomy term reference field to define specific discount value

Post back if you need any help,

---
Tags: 7, entities, commerce, rules
---


# Question
Title: I don't understand module_load_include()
I believe it is meant to be used as follows, in loading a module include file into the calling scope:

```
function mymodule1_myfunction1(){
    ...
    module_load_include($type, $module, $name);
    ...
}

```

But looking at the code of `module_load_include()`:

```
function module_load_include($type, $module, $name = NULL) {
  static $files = array();

  if (!isset($name)) {
    $name = $module;
  }

  $key = $type . ':' . $module . ':' . $name;
  if (isset($files[$key])) {
    return $files[$key];
  }

  if (function_exists('drupal_get_path')) {
    $file = DRUPAL_ROOT . '/' . drupal_get_path('module', $module) . "/$name.$type";
    if (is_file($file)) {
      require_once $file;
      $files[$key] = $file;
      return $file;
    }
    else {
      $files[$key] = FALSE;
    }
  }
  return FALSE;
}

```

We see that

`require_once $file`

is used to load `$file` into the scope of `module_load_include()`, not `mymodule1_myfunction1()` so `$file` is not available to `mymodule1_myfunction1()`. Is this not how `module_load_include()` is meant to be used?

# Answer
> 3 votes
> We see that `require_once $file` is used to load $file into the scope of module\_load\_include()

Not quite. This is from the `include` docs (identical to `require` in this respect)

> When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, **all functions and classes defined in the included file have the global scope**.

Emphasis mine.

So functions/classes defined in an a file sourced with include/require will be available to all subsequent code. Or more specifically, all functions/class defined in the file you include via `module_load_include` will be available in `mymodule1_myfunction1()` after the call.

---
Tags: 7
---


title: Which Commerce module to use?

text:
# Question
Title: Which Commerce module to use?
I'm creating a website that only has one product (credits to enable them to contact matching users), but want users to be able to buy multiple credits if desired and to be able to track how many have been used. I don't need to use Kickstart as I don't need a storefront. Is there a way to set this up in Commerce or can someone point me to a tutorial that just has a simple setup?

# Answer
Commerce has reported installs: 65,052, Ubercart has reported installs: 37,622, commerce is best updated and there are more sub-modules avilable . On both, simple payment method is not so easy, everything is editable: amount, price, whatever. My humble advise is go with commerce.
> 1 votes

---
Tags: commerce
---


# Question
Title: Setting site name in installation profile
I'm creating an installation profile. Currently, `hook_install()` contains only this:

```
/**
 * Implements hook_install().
 */
function myprofile_install() {
  \Drupal::service('config.factory')->getEditable('system.site')->set('name', 'My Site')->save();
}

```

Still, after installation is completed (using Drush) the site name is always "Drupal".

The code works if I paste it into Devel's *Execute PHP* after the site is installed.

Another option I tried is overriding system.site.yml within my profile, which won't load because I wrote `uuid: ''`. (I don't know how to leave the already-generated UUID.)

How can I set the site name during installation in my custom profile?

---

**EDIT**: I found out the following:

* The site name gets overwritten when the install configuration form is submitted by Drush, using the values provided by Drush (including site name)
* The installation profile must provide a translation of the site information for each enabled language (I have more than one). I assume I'll do this with the core module Configuration Translate.

# Answer
> 1 votes
The solution was to use `hook_install_tasks`.

The source of the issue was that Drush was filling in the install configuration form during the installation process. Because the form comes after the profile's `hook_install`, it will override whatever configuration we write in `hook_install`.

Using `hook_install_tasks` will work by defining a new install task for setting our preferred configuration, which Drupal will run **after** submitting the configuration form. See function `install_tasks()` in `core/includes/install.core.inc`, line 716.

---
Tags: installation-profiles
---


# Question
Title: How do I print logic field on page--node.html.twig?
This code printing 0 or 1

```
{{ node.field_some_logic.value }}

```

I want he print NO or YES.

Somobody know, how to do this?

# Answer
> 1 votes
With simple logic, you could try using

```
{{ node.field_some_logic.value ? 'YES' : 'NO' }}

```

See **ternary operator** on https://twig.sensiolabs.org/doc/2.x/templates.html

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


# Question
Title: How to Clone a production site locally for testing?
Ok so I am kinda new to drupal (I've only been working with it for a few months at work) and I just got my first freelance client who has a drupal site that he wants to modify its layout.

I am now stuck at trying to **duplicate the website and set it up on my machine** and I don't want to do changes to the production environment directly. Here's what I did so far:

1. I got access to the webhost server and downloaded the site's drupal root directory
2. I exported the site's database and stored it on my machine
3. Used Acquia Dev Desktop 2 to import a local site -\> chose the downloaded drupal site root -\> selected the sq database dump file that I exported earlier

When I try to open the site on my local server it runs the drupal installation but when I choose a profile and press "Save and continue" it shows me the following message:

> "Drupal already installed. To start over, you must empty your existing database. To install to a different database, edit the appropriate settings.php file in the sites folder."

Now I know that drupal is already installed probably because I cloned the website codebase and database exactly as they are from the webhost server, and I did not change any of the settings.php files. How exactly do I run the website l locally through Acquia Dev Desktop and then push my changes to the host?

Any tips, best practices comments, and advice is highly appreciated!

# Answer
> 0 votes
Most probably the problem is in your settings.php, what you can do:

1. Open your settings.php files and search for the folowing code:

$databases = array 'default' =\> array ( 'default' =\> array ( 'database' =\> 'your-db-name', 'username' =\> 'your-db-user', 'password' =\> 'your-db-user-password', 'host' =\> 'localhost', 'port' =\> '', 'driver' =\> 'mysql', 'prefix' =\> '', ), ),
);
2. If you are not sure if you have the correct code for your database, please post your code back in here and i will take a look on it
3. Last thing, if all you need is making changes to your website using a test website and then push all changes back to the production website, my suggestion is to create a subdomain on your webshost (Ex: dev.yourdomainname.com) and completely clone your entire website from **dev.yourdomainname.com** so you can work on your dev website without touching your production one.

I can help you with that also but first tell me what your need and answer the following:

_ You have access to Drush console ? _ You have access to the webhost server ?

waiting your response...

**Update # 1: Clone your production website for testing purposes on your webhost**

1) Create a subdomain for your domain name (ex: dev.yourdomain.com)

2) From your cpanel, create a new empty database (don't forget to prefix your db name at end by **\_test** to distinguish it from the original one) (Ex: db\_name**\_test**)

**write down the name of the database**

3) create a new user for your test database and also (don't forget to prefix your user name at end by **\_test** to distinguish it from the original one)

**Write down the name of the user & password**

4) Grant the test user all privileges for the new database.

5) goto your production site and do the following manually or by using the drush command:

* Clear all caches. **(drush cc all)**
* Disable clean URLs. (/admin/config/search/clean-urls)**(drush vset clean\_url 0 --yes)**
* Disable cron job. (/admin/config/system/cron)
* Put site in maintenance mode. **(drush vset maintenance\_mode 1 --yes)**

6) Copy the entire site's drupal root directory to the new test website root directory and make sure the settings.php file is copied as well.

**Manually:** Click on the site root directory and choose copy and type the destination path.

**drush command:**

cp -rp /home/cpanel-user/public\_html/your-**original**-site-root-directory /home/cpanel-user/public\_html/your-**dev**-site-root-directory

7) **Goto** your phpMyAdmin, **Select** your original database, **Choose** operations, under the **copy database to** section, **write down** your test database name as it is, make sure the **structure and data** is selected, and **uncheck** create database before copying, **leave** everything else as it is, click **Go** and **wait for the confirmation message.**

8) Make sure the permission given to the deb-site root directory is: **0755**

9) navigate to your new test website directory, edit settings.php and edit the database settings to fit the **new database name**, **new database user** & **new user password**

10) open new tab browser and navigate to: **dev.yourdomain.com**

11) Voila, all should be good.

12) goto your dev site and do the following manually or by using the drush command:

* Clear all caches. **(drush cc all)**
* Enable clean URLs. (/admin/config/search/clean-urls)**(drush vset clean\_url 1 --yes)**
* Enable cron job. (/admin/config/system/cron)
* Don't remove the site from the maintenance mode since it is a test website.

Note, you can do the exact steps above to have a copy of your website locally, but i will just stick with this method since it is more reliable. easier and faster.

**If you insist of cloning your website locally to acquia dev desktop:**

1) Get a fresh copy of your prod-site database and file, manually or using drush

drush ard --destination=/home/cpanel-user/create-a-directory-for-backup/choose-a-name.tar.gz

The above command using drush 7, will get you a copy of your database and your files/folders.

2) Download the archive backup folder to your desktop and unzip.

3) Goto Acquia dev desktop, click on **+** and **import local drupal site**

4) Choose the local codebase folder from the unzipped folder you just downloaded.

5) choose a local site.

6) leave the create a new database and give it a new name of your choice.

7) when finish importing, visit your website and complete a new fresh installation from your website.

8) when all go good and you will have a fresh new Drupal website up and running, goto your local database (phpMyAdmin), click on **Structure**, **Scroll down** to the button, **Check all** tables, **with selected** choose drop, **make sure** there is no any left tables in the database.

9) Goto **import**, select you **.sql** database, leave everything as it is, click **Go**

10) no need to change anything inside the settings.php, just visit your site and voila.

# Answer
> 0 votes
As you have access to the webhost and downloaded the files and db, follow these steps for Acquia Desktop:

Open the db and empty all the cache\_\* tables. 2. Rename settings.php to something else, eg settings.php\_prod 3. Move the sites filesystem to Acquia Desktop appropriate directory 4. Open Acquia Desktop and press + -\> Import Local Drupal Site 5. Select the filesystem and in the database field select Import an sql dump file 6. Select your downloaded db and leave it import it.

You will find out that Acquia Desktop creates a folder with dd suffix which is a shortcut to sites/default. Change paths to uploaded files to sites/default.

When you are done, empty cache tables again, delete Acquia Desktop settings.php (which is different from the production) and rename back settings.php\_prod to settings.php.

Upload everything to the webhost and you are done.

---
Tags: database, configuration, acquia-dev-desktop
---


# Question
Title: migrating from localhost to server - What to do with the folder sites/localhost.mysitename?
I am trying to migrate my site from acquia dev desktop (local host server) to bluehost. In my site on my computer I have inside the "sites" folder, 3 folders:

* all
* default
* **localhost.mysitename**

Inside **localhost.mysitename** I have the "**files**" folder, and inside that I have the following folders: adaptive theme, banner, color, ctools, custom\_search, custom\_search, feeds, pictures, styles, styles. in addition I have the ".htaccess" file and many pictures and logos of the site.

Should I change the folder name of "localhost.mysitename" to only "mysitename"?
Should I change it at all or to other name?

# Answer
I don't know the acquia product you are using. And I don't know bluehost - but it seems to be a "usual webhoster". I assume at bluehost is an ordinary LAMP stack running without any drupal-specific modifications.

*update 2 after comments of EB84:*

It turns out you are not using multi-sites. Seems to me as you made your setup more difficult than it needs to be:

Just replace the default folder with your localhost.mysitename folder. By doing so you revert your folder-structure back to a simple single-site setup.

Keep in mind, that you need to adopt your settings.php to the preferences of your bluehost webspace (database parameters, etc.). Your settings.php will look different on the server than on your local machine - all other files and directories may be the same.

*update 1 after comment of EB84:*

Since you are using a multi-site setup the configuration in `sites/sites.php` will control which site will be used for what domain names in HTTP requests.

Please read following documents:

You will read that the directory names are arbitrary - as long as you map the domain name of the HTTP requests to it (via the configuration in sites.php).

Anyhow it might be good to remove the term "localhost" from your directory name - not for the whole thing to run technically, but to not confuse yourself some when in future.
> 1 votes

# Answer
I have been using acquia dev desktop for a long time now, and the folder you are speaking about is basically nothing and you can delete it.

I you compare this folder to the default folder, you will notice that they are identical in contents.

This what i usually do to all of my websites, and is working as expected !
> 0 votes

---
Tags: acquia-dev-desktop
---


# Question
Title: How do I render a custom form in page--front.tpl.php?
I have a custom form with a button.

```
function mymodule_get_subscribed_form($form, $form_state) {
    $form['actions']['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
    );
    return $form;
}

```

Now I want render this button on the front page. I've wrote this code in page--front.tpl.php.

```
print render(drupal_get_form('mymodule_get_subscribed_form'));

```

It doesn't work with Drupal 7.54, even after clearing the cache.

# Answer
> 0 votes
It might be because of variables being passed by reference. Try this instead:

```
$form = drupal_get_form('mymodule_get_subscribed_form');
print drupal_render($form);

```

# Answer
> 0 votes
I added

```
'mymodule_get_subscribed_form' => array(
      'render element' => 'form',
      'file' => 'mymodule.pages.inc',
),

```

to mymodule\_theme hook and now it works.

---
Tags: theming, forms
---


# Question
Title: How to add an element into a nested array in twig?
I've decided to include opportunities of the bootstrap library in drupal native forum and I'm trying to add new class into a nested array in twig. Here is my code.

```
{%  set topics['#rows'][0][0]['class'] = topics['#rows'][0][0]['class']|merge(['col-xs-9', 'col-sm-6']) %}
{%  set topics['#rows'][0][1]['class'] = topics['#rows'][0][1]['class']|merge(['col-xs-3', 'col-sm-2']) %}
{%  set topics['#rows'][0][2]['class'] = topics['#rows'][0][2]['class']|merge(['hidden-xs', 'col-sm-4']) %}

```

But upon executing the page an error is being displayed. Here is description of the error.

```
Twig_Error_Syntax: Unexpected token "punctuation" of value "[" ("end of statement block" expected). в Twig_TokenStream->expect()

```

Could you clarify me, how to properly add new elements into the compound array ?

# Answer
I managed to solve the problem via hook\_preprocess. Here's the code

```

function mytheme_preprocess_table__forum_topic_list(&$vars){
    $vars['header'][0]['attributes']->addClass(['col-xs-9', 'col-sm-6']);
    $vars['header'][1]['attributes']->addClass(['col-xs-3', 'col-sm-2']);
    $vars['header'][2]['attributes']->addClass(['hidden-xs', 'col-sm-4']);

    $vars['rows'][0]['cells'][0]['attributes']->addClass(['col-xs-9', 'col-sm-6']);
    $vars['rows'][0]['cells'][1]['attributes']->addClass(['col-xs-3', 'col-sm-2']);
    $vars['rows'][0]['cells'][2]['attributes']->addClass(['hidden-xs', 'col-sm-4']);
}

```
> 0 votes

---
Tags: theming, 8
---


title: Skip Payment Step from Checkout process

text:
# Question
Title: Skip Payment Step from Checkout process
I have setup a Drupal Commerce website (using Drupal 7) with two shipping options:

1. Delivery by courier company
2. Pickup from store

The next step in checkout process is to choose the payment method. BUT... if the second choice (pickup from store) is chosen, the only available payment method is **Pay at store** (offline payment). I have managed to show only this option through Rules. So far so good.

My concern is that for **better user experience** I have to make this step skipped. So after the Shipping step where the user selects the Pickup from store option, the next logical step is the *Review* pane for a final review by the user before complete the checkout process.

I have read that the Payment selection method (checkout step) is required for the Payment Redirection (I fail to understand it).

I have already tried to use hook\_commerce\_checkout\_router, checking the $order shipping line and use the drupal\_goto function redirect to the review page. My custom function is the following:

```
function <myModule>_commerce_checkout_router($order, $checkout_page) {
  global $user;

  if ($checkout_page['page_id']=='checkout') {
    if (!empty($order->commerce_order_total['und']['0']['data']['components']['2']) && ($order->commerce_order_total['und']['0']['data']['components']['2']['name']=='flat_rate_from_store')) {
      drupal_goto('checkout/' . $order->order_id . '/' . $checkout_page['next_page']);
    }
  }
}

```

I get error "*The page isn’t redirecting properly*". It is the same result as if someone is at the shipping step and manually tried to enter at the url the */review*.

Do you think is possible to achieve skipping this step to speed up the checkout process or I have to give up trying ? At year 2017 it is very important to give a user the best and the most logical way to move around in a website. Useless steps and clicks slow down the process and maybe end in frustration.

# Answer
> 2 votes
The problem is you're redirecting without also updating the order's status. The checkout router determines access to a checkout page by matching the order status to the URL, and it will prevent access to any page the order doesn't appear to have reached yet.

In your case, you should just use the same API function the Payment module uses when it needs to redirect past the off-site payment redirect page because an on-site payment method was used. The function is **commerce\_payment\_redirect\_pane\_next\_page()** and you can view the function signature and docs in commerce\_payment.module.

---
Tags: 7, commerce
---


# Question
Title: How do I check whether debug mode is enabled?
I enabled the Twig debug mode in the *development.services.yml* file. Is it possible to verify when the debug mode is enabled, using the `Twig_extension` class?

I need to check this in a Twig extension I created.

# Answer
> 2 votes
Passing a `Twig_Environment` object to the extension method, it's possible to use `Twig_Environment::isDebug()`, as in the following example code.

```
public function myfunction(\Twig_Environment $env, $string) {
  if ($env->isDebug()) {
    $string = 'foobar';
  }

  return $string;
}

```

Starting from Drupal 8.5.x, the `\Twig_Environment` class has been replaced from the `Environment` class. The previous code needs to be replaced by the following one.

```
// Put the following line on the top of the file containing this method.
use Twig\Environment;

public function myfunction(\Environment $env, $string) {
  if ($env->isDebug()) {
    $string = 'foobar';
  }

  return $string;
}

```

# Answer
> 1 votes
$twig\_debug\_on = \Drupal::service('twig')-\>isDebug();

---
Tags: 8
---


# Question
Title: How do I programmatically validate reCaptcha?
In Drupal 7, I use the Commerce\_Checkout\_Redirect module which uses custom validation functions. It uses the following code.

```
// Use the username as order email.
// Email validation for the username form element
if (variable_get('commerce_checkout_redirect_username_as_order_email', FALSE)) {
  $form['name']['#title'] = t('Email');
  $form['actions']['continue_button']['#limit_validation_errors'] = array(array('name'));
  $form['actions']['continue_button']['#validate'][] = 'commerce_checkout_redirect_username_as_order_email_form_validate';
}

```

The validation function is the following.

```
function commerce_checkout_redirect_username_as_order_email_form_validate($form, &$form_state) {...}

```

The form ID is *user\_login*, the reCaptcha is enabled for this form and it is shown, but it is ignored by the validation process when users submit the form.

How can I "force" the validation of the reCaptcha inside a custom validation function?

# Answer
> 0 votes
I figured out myself. The only thing i had to do is to add in *#limit\_validation\_errors* element another array with **captcha\_response**. So the right syntax is

```
$form['actions']['continue_button']['#limit_validation_errors'] = array(array('name'),array('captcha_response'));

```

---
Tags: captcha
---


# Question
Title: Module and functions goes missing intermittently
Looking for ideas as to why a custom module might "go missing" intermittently.

It has been put into production, serves thousands of page views and works well most of the time. Every now and then it just "seems" to go missing.

Symptoms are:

* Fieldable panels pane plugins (declared by the same module) can't make callbacks to functions within the module, getting "undefined function" errors.
* Template files which call functions from the module get the same errors above.
* The module declares a hook\_menu URL which starts returning 404s.
* Form callbacks functions in the module get "not found or invalid function name in drupal\_retrieve\_form()"

All of this is intermittent, runs fine for a week, or maybe a couple of hours, then it starts happening. I clear the caches, sometimes once or twice and it comes back to normal. There are no errors in the logs that I can see, nothing in watchdog that stands out.

How is it possible for a module and its functions to randomly go missing?

# Answer
I may have tracked this down to memcache, though it's such a strange error I can't be sure. Sometimes a group of nodes we put into cache was over the memcache 1mb default limit.

So instead of caching the nodes, I ran them through the theme layer first and reduced the required caching space by about 80%.

This didn't exhibit on my local host as I don't have memcache installed, rather relying on Drupals database caching. Running some queries like this helped identify the potential problem:

```
SELECT cid, LENGTH(data) AS Cache_Size FROM cache ORDER BY Cache_Size;

```
> 0 votes

---
Tags: 7
---


# Question
Title: Install.php not found after installing with Drustack
I'm highly experienced with Joomla, cPanel, and reasonably experienced with SSL/command-line. I know PHP and MySql enough to figure out how not to break code and do minor changes, and find stuff I need to remove/comment-out.

I installed DruStack 8.3.1 with `composer create-project`, and then `drush site-install` with `--db-url=mysql` info correctly done.
Both were done via SSL with the correct user (no root) and both went fine (no errors, etc). The database was filled.

The site is located at the root of a subdomain (not at a /dupal subfolder).

After those two steps, there is no index.php or .htacces at the root (which I expect for an installed site). Those are located into the /web folder, and I'm at a loss on what to do next.

When I try to access /install.php I get a 404.
If I try to access /web/install.php I'm directed to /web/core/install.php with a 500 internal server error.

I did a good search on install.php + 404 error, without any result that would help me.

Any help is much appreciated.

# Answer
Please see Usage page of `drustack-standard` project at GitHub:

> * **Drupal will be installed in the `web`-directory.**
> * Autoloader is implemented to use the generated composer autoloader in vendor/autoload.php, instead of the one provided by Drupal (web/vendor/autoload.php).
> * Modules (packages of type drupal-module) will be placed in web/modules/contrib/
> * Theme (packages of type drupal-theme) will be placed in web/themes/contrib/
> * Profiles (packages of type drupal-profile) will be placed in web/profiles/
> * Creates default writable versions of settings.php and services.yml.
> * Creates sites/default/files-directory.
> * Latest version of drush is installed locally for use at vendor/bin/drush.
> * Latest version of DrupalConsole is installed locally for use at vendor/bin/drupal.

Therefore setup your web server for DruStack if:

* You are running with Apache2, point your DocumentRoot to the `web` folder
* You are running with PHP internal web server, execute `php -S 127.0.0.1:8080 -t web`

Then access the `core/install.php` directly to kickstart the installation ;-)
> 1 votes

---
Tags: 8, drush, composer
---


# Question
Title: new product display content type not showing in products view
I've just started playing with drupal commerce which seems pretty good. I'm using Kickstart v2-rc1. I created a new product display type (content type with a product reference field). Everything seems to work, I can create a new node of this type and create/add variation. I can see my product under the correct category. However, when I use the product view (all product), my product doesn't appear in this list. What am I missing ? Is it an permission problem or the products view which is filtering my product ?

# Answer
I finally found the problem. The answer is probably obvious for a drupal expert but not for someone who just use drupal commerce out of the box.

Right, so the search facility (search box and 'all product' link ) use the search API which needs to be re-indexed when something changed.

For some reasons it wasn't. I'm expecting that adding a new product/entiry will triggered a reindexation but it doesn't. It seems also it could be done via the cron (but I haven't set any cron either, nobody told me to so). And, anyway, it seems the indexation was 'broken' (I changed one of the category name) so I add to recreate the indexes form scratch.

So the answer is , my searches need reindexation.
> 1 votes

# Answer
This has to do with the default backoffice view that is provided by Drupal Commerce. You can edit that view by going to http://yoururl.com/admin/structure/views/view/commerce\_backoffice\_products/edit

You can set the field filters in the view.
> 0 votes

# Answer
For me it helped to set the limit (Options list limit) to 10000 in the product reference field (/admin/structure/types/manage/product/fields/field\_product).

As the default (no limit) not seems to take affect. I only saw the first 10 products available.
> 0 votes

---
Tags: views, commerce
---


title: Block link with active class

text:
# Question
Title: Block link with active class
I've created couple of blocks from the Drupal UI.

These blocks has unsorted list with links to the other pages.

They act like a sub menus located into the sidebar region and visible to specific pages.

Here's an example for a block called fruits that have a couple of links:

* Apple
* Orange
* Mango

The Drupal menu system or Superfish module generates active class on the links based on the URL location. How can I do that with these blocks, so let's say a user clicks on the link Apple and when the new page loads, the Apple link will have a active class, so it will look like this:

```
<li><a href="/apple" class="active">Apple</a></li>

```

I want this, so I can set a CSS for active link.

# Answer
It needs to be done with PHP. If you use the `l()` function to generate your links, they will automatically get the active class if you are the page to which the link is linked to. To do this you would need to enable the PHP filter, but this filter is both recommended against, as well as non-existent in Drupal 8, so it would be better to create a block through code and use that instead of enabling the PHP filter.
> 1 votes

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


title: Add redirection in submission handler

text:
# Question
Title: Add redirection in submission handler
How can I redirect users to a node in a form submission handler similarly to the following code?

In my form alter I have added an additional submit button:

```
$form['actions']['save_and_exit'] = array(
    '#type' => 'submit',
    '#value' => t('Save & Exit'),
    '#submit' => array('custom_submit'),
  );

function custom_submit(&$form, \Drupal\Core\Form\FormStateInterface
  $form_state) {
    $system_path = '/node/2';
    $url = \Drupal::service('path.alias_manager')->getAliasByPath($system_path);
    $form_state->setRedirect($url);
}

```

Then I'm getting following error:

> Symfony\Component\Routing\Exception\RouteNotFoundException: Route "/mypage" does not exist. in Drupal\Core\Routing\RouteProvider-\>getRouteByName() (line 190 of C:\wamp\www\www\_assure\_local\_com\core\lib\Drupal\Core\Routing\RouteProvider.php).

where `/mypage` is the url alias of my `/node/2`.

# Answer
> 2 votes
A form submission handler never returns a `RedirectResponse` object to redirect users. (It actually doesn't return any value.)

A form submission handler calls `FormState::setRedirect()`, or `FormState::setRedirectUrl()` which accepts a `Url` object, for example the value returned from `Url::fromUri('//my_node_url_alias')`.

---
Tags: redirection
---


title: Errors with "LOAD DATA LOCAL INFILE"

text:
# Question
Title: Errors with "LOAD DATA LOCAL INFILE"
I am using `\Drupal::database()->query()` with the following SQL statement.

```
LOAD DATA LOCAL INFILE '{my file name}'
INTO TABLE {my table name}
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES
({my column names})

```

I have also tried with `db_query()` with same result. I can confirm the SQL statement works as expected in phpMyAdmin, so I don't think it's a problem with the SQL statement.

### First error

> Warning: PDOStatement::execute(): LOAD DATA LOCAL INFILE forbidden in Drupal\Core\Database\Statement-\>execute() (line 59 of {my directoreis}\core\lib\Drupal\Core\Database\Statement.php)

Line 59 is `$return = parent::execute($args);` which I believe is referring to PDOStatement.

### Second error

> Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE\[HY000\]: General error: 2014 Cannot execute queries while other unbuffered queries are active. Consider using PDOStatement::fetchAll(). Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL\_ATTR\_USE\_BUFFERED\_QUERY attribute.

Not sure if this can be set in a call to `\Drupal::database()->query();`

My research on this has shown me it should be possible to do in Drupal.

https://www.drupal.org/node/1034584

https://www.drupal.org/node/2110935

https://evolvingweb.ca/blog/import-hundreds-of-thousands-of-records-15-seconds-custom-entities

Database Abstraction Layer and 'LOAD DATA INFILE' Statements

https://stackoverflow.com/questions/3994133/how-to-load-data-to-db-from-csv-using-load-data-infile-in-drupal

So, where am I going wrong and how can I fix it?

**UPDATE**

Based on some of the pages I linked to above, I was able to come up with a working solution.

```
// set up an extra db connection
$connection = \Drupal::database()->getConnectionOptions();
$connection['pdo'][\PDO::MYSQL_ATTR_LOCAL_INFILE] = 1;
\Drupal\Core\Database\Database::addConnectionInfo('extra', 'default', $connection);
\Drupal\Core\Database\Database::setActiveConnection('extra');

// instantiate the extra db connection and query against it
$db = \Drupal\Core\Database\Database::getConnection();
$db->query($sql_statement)->execute();

// set connection back to default;
\Drupal\Core\Database\Database::setActiveConnection();

```

But for some reason I don't think this would be the "Drupal" way. And now, I am not sure what my question is. Maybe, is this the appropriate Drupal way or is there a more elegant built in solution I am unaware of?

# Answer
> 1 votes
> Maybe, is this the appropriate Drupal way or is there a more elegant built in solution I am unaware of?

Yes, that's an appropriate "Drupal" way.

The other way is to make it global, and add it to the database settings array in settings.php.

But you're essentially setting the same thing whichever way you do it. If you were to use your method, and then *remove* that option from the connection afterwards, it could arguably be considered more secure, since you're limiting the time and scope that `LOCAL INFILE` can be used in.

---
Tags: database
---


title: Multiple date fields

text:
# Question
Title: Multiple date fields
I have a customized Calendar view. When I created the view using the template, it allowed me to select one field to be used as the date. Is it possible to have multiple date fields, for example *Due date*, *Start date*, and *Review Date*? The node should show on the calendar for each date.

# Answer
I was able to accomplish this adding or statements to my calendar's existing contextual filter. I added each date field as an "or" statement and now it shows each date on the calendar.
> 0 votes

---
Tags: 7, views, datetime
---


# Question
Title: Trigger an event when file is upload on managed_file field
I'm trying to trigger an javascript function when a user select an image for a managed\_file field and click on the upload button, not the submit one.Except that in Drupal 7, managed\_filr field do not accept ajax argument, I don't have any idea on how to solve my problem. Thanks you in advance.

# Answer
> 0 votes
Finally I found a solution. I decide to use the '#upload\_validators' parameter on my form and to declare my own function:

```
'#upload_validators' => array(
  'myOwnFunction' => array(parameters)
),
.
.
.

function myOwnFunction(parameters){
do stuff();
}

```

---
Tags: 7, forms, javascript, ajax, files
---


title: Using drush migrate-import --update

text:
# Question
Title: Using drush migrate-import --update
I created a migrate script to import hundreds of records into a specific content type. A year after, I need to add another field to the content type and import values specific to each record. Because of changes made to some of the records over the past year, I cannot re-import the content from the csv file with the additional column. I am using config-edit to edit the migrate .yml file. Is there a way to rerun the migration to import content for the new field while ignoring all other fields that already have content.

I am using Drupal 8.

Thanks,

# Answer
> 1 votes
Try creating a new import \*.yml template(s) where - in the main

```
process:

```

section, include only the field that was recently added/changed. My (wild) guess is that the existing fields will be left intact.

# Answer
> 1 votes
I was able to make it work by doing a vigorous edit of the original migrate script, removing all the fields and their mappings, except for the key. Adding the new field, allowed me to rerun the migrate script and the new field was imported while leaving the other content intact. I am still able to use the rollback and other functions of the script.

---
Tags: 8, drush, migrations
---


title: Count everytime a node it shown in view

text:
# Question
Title: Count everytime a node it shown in view
I have a view that show content of a specific content type, based on some exposed filters.

Each node is "owned" by a user, and i want to provide statistics for how many times their node have been shown in a view (not hov many times the node have been viewed fully).

Then i want to provide the owner of the node with statistics like:

Views today, X Views last 7 days, X. Views last 30 days, X.

Any smart ideas?

# Answer
> 0 votes
there is a module for that node view count, from module page:

> Node View Count module allows to count node views. Unlike statistics module, this module records each view of node with user uid and timestamp. So now you can know how many times a user viewed node by day, week, month and etc.

This module is integrated with Views module. You can use it to create different statistics pages, output new not viewed nodes for user and many more.

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


title: Theme logo and site name

text:
# Question
Title: Theme logo and site name
how can I put **logo** and **site name** in an unordered list? I am using a bootstrap subtheme !

# Answer
For that, you're going to want a custom template file (.tpl.php in D7, .html.twig in D8).

In Drupal 8, the logo and site name are contained within Bootstrap's block--system-branding-block.html.twig; in Drupal 7, they're set in Bootstrap's page.tpl.php. If you go into that file, you can change how those elements are rendered - just wrap them in the necessary /

- tags and you'll be good to go!
> 2 votes

# Answer
Yes ! it worked ! thank you so much. Here is the modification I made. Thanks for pointing out about the position of ul

```
 `<header id="navbar" role="banner" class="<?php print $navbar_classes; ?>">
  <div class="<?php print $container_class; ?>">
    <div class="navbar-header">
     <?php if (!empty($logo) || !emtpy($site_name)): ?>
      <ul class="list-inline">
        <?php if ($logo): ?>
       <li> <a class="logo navbar-btn pull-right" href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>">
          <img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>" />
        </a></li>

      <?php endif; ?>

      <?php if (!empty($site_name)): ?>
        <li><a class="name navbar-brand pull-right" href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>"><?php print $site_name; ?></a></li>
      <?php endif; ?>

      <?php if (!empty($primary_nav) || !empty($secondary_nav) || !empty($page['navigation'])): ?>
        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar-collapse">
          <span class="sr-only"><?php print t('Toggle navigation'); ?></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>
      <?php endif; ?>
            </ul>
    <?php endif; ?>
    </div>`

```
> 0 votes

---
Tags: theming
---


title: 300000+ records user importing problem

text:
# Question
Title: 300000+ records user importing problem
I’m trying to imports data from vBulletin into Drupal using this dev module vbtodrupal But because the database is too large I experienced a difficult to import ALL data to drupal DB , I discovered that there is a specific limit to importing is 300k user ! I searched in google and found that there was a problem with "300000+ records user"

I hope to help . I did not find the response from the support module :(

# Answer
For an import of that size you will need to run the import in the background and in steps.

This will use cron to run the feeds cron job. Drupal uses a poor-mans cron so it would be best to setup a cron on the server or use a module like Elysia cron. If you do not not you could try something link https://www.pingdom.com (you can use a free account) to ping your site every e.g. minute to trigger the drupal corn.

I would also make sure that your server is optimal for Drupal 7 and just for the import consider increasing php memory limit and execution timeout value.

Nevertheless I would recommend using a more generic module like "Migrate", though it needs some more work to be done.

I personally imported 23K user profiles into Drupal a few months ago, so it is possible.
> 1 votes

---
Tags: database, importing-exporting
---


# Question
Title: how to insert a button in select to add new item in select item list?
I am using a select(combobox) to insert category of device as input. And in that combobox I wish to add a button at end of item list of categories to add new category. When user clicks that button there must be a text box appeared at end of list or modal like Ctools to add new category. Please help me to get this done thank you.

# Answer
> 0 votes
It seems like you are looking for the something similar to the select\_or\_other module. I believe your request is a "modern" implementation of this module, I've seen it on some sites. You might try to do some CSS/JS wizardry to make the Select or Other module fit your need.

---
Tags: 7
---


# Question
Title: When should I use DependencySerializationTrait?
I have noticed that some classes contain the following line:

```
use DependencySerializationTrait;

```

I know this trait is used for serialization, but I don't get when to use it and what kind of classes need to support serialization.

# Answer
> 9 votes
@kiamlaluno described the technical details. This is the background why the `DependencySerializationTrait` was introduced:

This was the situation before:

> * Any class that receives injected dependencies (whether by constructor injection or setter injection) typically keeps a reference to its dependencies in class members. That's how dependency injection works.
> * Drupal being Drupal, it serializes stuff in several places:
>     + Anything that is in a $form / $form\_state : the FormInterface object, but also any object whose methods are used by FAPI #callbacks ('#pre\_render' = array($some\_object, 'someSubmit')).
>     + Anything that gets cached, stored in state(), or more generally in the k/v stores...
> * When an object is serialized, all the objects it references get serialized as well, and recursively, all the dependencies of those objects...
> * This leads to a serialization chain of hell: \[#1909418\] hit a case where serializing the form controller meant serializing the EntityManager -\> the Container -\> (among many other things) the DrupalKernel. This got fixed by making sure the kernel was serializable - which is just insane :-).

And this was the proposed solution:

> The answer for "DIC-friendly serialization" seems to be:
>
> * On serialize, do not serialize dependencies.
> * On unserialize, re-pull them from the container. Granted, this breaks mocking, but serialization/unserialization is not something you typically do in unit tests, so I don't see this as a real problem.
>
> How to do this might not be too simple though. Two approaches come to mind:
>
> 1. Classes that want to be "DIC-friendly serialized" need to implement an unserialize() method that hardcodes the services ids of its dependencies. That means doing something similar to the create() factory method that is currently used at instantiation time in a couple places in core (controllers, some plugins). Hardcoding service ids in more and more classes is not a joyful perspective, though.
> 2. Crazy idea:
>     * Modify the DIC so that each time a service gets instantiated, the service id by which it got instantiated gets placed in a public \__serviceId (or something) property on the object.
>     * Classes that want to be "DIC-friendly serialized" do:
>     * On serialize() : foreach member, if (!empty($this-\>member-\>\__serviceId)) {just serialize the \__serviceId string instead of the whole object});
>     * On unserialize() : $this-\>member = \Drupal::service($service\_id)

Quoted from Injected dependencies and serialization hell

# Answer
> 4 votes
`DependencySerializationTrait` is used from classes that are serialized and that have services in their properties. For those classes, the trait replaces the service with its service ID, so that when an object of those classes is restored after being serialized, those service properties get a fresh object, as said in the code comment.

> If a class member was instantiated by the dependency injection container, only store its ID so it can be used to get a fresh object on unserialization.

For example, a class that just saves arrays in its properties would not have much use of that trait, especially if it's not going to be serialized.

If then the class stores the dependency injection container, the trait replaces it with the string *service\_container*.

---
Tags: 8, symfony-services
---


# Question
Title: How does the UserData plugin get the correct value?
The User module defines a `UserData` plugin for the Views module, which allows to access the user.data service from a view. Its `render()` method contains the following code.

```
$uid = $this->getValue($values);
$data = $this->userData->get($this->options['data_module'], $uid, $this->options['data_name']);

// Don't sanitize if no value was found.
if (isset($data)) {
  return $this->sanitizeValue($data);
}

```

}

How does the Views module know the plugin require a user ID? In other words, how does the Views module know that is a field plugin associated with the *User* entity and not another entity?

The annotation for the plugin is simply the following one.

```
@ViewsField("user_data")

```

Neither its `create()` nor its constructor method set something that would make clear to which entity the plugin is associated.

```
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
  return new static($configuration, $plugin_id, $plugin_definition, $container->get('user.data'), $container->get('module_handler'));
}

```

```
public function __construct(array $configuration, $plugin_id, $plugin_definition, UserDataInterface $user_data, ModuleHandlerInterface $module_handler) {
  parent::__construct($configuration, $plugin_id, $plugin_definition);

  $this->userData = $user_data;
  $this->moduleHandler = $module_handler;
}

```

# Answer
The available fields for the user entity are defined in Drupal\user\UserViewsData::getViewsData():

```
$data['users']['data'] = [
  'title' => $this->t('Data'),
  'help' => $this->t('Provides access to the user data service.'),
  'real field' => 'uid',
  'field' => [
    'id' => 'user_data',
  ],
];

```

This attaches the field `user_data` to the user entity.
> 1 votes

---
Tags: views, entities
---


# Question
Title: How do I use inline CSS in "Global: Custom text"?
My scenario:

* a field (color\_field) to enter a color code (ie: #fafafa)
* in **Global: Custom text in Views** use the token of color\_field to generate a border color (is: style="border-color: \[color\_field\]")

Then, I must display for each row a different border-color and the color code is generated with a color picker in color\_field when add a new node.

Unfortunately the inline CSS is stripped from Global: Custom text in Views.

How I can use inline css in Global: Custom text in Views?

Or have I to change approach to my scenario?

# Answer
I've solved overriding view-view-field--field-myfield.tpl.php and in template file I've used color from $row variable.

```
<?php
$title = $row->field_field_myfield[0]['rendered']['#markup'];
$color = $row->field_field_myfield_color[0]['rendered']['#markup'];
?>
<h3 style="border-color: <?php print $color ?>"><?php print $title ?></h3>

```
> 2 votes

---
Tags: views, theming, entities
---


# Question
Title: How to show view for submitted result of a webform by a user
How i can show all submitted value of a webform by a user in a view in a tab of a user profile section.

Iam using drupal 6.For example when user click on a tab say form on his profile the webform value submitted by that user show.

Thanks for your help.

# Answer
> 0 votes
I have done that in drupal 7 but not in drupal 6. In drupal 7, go to View.

1. Create a relationship "Webform Submissions: User" and require it
2. Create the contextual filter "User: uid"
3. Select the relationship which you created in step 2 and select "provide Default Value" under "When the value is NOT in the URL" and select "User ID from logged in User".

I hope this will help you out.

# Answer
> 0 votes
You can refer this link which is very usefull http://yalesites.yale.edu/book/creating-view-webform-data.

---
Tags: views, webforms, users
---


# Question
Title: Exclude from list view some articles based on their content type?
i’m listing in a view a list of article filtered with taxonomy terms.

The result is like this :

```
taxonomy term 1
- article A (content type 1)
- article B (content type 1)
- article C (content type 2)

taxonomy term 2
- article D (content type 1)
- article E (content type 1)
- article F (content type 2)

taxonomy term 3
- article G (content type 1)
- article H (content type 1)
- article I (content type 2)

```

How can i exclude from this list some articles based on their content type ? For example, remove "content type 2".

Also, i’ve created a view which contains article C, F, I. How can i add a specific view to this list ?

Here is my view settings :

Here is the result in front-end :

# Answer
> 3 votes
You can add this rule to Filter criteria section as on screen

# Answer
> 0 votes
You can add link to this views manually in footer. Go to footer section and add unfiltered text as on screen

This link will be in the bottom of list

# Answer
> 0 votes
Add new Link field in View like displayed in below image to add Link in view like "Read More".

Text it Like "Read More" so it will link to detail view of that article.

in Rewrite Results you can add link , class , text etc

---
Tags: views
---


title: create field group in hook_install()

text:
# Question
Title: create field group in hook_install()
I am using the field\_group module and want to programmatically create groups of fields in the hook\_install of my module.install file.

It seems that field\_group doesn't have much of an api that can be used by other modules. Does anyone know of a way that I can create a field group and assign field types to it programmatically?

# Answer
I ended up rolling my own function to do this (works for me, YMMV):

```
/**
 * Create a field group.
 *
 * The field_group module does not come with an API that can be used by other
 * modules. This method fakes a Drupal new group form submission to create the
 * new group.
 *
 * @param  array  $group
 */
function _field_group_create_group(array $group) {

  drupal_load('module', 'field_group');
  module_load_include('inc', 'field_group', 'field_group.field_ui');

  $defaults = array(
    'entity_type' => 'node',
    'mode' => 'form',
    'parent' => '',
    // TODO: default to heaviest weight
    'weight' => '',
    'format' => array('type' => 'fieldset'),
    'fields' => array()
  );

  $group = $group + $defaults;

  $form = array(
    '#entity_type' => $group['entity_type'],
    '#bundle' => $group['bundle'],
    '#view_mode' => $group['mode'],
    '#groups' => array()
  );

  $form_state = array(
    'values' =>  array(
      'fields' => array(
        '_add_new_group' => array(
          'group_name' => $group['group_name'],
          'label' => $group['label'],
          'parent' => $group['parent'],
          'parent_wrapper' => array('hidden_name' => '_add_new_group'),
          'weight' => $group['weight'],
          'format' => $group['format'],
        )
      )
    )
  );

  foreach ($group['fields'] as $field_name) {
    $form_state['values']['fields'][$field_name] = array(
      'parent' => '_add_new_group',
    );
  }

  field_group_field_overview_submit($form, $form_state);
}

```
> 1 votes

# Answer
The marked answer is correct here, but I can't comment on it. There's a couple "bugs" in it. The following changes were made to make it work with the object/array that gets exported when using `field_group_load_field_group()`

Specifically, I changed this line:

`'format' => array('type' => 'fieldset'),`

To:

`'format' => array('type' => $group['format_type']),`

And:

`foreach ($group['fields'] as $field_name) {`

To:

`foreach ($group['children'] as $field_name) {`

The final code:

```
/**
 * Create a field group.
 *
 * The field_group module does not come with an API that can be used by other
 * modules. This method fakes a Drupal new group form submission to create the
 * new group.
 *
 * @param  array  $group
 */
function _field_group_create_group(array $group) {

  drupal_load('module', 'field_group');
  module_load_include('inc', 'field_group', 'field_group.field_ui');

  $defaults = array(
    'entity_type' => 'node',
    'mode' => 'form',
    'parent' => '',
    // TODO: default to heaviest weight
    'weight' => '',
    'format' => array('type' => $group['format_type']),
    'fields' => array()
  );

  $group = $group + $defaults;

  $form = array(
    '#entity_type' => $group['entity_type'],
    '#bundle' => $group['bundle'],
    '#view_mode' => $group['mode'],
    '#groups' => array()
  );

  $form_state = array(
    'values' =>  array(
      'fields' => array(
        '_add_new_group' => array(
          'group_name' => $group['group_name'],
          'label' => $group['label'],
          'parent' => $group['parent'],
          'parent_wrapper' => array('hidden_name' => '_add_new_group'),
          'weight' => $group['weight'],
          'format' => $group['format'],
        )
      )
    )
  );

  foreach ($group['children'] as $field_name) {
    $form_state['values']['fields'][$field_name] = array(
      'parent' => '_add_new_group',
    );
  }

  field_group_field_overview_submit($form, $form_state);
}

```
> 3 votes

# Answer
Check this out, all can be done this way: https://www.drupal.org/node/1425984

```
function mymodule_install() {
// Add fieldgroup:
  $group_name = 'group_bankverbindung';
  $entity_type = 'profile2';
  $bundle = 'organizer_data';
  $mode = 'form';
  if (!field_group_exists($group_name, $entity_type, $bundle, $mode)) {
    $group = (object) array(
      'identifier' => $group_name .'|'. $entity_type .'|'. $bundle .'|'. $mode,
      'group_name' => $group_name,
      'entity_type' => $entity_type,
      'bundle' => $bundle,
      'mode' => $mode,
      'label' => 'Bankverbindung',
      'weight' => '1',
      'children' => array(
        'field_foobar',
      ),
      'format_type' => 'fieldset',
      'format_settings' => array(
        'formatter' => 'collapsible',
        'instance_settings' => array(
          'description' => '',
          'classes' => '',
          'required_fields' => 1,
        ),
      ),
    );
    field_group_group_save($group);
    ctools_include('export');
    ctools_export_crud_enable('field_group', $group->identifier);
  }
}

```
> 1 votes

# Answer
My solution - works for me

```
function mymodule_install() {
//Field_group object
 $group = (object) array(
    'identifier' => 'group_attributes|node|article|form',
    'group_name' => 'group_attributes',
    'entity_type' => 'node',
    'bundle' => 'story',
    'mode' => 'form',
    'label' => 'Attributes',
    'children' => array(),
    'weight' => '7',
    'format_type' => 'fieldset',
    'format_settings' => array(
      'formatter' => 'collapsible',
      'instance_settings' => array(
        'description' => '',
        'classes' => '',
        'required_fields' => 1,
      ),
    ),
  );
    module_load_include('module', 'field_group');
    module_load_include('module', 'ctools');
    ctools_include('export');
 $new = new stdClass();
        $new->group_name = $group->group_name;
        $new->entity_type = $group->entity_type;
        $new->bundle = $group->bundle;
        $new->label = $group->label;
        $new->parent_name = $group->parent_name;
        $new->children =$group->children;
         // The form.
        $new->id = NULL;
        $new->weight = $group->weight;
        $new->mode = 'form';
        $new->format_type = $group->format_type;
        $new->format_settings = $group->format_settings;
        $new->identifier = $new->group_name . '|' . $new->entity_type . '|' . $new->bundle . '|' . $new->mode;
        ctools_export_crud_save('field_group', $new);
}

```
> 0 votes

---
Tags: 7, entities
---


# Question
Title: Clicking "use-ajax" locks JS on page on slower devices until done. How to replace with $.ajax?
I have a large form that is often used but takes 2-3 seconds to load. To get around this, I have it loaded by clicking the `<a id="doc_ready_link" class="use-ajax"` link with JS on page load.

```
document.querySelector('#doc_ready_link').click();

```

Module

```
function custom_ajax_page_st_form_menu() {
  $items['class-content-form'] = array(
    'page callback' => 'ajax_content_response',
    'access callback' => 'user_access',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

```

On faster machines like my laptop or phone, this is fine and I have a fast page load and a spinner on the form link.
But on slower laptops and phones, other JS stuff like the menu doesn't work until it's loaded giving a bad UX.

How do I get that form loaded with ajax after page load without locking up the browser? For a normal click, the UX is ok but when it's all hidden like what I'm doing, the clunkiness is jarring.

Thanks.

EDIT:

I have tried the other methods below for clicking the link but the locking of other JS remains on slower devices. I'm still looking for some other method, most likely a snippet of `$.ajax` code that can call my module's code just like `class="use-ajax"` does.

PS for anyone wondering how to click Flags etc. in Drupal:

`document.querySelector('#').click();` works when `$('#').click();` usually doesn't.

Edit: For what it's worth, this is the module that the "use-ajax" link calls but I don't think it matters much.

```
<?php

function custom_ajax_page_st_form_form_init()
{
    drupal_add_js('misc/jquery.form.js');
    drupal_add_library('system', 'drupal.ajax');
}

/**
 * Implements hook_menu().
 */
function custom_ajax_page_st_form_menu()
{
    // A menu callback is required when using ajax outside of the Form API.
    $items['class-content-form'] = array(
        'page callback' => 'ajax_content_response',
        //   'access callback' => 'user_access',
        'access arguments' => array(
            'access content'
        ),
        'type' => MENU_CALLBACK
    );
    return $items;
}

function ajax_content_response($type = 'ajax', $nid = 0, $node_type = "", $home_nid)
{

    $output = _custom_page_st_form_loader();
    if ($type == 'ajax') {
        $commands   = array();
        $commands[] = ajax_command_replace('#class_form_load', '<div id="class_form_load">' . $output . '</div>');
        //    $commands[] = ajax_command_invoke('.add_menu', 'show');
        // Remove Spinner
        $commands[] = ajax_command_invoke('html', 'trigger', array(
            'remove_ajax_spinner'
        ));
        // Set Groups Audience
        if ($nid != 0) {
            $commands[] = ajax_command_invoke('#edit-og-group-ref-und-0-default', 'val', array(
                $nid
            ));
            $commands[] = ajax_command_invoke('#edit-og-group-ref-und-0-default', 'trigger', array(
                "chosen:updated"
            ));
        }
        // Set Home
        if ($nid != 0) {
            if ($node_type == "homepage_group") {
                $commands[] = ajax_command_invoke('.form-item-field-home-und input', 'prop', array(
                    "checked",
                    true
                ));

            } // $(".form-item-field-home-und input").prop("checked", true)
        }
        // Set Homepage Audience
        $commands[] = ajax_command_invoke('#edit-field-homepage-audience-und-0-default', 'val', array(
            $home_nid
        ));
        $commands[] = ajax_command_invoke('#edit-field-homepage-audience-und-0-default', 'trigger', array(
            "chosen:updated"
        ));

        $page = array(
            '#type' => 'ajax',
            '#commands' => $commands
        );
        ajax_deliver($page);
    } else {
        $output = '<div id="class_form_load">' . $output . '</div>';
        return $output;
    }
}

function _custom_page_st_form_loader()
{
    module_load_include('inc', 'node', 'node.pages');
    $form = node_add('class_content');
    return drupal_render($form);

}

```

And the reason this is a big deal for my site. There are 8 JS buttons that users click very quickly on the site and all break on slow devices.

# Answer
You should use `window.onload` if you want to have your code run after other javascript code (and DOM and CSS) have been loaded. `window.onload` is triggered after `document.onready`.

> The ready event occurs after the HTML document has been loaded, while the onload event occurs later, when all content (e.g. images) also has been loaded.
>
> The onload event is a standard event in the DOM, while the ready event is specific to jQuery. The purpose of the ready event is that it should occur as early as possible after the document has loaded, so that code that adds functionality to the elements in the page doesn't have to wait for all content to load.

\[quoted from https://stackoverflow.com/a/3698214/5875098\]

As an example (and to be more Drupal-specific), the following javascript should cover what you need:

```
(function ($) {
  Drupal.behaviors.yourModule = {
    attach: function(context, settings) {
      $('body').once('bind-window-load', function(){
        $(window).bind('load', function() {
          $('#doc_ready_link').click();
        });
      });
    }
  };
})(jQuery);

```

Good luck!
> 1 votes

# Answer
Hi everybody I coming back ;)

According to

# Events

`$(document).on('ready', handler)` binds to the ready event from jQuery. The handler is called **when the DOM is loaded**. Assets like **images maybe still are missing**. It will never be called if the document is ready at the time of binding. jQuery uses the *DOMContentLoaded*-Event for that, emulating it if not available.

`$(document).on('load', handler)` is an event that will be fired once all **resources are loaded** from the server. Images are loaded now. While onload is a raw HTML event, ready is built by jQuery.

# Functions

`$(document).ready(handler)` actually is a promise. **The handler will be called immediately if document is ready at the time of calling.** Otherwise it binds to the `ready`-Event.

Before jQuery 1.8, `$(document).load(handler)` existed as an alias to `$(document).on('load',handler)`.

# Further Reading

The @Stephan solution is not wrong but it's better you don't wait for all resources ( I mean all images etc ) load when your Menu Item ( DOM objects) loaded **So**

```
(function ($) {
  Drupal.behaviors.yourModule = {
    attach: function(context, settings) {
        $('#doc_ready_link').click();
    }
  };
})(jQuery);

```

**NOTE1:** As you know `Drupal.behaviors` acts like `$(document).ready` on Drupal so imagine *Bind on windows.load event in document.ready event binding*.

**NOTE2** if you have some ajax call it cause duplication calling of this form and for preventing duplication triggering(although in your case not required because you redirect page to another page immediately ) **So**

```
(function ($) {
  Drupal.behaviors.yourModule = {
    attach: function(context, settings) {
        $('body', context).once('myModule', function () {
        $('#doc_ready_link').click();

});
    }
  };
})(jQuery);

```
> 1 votes

# Answer
I don't really know what your form is doing, but perhaps the request and delivery callback is doing too much work. In my comment I had mentioned changing the delivery callback to ajax deliver. Here is an example:

https://gist.githubusercontent.com/kevinquillen/4c5df0e5f9c586182117/raw/1190acbc27b3192c33b87788f5a1f1c35f98b3c6/dynamic-reveal.example.php

```
function user_alert_menu() {
  $items = array();

  $items['js/user-alert/get-message/%'] = array(
    'page callback' => 'user_alert_display_alert',
    'delivery callback' => 'ajax_deliver',
    'page arguments' => array(3),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function user_alert_display_alert($nid) {
  $output = '';

  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node');
  $query->entityCondition('bundle', 'user_alert');
  $query->propertyCondition('nid', $nid);
  $query->propertyCondition('status', 1);
  $query->propertyOrderBy('nid', 'DESC');
  $query->range(0, 1);

  $result = $query->execute();

  if ($result['node']) {
    $record = reset($result['node']);
    $wrapper = entity_metadata_wrapper('node', $record->nid);
    $output = theme('user_alert', array('node' => $wrapper->value()));
  }

  $commands = array();
  $commands[] = ajax_command_html('div#user-alert-message', $output);
  $commands[] = ajax_command_invoke('div#user-alert-message', 'foundation', array('reveal', 'open'));
  return array('#type' => 'ajax', '#commands' => $commands);
}

```

On the front end, there are link(s) with the `use-ajax` class that trigger this behavior. The callbacks only function is what you see above, and despite doing an EFQ and a `theme` call, it was pretty quick. The end result here is the themed output is injected to a hidden div, and then a modal plugin opens that div.

You can also use `$.ajax` too, since you are just hitting a menu item route.
> 0 votes

---
Tags: 7, forms, ajax
---


# Question
Title: Is there a way to alter a form, implemented by another module, using a class?
Is there a way to alter a form, implemented by another module, using a class, in the same way it is possible to build a form using a class?

# Answer
Drupal core code still uses `hook_form_alter()` (or `hook_form_BASE_FORM_ID_alter()`, or `hook_form_FORM_ID_alter()`) for that purpose.
You could alter a route and change the form associated with that route, but this would mean that:

* You would need to keep track of the form class that was associated to that route before you changed it; in this way, you would be able to let the previous class add its own form fields
* You would need to alter all the routes using that form class, in order to make Drupal use your class

The closer I could see used from Drupal code, which means the code would be in a class, is what the *Content moderation* module does in `content_moderation_form_alter()`.

```
function content_moderation_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  \Drupal::service('class_resolver')
    ->getInstanceFromDefinition(EntityTypeInfo::class)
    ->formAlter($form, $form_state, $form_id);
}

```

Using that, you have the pro of using object-oriented code, allow other modules to extend the same form without complicating your code, and without interfering with code used from other modules.

Since the Drupal API page doesn't link the `EntityTypeInfo` class, it's the class defined in core/modules/content\_moderation/src/EntityTypeInfo.php.

The relevant code is the following one, which shows how a class method is used as form submission handler.

```
  /**
   * Alters bundle forms to enforce revision handling.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   * @param string $form_id
   *   The form id.
   *
   * @see hook_form_alter()
   */
  public function formAlter(array &$form, FormStateInterface $form_state, $form_id) {
    $form_object = $form_state->getFormObject();
    if ($form_object instanceof BundleEntityFormBase) {
      $type = $form_object->getEntity()->getEntityType();
      if ($this->moderationInfo->canModerateEntitiesOfEntityType($type)) {
        $this->entityTypeManager->getHandler($type->getBundleOf(), 'moderation')->enforceRevisionsBundleFormAlter($form, $form_state, $form_id);
      }
    }
    elseif ($form_object instanceof ContentEntityFormInterface) {
      $entity = $form_object->getEntity();
      if ($this->moderationInfo->isModeratedEntity($entity)) {
        $this->entityTypeManager
          ->getHandler($entity->getEntityTypeId(), 'moderation')
          ->enforceRevisionsEntityFormAlter($form, $form_state, $form_id);
        // Submit handler to redirect to the latest version, if available.
        $form['actions']['submit']['#submit'][] = [EntityTypeInfo::class, 'bundleFormRedirect'];
      }
    }
  }

```

This is the form submission handler that method is using.

```
  /**
   * Redirect content entity edit forms on save, if there is a forward revision.
   *
   * When saving their changes, editors should see those changes displayed on
   * the next page.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   */
  public static function bundleFormRedirect(array &$form, FormStateInterface $form_state) {
    /* @var \Drupal\Core\Entity\ContentEntityInterface $entity */
    $entity = $form_state->getFormObject()->getEntity();

    $moderation_info = \Drupal::getContainer()->get('content_moderation.moderation_information');
    if ($moderation_info->hasForwardRevision($entity) && $entity->hasLinkTemplate('latest-version')) {
      $entity_type_id = $entity->getEntityTypeId();
      $form_state->setRedirect("entity.$entity_type_id.latest_version", [$entity_type_id => $entity->id()]);
    }
  }

```

As you see, it's not the same as extending `FormBase`, but it's more OOP than using plain functions.
> 2 votes

# Answer
No, there's no object-oriented alternative to `hook_form_alter`.
> 0 votes

---
Tags: forms
---


title: Accessing fields from view template

text:
# Question
Title: Accessing fields from view template
I have a block view which filters for a specifiy content-type. I'd like to fully style it myself and also write the html myself it outputs. So I went and created the file views-view-fields-header-image-slider--block.tpl.php in /templates.

Now, I do have the $view object but no $field etc. Also `var_dump($view->field['description_title']);` result in Null.

I'm a bit confused how I can access the fields nor properly so I can render the image + description and all the other stuff.

# Answer
> 0 votes
If you haven't already, look at the theme information in the Advanced section on your Views admin page. It's near the bottom.

You should see a list of theme templates for each field, along with a row style that should have information for each row. Each field is also linked to a sample template, and you will also notice the list of file names the view is searching for, from general to specific. I've attached an example of what it looks like.

Looking at my own now... You might also want to try the "style output," though in my case I did everything through the field content template.

**Edited to add:**

I don't have enough reputation to comment yet, but it looks like there is some useful info on How do I access a field value in the $row variable in a field view theme template?

Simply out, here are the two approaches from over there:

```
$field = $row->{$field->field_alias}
$rendered_field = $view->render_field($fieldname, $view->row_index);

```

---
Tags: 7, views
---


# Question
Title: hook_theme_suggestions_hook_alter() not working for Views
I'm trying to create a custom template for a view page in Drupal 8.3.x. It's going in a custom theme, and needs to be a view-level template (so not page- or node-).

I've been fighting with it for a while and figured it might be an issue with the specific name, so I've made the code as sparse as possible - still no luck.

I have the following code in mytheme.theme:

```
function mytheme_theme_suggestions_views_view_alter(array &$suggestions, array $variables) {
  $suggestions[] = 'test_template';
}

```

And the following file structure:

```
- mytheme
  ~ templates
    * test-template.html.twig
  ~ mytheme.theme
  ~ mytheme.info.yml
  ~ ... etc.

```

I know that the theme\_suggestions alter function is working properly; I have Twig debugging enabled, and when I pull up my site and look at the code, I can see the following: (note the "X" next to views-view.html.twig showing that as the currently used Twig file)

```
<!-- FILE NAME SUGGESTIONS:
   * test-template.html.twig
   x views-view.html.twig
-->

```

So it's adding the suggestion. And the template file is named correctly. I know it's not a directory issue, because I have other .html.twig files in that /templates/ folder that are working correctly.

Does anyone know why the file name suggestion is working, but the matching file isn't?

---

Edit: Kevin pointed out a possible duplicate ticket in the comment below. That's only half-related. It does solve the **symptom** in this particular example - I have been able to pull in one of the templates mentioned here, and it works for this case.

However, the title of the ticket and general issue still holds. I can't get the hook\_theme\_suggestions\_hook\_alter() to work with my custom theme\_suggestion / template. While it turns out the view I used as my example could be solved another way, there are other instances where that won't be the case.

# Answer
Found the solution. As it turns out, for some reason Drupal doesn't play nicely with custom theme suggestions starting with a word + single dash.

I updated my HOOK\_theme\_suggestions\_HOOK\_alter() function to include `$suggestions[] = 'test__template';` (with 2 underscores between the words) and updated my template name to `test--template.html.twig` (with 2 dashes to match the 2 underscores), and everything works as expected.
> 6 votes

---
Tags: 8, theming
---


title: Getting a block inside main content

text:
# Question
Title: Getting a block inside main content
I have created a Drupal page which consists of the main content of my page, text plus a photo, a nested box which is just a button and a views block which is the third element. What I want to do though is make the nested box go below the views block which is only possible if I add the views block to the content page class but I am not sure how to do it. Any ideas?

# Answer
You can place your blocks in the "content" region and then you can arrange them in the correct order on the blocks page, `admin/structure/block`.

See screenshot below for Drupal 7 example.
> 0 votes

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


# Question
Title: How can I create a View utilizing the Access Log hits (Hits in last 4 weeks)
When creating a View, the only statistics available are total, today, and most recent. Is there a way to utilize the Access Log statistics (Number of views in last 4 weeks by example) instead?

See here for example of how to set up the typical Statisics Hits View: https://www.ostraining.com/blog/drupal/track-hits/

But instead I want only the hit count from the Access Log (Set for 3 days in the above example, mine is set for 4 weeks) so I can restrict the counter to a larger time period than "today", but shorter than "total".

# Answer
Maybe the visitors module might be a valid alternative to consider? Refer to its community docu for some more details.

**Be aware**: I'm the new maintainer of this module, it was unsupported until recently ...
> 1 votes

# Answer
You might try building an access log parser, which parses the access log, or merely gets a line count. Once you have that, create, say, one node per day with a total of the hits per day. You could write a PHP script to do this, or this might help: https://stackoverflow.com/questions/4662725/looking-for-a-php-class-to-parse-an-access-log-file

If you have access you your log files and logrotate, set it to a daily rotation, and parse the previous day's log (access.log.1). A line count should get a simple count of hits, though your may want to explicitly parse out only GET requests, or you might want to separate 200/non-200 requests.

Something else that's a bit more advanced is to install the ECK module and Services, and have a Python script parse the log and post each line into your site. I've found that Views is much faster if you flatten the logs into entities which only have properties, as this requires only one DB table.
> 0 votes

---
Tags: views, nodes
---


# Question
Title: AJAX request failing each time I try to invoke php function from module
I'm trying to invoke a AJAX request whenever someone clicks a download button on my drupal site.

In my module I have referenced the javascript file in the (my-module).info as follows:

```
scripts[] = js/my_module.js

```

my\_module.js:

```
(function ($) {
  $(document).ready(function(){
    $(".book-purchase-button").click(
    function(){
        $.ajax({
        type: 'POST',
        url: '/foo/ajax/tag',
      success: function(){
        alert("AJAX Call Successful!");
    },
      error: function(){
        alert("AJAX Call Failed!!");
    }
        });
    });
  });
})(jQuery);

```

I figured I could do a menu callback to capture the AJAX request based on the url

my\_module.module:

```
/*
*    Implements hook_menu().
*/
function my_module_menu()
{
  $items = array();
  $items['/foo/ajax/tag'] = array(
    'title' => '',
    'page callback' => 'my_module_tag_user',
    'access arguments' => array('access content'),
    'access callback' => TRUE, // allows access to any user
    'type' => MENU_CALLBACK,
  );
  return $items;
}

```

But for some reason the AJAX request keeps alerting me that the ajax call has failed... Is there something I'm doing wrong?

# Answer
> 1 votes
Routes don't have leading slashes:

```
$items['foo/ajax/tag'] = array(

```

Clear caches, and assuming the callback function exists and writes something to the buffer, it'll start working.

---
Tags: 7, ajax, hooks, navigation
---


# Question
Title: Difference between strongarm, field base, and field instance
What is the difference between the following options when using features? What is each of them for and an example of why each would be used.

* strongarm
* field base
* field instance

To make things even more complicated, there are often "field bundle" variables listed for strongarm to use.

# Answer
> 3 votes
A Drupal 7 database contains various structural configuration. Some of these are:

* Entity bundles, e.g. node types or taxonomy vocabularies.
* Field bases: These are definitions of fields that apply across bundles and entity types, wherever the same field is used.
* Field instances: These describe how a field is used for a specific entity bundle.
* Field display configuration per entity bundle and view mode. This gets even more with Display suite.
* General global key/value settings, stored in the variable table, which can be accessed with variable\_get() and variable\_set(). These are exported to features with strongarm.

Unfortunately, this entire system is a bit "dirty": Some of the structural configuration for fields and entity bundles is stored in the variable system, and not together with the field or entity type.

Therefore, whenever you export an entity bundle (e.g. node type) with features, you will also see some strongarm stuff. This is annoying and messy, but it is not avoidable.

I would recommend to maintain

* One feature containing all field bases.
* One feature per node type, with all field instances and field display configuration for this node type. This will also contain a lot of strongarm stuff.
* Another feature for general strongarm settings, that are not related to anything else.
* And more.

As far as I remember, `drush features-export myfeature node:mytype` already adds all the field instances and strongarm stuff for this node type.

Ideally you also have a naming pattern such as `mysite_ft_*` for all features, and `mysite_ft_ct_*` for all content type features. Also organize your sites/all/modules into `contrib/`, `custom/`, `features/`.

---

So in conclusion: You don't have a choice to pick either field base or field instance or strongarm. Instead, you usually want to export everything that you want to sync between your local environment and the dev, staging or live environments. The only choice is which of those things should live in the same feature, and which parts should live in different features.

---
Tags: 7, entities, features, strongarm
---


# Question
Title: How to display a view link in another view?
I’m listing in a view a list of article filtered with taxonomy terms.

The result is like this :

```
taxonomy term 1
- article A
- article B
- article C

taxonomy term 2
- article D
- article E
- article F

taxonomy term 3
- article G
- article H
- article I

```

Here is the view configuration :

I’ve also created a view which contains 3 articles and which have the same taxonomy relationship than articles.

I can see this view as a page like this : http://my-site.com/my-view

Here is my view configuration :

I would like to display this view link in the listing :

```
taxonomy term 1
- article A
- article B
- article C
- link to view A (associated with term 1)

taxonomy term 2
- article D
- article E
- article F
- link to view B (associated with term 2)

taxonomy term 3
- article G
- article H
- article I
- link to view C (associated with term 3)

```

How can I do that? I can't find a field in view configuration to display this view.

# Answer
> 2 votes
You can use either of these modules:

Views Field View

> There are a lot of cases in views where you want to embed a list inside each row. One example could be, you have a list of groups, and for each groups you want to list the first and last name of all of their members.

Viewfield

> Viewfield provides a field that holds a reference to a View and renders it whenever the entity containing the field is displayed.

# Answer
> 1 votes
As long as I can understand what you want, you can do it in 2 different method:

**Method 1:**

Within the first view (list of article filtered with taxonomy terms) add a field of type: **Global: Custom text** which will allow to create custom text or link and then add **the link of your second view** inside the **Global: Custom text**

**Method 2:**

You have to install and enable the Views field view module.

> There are a lot of cases in views where you want to embed a list inside each row. One example could be, you have a list of groups, and for each groups you want to list the first and last name of all of their members.
>
> This can be achieved with this module, as views\_field\_view allows you to embed one view into another view and pass arguments along.

and then go to your first view (list of article filtered with taxonomy terms) and add the **Global:view**, and now from within the settings of this field select **your second view** and voila !

**Note:** Using method # 2 will embed/display the entire **second view** within the **first view**.

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


# Question
Title: How to import an external database to D8 and create a search form?
I have a MySQL database with 2000 doctors, which are accessed classicaly through a HTML form and PHP. With the form you can search with criterias like ZIP, town, target group, treatment, languages, etc. Then a result list with doctors is shown and when clicking on one a profile page is opened with all the details of the doctor.

How can I migrate this to Drupal 8? I already read a lot and often Feeds is sugggested, but unfortunately it is not yet ready for Drupal 8.

# Answer
The best and most flexible option at your disposal will be to use the Drupal Migrate module. It's included by default in D8.

**The steps you'll have to follow is as below:**

1. Migrate your data from MySQl to a Drupal content type or an entity. You could also consider exporting your data to CSV and import from the CSV.
2. If you are not expecting very large traffic, use views and exposed filter to implement your search form with filters. If you are expecting the more traffic and scale user search\_api and use something like Solr in the backend.

**Some of the links where you can get started:**

1. Migrate to Drupal 8 from MySql.
2. Migrate to Drupal 8 from CSV file.
3. Official Migrate API documentation.

I am assuming you already know what content type, entity, views, exposed filters etc are. In case you don't know any of it, plenty of resources are available online.
> 1 votes

---
Tags: views, 8, forms, database, migrations
---


title: URL condition in Twig

text:
# Question
Title: URL condition in Twig
I have a category `mysite/news` (the page created by the Views) and when I turn to the next page of this category - `mysite/news?page=1`, some text and image should not be displayed.

This code does not work

```
{% if url == 'mysite/news' %}
some text
{% endif %}

```

# Answer
> 2 votes
You should be able to use 'in' operator to get around this issue. Try something like:

```
{% if 'mysite/news' in url %}

some text

{% endif %}

```

---
Tags: theming, 8
---


title: how to add a form to a build array

text:
# Question
Title: how to add a form to a build array
I am creating a custom module that has the following as the build:

```
$build = array(

          '#type' => 'markup',
          '#markup' => $html,
          '#attached' => array(

             'library' => array('pup_viewfiles/sortfiles_libraries'),
            ),
        );

    return $build;

```

I have a Form that I get with the following line :

```
$form=\Drupal::formBuilder()->getForm(pup_viewfiles\pager),

```

The question is how can I incorporate this form into the build ?

# Answer
> 2 votes
`getForm()` returns a render array, and a render array can have other render arrays as children, so:

```
$build = [
    'form' => $form,
    ...
];

```

---
Tags: 8, forms
---


# Question
Title: How to "featurize" customizations to Answers module (or a content type that is part of a module)
I'm implementing a discussion feature using the Answers module. I want to create a feature for all the customizations so I can implement and deploy using the git process.

The views and content types that I've customized (answers and questions) are not showing up as options to include in the feature.

Has anyone else worked with this module with git for local, staging/testing and production? How did you push your customizations? Thanks!

Drupal 7.54; Answers 7.x-4.0-rc2

Edit: Answers is a contributed module that comprises of some views and some content types and possible other components.

Edit 2: I've followed the advice in this SE post regarding a similar situation in views, but it doesn't solve my issue with content types or having to basically re-create the module.

# Answer
> 0 votes
For the customized views, I cloned and disabled the original views. Then I was able to pull the view (cloned one) into the feature.

For the content type customizations, I was able to pull in the new fields I created, and customizations to the other fields, by finding the names of the specific customized fields in field bases and strongarm in features.

---
Tags: features, 7
---


title: tablesorter pager.js is not working

text:
# Question
Title: tablesorter pager.js is not working
I have successfully added the tablesorter.js library to a table in my drupal website but when I try to add the pager, the input and select Html that I add do not show up. I add this HTML

```
    <div id="pager" class="pager">
    <form>
        <img src="../addons/pager/icons/first.png" class="first"/>
        <img src="../addons/pager/icons/prev.png" class="prev"/>
        <input type="text" class="pagedisplay"/>
        <img src="../addons/pager/icons/next.png" class="next"/>
        <img src="../addons/pager/icons/last.png" class="last"/>
        <select class="pagesize">
            <option selected="selected"  value="10">10</option>
            <option value="20">20</option>
            <option value="30">30</option>
            <option  value="40">40</option>
        </select>
    </form>
</div>

```

but something in the drupal site makes the select options and the input options disappear from the final page.

# Answer
> 0 votes
I had to add the form and form elements as a Form under the src/ directory and call it with

```
 $form= \Drupal::formBuilder()->getForm('Drupal\pup_viewfiles\Form\PagerForm', $extra);

```

---
Tags: 8
---


title: How do I put a <div> around a form?

text:
# Question
Title: How do I put a <div> around a form?
I have created a form that I will embed in my page with a custom module. How can I wrap this form with a div that has a specific class?

I need to add it to the build which is made with the following code.

```
$build = array(
          'form' => $form,
          '#type' => 'markup',
          '#markup' => $html,
          '#attached' => array(

             'library' => array('pup_viewfiles/sortfiles_libraries'),
            ),
        );

```

# Answer
There are many different ways to add markup to a form in Drupal 8. In your build array, you could add a wrapper element, and then nest the form within:

```
$build['wrapper'] = [
  '#type' => 'container',
  '#attributes' => ['id' => 'my-form-wrapper', 'class' => ['my-form-wrapper']],
];

$build['wrapper']['form'] = \Drupal::formBuilder()->getForm('Drupal\mymodule\Form\MyForm');

```

Alternately you could add a '#prefix' and a '#suffix' to your form.

```
$form['#prefix'] = '<div class="my-form-wrapper">';
$form['#suffix'] = '</div>';

```

Or you could use a template for your form and add it to your theme, using the suggestion form--form-id.html.twig and add custom markup there. (Be sure to replace underscores with hyphens in the template name.)

```
<div id="my-form-wrapper">
  <form{{ attributes }}>
    {{ children }}
  </form>
</dv>

```
> 14 votes

# Answer
I believe that you have described the perfect use case for the container render element.

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21Element%21Container.php/class/Container/8.2.x

I believe your build would be something like

```
$build = [
  'some_name' => [
    '#type' => 'container',
    '#attributes' => [
        'class' => 'some class',
    ],
    'form' => $form,
  ],
  'some_other_name' => [
    '#type' => 'markup',
    '#markup' => $html,
  ],
  '#attached' => array(
    'library' => array('pup_viewfiles/sortfiles_libraries'),
  ],
];

```

Wasn't exactly sure where you wanted the html markup (this has it outside the container).
> 3 votes

---
Tags: theming, forms
---


# Question
Title: D8 - Paragraphs - Multilingual - Content Erasing
I'm running into an issue on my D8 site where Paragraphs (module) content is erasing from a replicated node when I change the language of the replicated node.

I am using Paragraphs 8.x-1.1, Replicate 8.x-1.x-dev, Replicate UI 8.x-1.x-dev, and Drupal core is a little behind at 8.2.3.

I understand there's some issues with Paragraphs and translating and I found that others seem to have this working, but I'm wondering if there's something small (hopefully) that I'm missing in order to get this working.

A similar thread to mine can be found here regarding deleting the cloned nodes.

Thank you in advance!

# Answer
It turns out the issue was that I had the "Users may translate this field" checkbox checked for the paragraph field types in my content types. Once I unchecked those I was able to replicate the node, change the language, and the paragraph content did not erase.
> 1 votes

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