# Question
Title: Twitter sign in module session token values lost in twitter/oauth path in HTTPS - Invalid Twitter OAuth request
The twitter sign in module works on my local and staging server on HTTP fine. But when I install the same module in production mode which is https://example.com, it stops working. The error says "Invalid Twitter OAuth request". I debugged the code a little bit, and I could understand that the session variables stored in token before redirecting to twitter are lost when control is redirected to my site in twitter/oauth path.

```
/**
 * Submit handler for Twitter signin.
 */
function twitter_signin_redirect() {
  module_load_include('inc', 'twitter');
  $key = variable_get('twitter_consumer_key', '');
  $secret = variable_get('twitter_consumer_secret', '');
  $twitter = new Twitter($key, $secret);
  $token = $twitter->get_request_token();
  $_SESSION['twitter_oauth']['token'] = $token;
  $_SESSION['twitter_oauth']['destination'] = $_SERVER['HTTP_REFERER'];
  $_SESSION['twitter_oauth']['signin'] = TRUE;
  watchdog("twitter_sign_in", "Session Values Set => ". print_r($_SESSION, 1));
  drupal_goto($twitter->get_authenticate_url($token));
}

```

And on the validate function in twitter.pages.inc, the session values are clearly lost. I used watchdog entries on both functions. Its working fine in my local and staging server.

```
/**
 * Validate results from Twitter OAuth return request.
 */
function twitter_oauth_callback_form_validate($form, &$form_state) {
  global $twitter_token;
  $key = variable_get('twitter_consumer_key', '');
  $secret = variable_get('twitter_consumer_secret', '');
  watchdog("twitter_sign_in", "Session Values Set => ". print_r($_SESSION, 1));

  if (isset($_SESSION['twitter_oauth'])) {
    $form_state['twitter_oauth'] = $_SESSION['twitter_oauth'];
    unset($_SESSION['twitter_oauth']);
  }
  else {
    form_set_error('oauth_token', 'Invalid Twitter OAuth request');
  }

```

Any help is appreciated.

# Answer
> 1 votes
The error could be related to:

* Using API on the wrong domain/subdomain (*www* prefix can be relevant).

See: Why do I get a Oauth error?
* Temporary Twitter issue.

See: Twitter module Oauth 'TwitterException' with message 'Unauthorized'
* Make sure your code is passing the valid `oauth_verifier`.

> For OAuth 1.0a compliance this parameter is required unless you are using xAuth. Currently Twitter supports both OAuth 1.0 and OAuth 1.0a which means we do not error if this value isn't included. It is strongly recommended that applications not using this parameter are immediately updated with support for `oauth_verifier` added. OAuth 1.0a will be enforced soon and applications not using the `oauth_verifier` will fail to complete the OAuth flow.

See: Oauth/access\_token Stopped working today
* Your Twitter module may be outdated, please consider upgrading it.

If it's still happening, check the logs for any detailed responses. Otherwise contact Twitter support.

---
Tags: social-network, sessions
---


# Question
Title: How to grant permission to a node for an user programatically?
I am using ACL module to set user wise permission . Its working fine and I am able to set permission user wise from admin access.

What I need:

I have the `nid` and `uid` and I wants to set node view access permission to that user programmatically.

# Answer
> 1 votes
You may want to program it yourself, you can have something like this, probably implementing hook\_init():

```
function my_module_init() {
  global $user;

  $nid = 85; // We'll check node 85.

  // Users with access:
  $uids = array(
    3,
    9,
    11,
  );

  $node_path = 'node/' . $nid;

  // Check if the user is in the node detail.
  if (current_path() == $node_path) {
    // Check if the user is not in the list of allowed users.
    if (!in_array($user->uid, $uids)) {
      drupal_access_denied();
    }
  }
}

```

---
Tags: 7, nodes, users
---


title: How to have a proper breadcrumb path

text:
# Question
Title: How to have a proper breadcrumb path
I have a problem with my breadcrumb path on my drupal 7 installation. I am using URL-Alias (Module: pathauto) and have a "blog" content type. Now the view with all blog entries in the URL is on /blogs/ and entries are like /blogs/entryname. Unfortunately the breadcrumb still shows: frontsite / entryname no matter what I do instead of frontsite / blogs / entryname.

Same goes for taxonomy terms. I have an overview over taxonomy terms which is on /tags/ and when I click on a certain tag on that overview, i get a view with all nodes associated with that tag and the URL is like /tags/tagname but breadcrumbs still show frontsite / tagname instead of frontsite / tags / tagname.

Thanks for any help in advance

# Answer
I used a module called Smart Breadcrumb that builds breadcrumbs by using the url path and determining the title for each page. So far its Drupal 7 only. https://www.drupal.org/project/smart\_breadcrumb
> 1 votes

---
Tags: 7, path-aliases, breadcrumbs
---


title: Alter view data return?

text:
# Question
Title: Alter view data return?
I am wondering if there is a way to do the following.

I need to alter view return data and either remove entries or keep entires based upon running some PHP.

Is there any easy way to do that? I was looking at the theme stuff, but that would mean I would nuke my pagination, is there anyway I could remove results but regenerate my pagination.

Sorry if this is confusing...

**Edit:** It's a little difficult to explain, but I am using Commerce. And I need to get a list of discounted products. But commerce only discounts products before they are displayed (ie there is no database I can join/where on to get discounted products). So I need to get all the products, then remove those that are not discounts.

# Answer
> 0 votes
You can use `hook_views_data` to alter view data like Commerce discounted products. As suggested by *Clive*, here is the patch which is implementing related feature:

Other hooks to consider which can allow to alter the views data are:

---
Tags: 7, views, commerce
---


title: Entity forms bypass the access handler

text:
# Question
Title: Entity forms bypass the access handler
My entity defines an access control handler (a subclass of `\Drupal\Core\Entity\AccessControlHandlerInterface`) as well as a delete form (a subclass of `\Drupal\Core\Entity\EntityConfirmFormBase`).

The access handler designates certain entities as uneditable, and returns `\Drupal\Core\Access\AccessResult::forbidden()` on the "update" and "delete" operations for those entities.

This has the correct effect of hiding the "Edit" and "Delete" operation from the entity list.

Unfortunately, it doesn't do the same when visiting the forms directly via their URLs.

What am I doing wrong here? How do I actually block access to the forms?

Edit: The 404 was because I had the wrong URL for the edit form; turns out it's actually for all operations.

Do I need to call `$this->entity->access($this->operation)` myself in `buildForm()`?

# Answer
> 2 votes
> In your delete route add `_entity_access: yourentity.delete` to the route requirements.

As Ivan pointed out in the comment, this is a matter of the route not automatically requiring entity access when it points at an entity form. The entity access requirement must be added to the route explicitly.

---
Tags: entities, 8
---


title: DrupalGap Frontpage not displaying

text:
# Question
Title: DrupalGap Frontpage not displaying
I am following the drupalgap hello world creation tutorial, however all i tried to make the hello world proven to be unsucessful.

here is the frontpage config fron settings.js

i did the installation on mobile folder and the setting file is settings.js

```
// App Title
drupalgap.settings.title = 'gsam';

// App Front Page
drupalgap.settings.front = 'hello_world';

```

the module name is gsam with directory structure:

```
mobile/app/modules/custom/gsam

```

and here is my gsam.js,

when every i load my server pointing to the mobile I have 404, that is after i placed this code.

```
/**
 * Implements hook_menu().
 */
function gsam_menu() {
  var items = {};
  items['hello_world'] = {
    title: 'DrupalGap',
    page_callback: 'gsam_hello_world_page'
  };
  return items;
}

/**
 * The callback for the "Hello World" page.
 */
function gsam_hello_world_page() {
  var content = {};
  content['my_button'] = {
    theme: 'button',
    text: 'Hello World',
    attributes: {
      onclick: "drupalgap_alert('Hi!')"
    }
  };
  return content;
}

```

# Answer
One possible reason could be the apparent failure to refer the your custom module in your project settings.js. This file resides in mobile/app/modules/custom/gsam/www/app. Edit the file and add the following code in the *custom module* section:

```
Drupal.modules.custom['gsam'] = {};

drupalgap.settings.front = 'hello_world';

```
> 0 votes

---
Tags: services, javascript
---


# Question
Title: tb-megamenu how to click to open/close sub menu in mobile
We are attempting to get submenus to only appear when the user "taps" the menu option on a mobile browser. This functionality works good on hover but some mobile devices don't work with hovering. We need the ability to click submenu titles in order to drop them down and then click them again to collapse them.

# Answer
> 0 votes
Then look far, the best I found in my case has been the following:

I have overridden the method (js) of tb MegaMenu and done through the function drupal

1. I created a copy of tb-megaMenu-frontend.js file and called tbmega-custom.js and saved in the js folder of my theme.
2. What added to the system through the function drupal js\_alter. In my theme in the file called template.php

```
function mytheme_js_alter (&$javascript){
    $javascript[drupal_get_path('module', 'tb_megamenu') . '/js/tb-megamenu-frontend.js']['data'] = path_to_theme() . '/js/tbmega-custom.js';
}

```
3. I have adjusted the code to my needs. Just change the behavior of tbMegaMenuAction:

```
 Drupal.behaviors.tbMegaMenuAction = {
    attach: function (context) {
        $('.tb-megamenu-button', context).once('menuIstance', function () {
        var This = this;
        $(This).click(function () {
            if (parseInt($(this).parent().children('.nav-collapse').height())) {
                $(this).parent().children('.nav-collapse').css({height: 0, overflow: 'hidden'});
                Drupal.TBMegaMenu.displayedMenuMobile = false;
            }
            else {
                $(this).parent().children('.nav-collapse').css({height: 'auto', overflow: 'visible'});
                Drupal.TBMegaMenu.displayedMenuMobile = true;
            }
        });
    });

    //Comment this for mobile click
    //var isTouch = 'ontouchstart' in window && !(/hp-tablet/gi).test(navigator.appVersion);
    //if (isTouch) {

        $(document).ready(function ($) {
            var mm_duration = 0;
            $('.tb-megamenu').each(function () {
                if ($(this).data('duration')) {
                    mm_duration = $(this).data('duration');
                }
            });
            var mm_timeout = mm_duration ? 100 + mm_duration : 500;

            $('.nav > li, li.mega').click(function (event) {
                event.preventDefault();

                var $this = $(this);

                if ($this.hasClass('mega') && !$this.hasClass('clicado')) {

                    $('.nav > li, li.mega').each(function () {
                        $(this).removeClass('clicado open');
                    });

                    $this.addClass('clicado');
                    $this.addClass('animating');
                    clearTimeout($this.data('animatingTimeout'));
                    $this.data('animatingTimeout', setTimeout(function() {
                        $this.removeClass('animating')
                    }, mm_timeout));
                    clearTimeout($this.data('hoverTimeout'));
                    $this.data('hoverTimeout', setTimeout(function() {
                        $this.addClass('open')
                    }, 100));

                } else {

                    if($this.hasClass('mega') && $this.hasClass('clicado')) {

                        $this.removeClass('clicado');
                        $this.addClass('animating');
                        clearTimeout($this.data('animatingTimeout'));
                        $this.data('animatingTimeout', setTimeout(function() {
                            $this.removeClass('animating')
                        }, mm_timeout));
                        clearTimeout($this.data('hoverTimeout'));
                        $this.data('hoverTimeout', setTimeout(function() {
                            $this.removeClass('open')
                        }, 100));
                    }

                }

            });
        });

    //}

    $(window).resize(function () {
        var windowWidth = window.innerWidth ? window.innerWidth : $(window).width();
        if (windowWidth != Drupal.TBMegaMenu.oldWindowWidth) {
            Drupal.TBMegaMenu.oldWindowWidth = windowWidth;
            Drupal.TBMegaMenu.menuResponsive();
        }
    });
  }
 }

```

# Answer
> 0 votes
Because click function fires multiple times (e.g. when using a views block with ajax pager) I had to change the code like this (solution from here):

```
        //$('.nav > li, li.mega').click(function (event) {
        $('.nav > li > a, li.mega > a').click(function (event) {

          if(event.handled !== true) {
            event.handled = true;

            //event.preventDefault();

            //var $this = $(this);
            var $this = $(this).parent();

            if ($this.hasClass('mega') && !$this.hasClass('clicado')) {

                $('.nav > li, li.mega').each(function () {
                    $(this).removeClass('clicado open');
                });
                $this.addClass('clicado');
                $this.addClass('animating');
                clearTimeout($this.data('animatingTimeout'));
                $this.data('animatingTimeout', setTimeout(function() {
                    $this.removeClass('animating')
                }, mm_timeout));
                clearTimeout($this.data('hoverTimeout'));
                $this.data('hoverTimeout', setTimeout(function() {
                    $this.addClass('open')
                }, 100));
            } else {

                if($this.hasClass('mega') && $this.hasClass('clicado')) {

                    $this.removeClass('clicado');
                    $this.addClass('animating');
                    clearTimeout($this.data('animatingTimeout'));
                    $this.data('animatingTimeout', setTimeout(function() {
                        $this.removeClass('animating')
                    }, mm_timeout));
                    clearTimeout($this.data('hoverTimeout'));
                    $this.data('hoverTimeout', setTimeout(function() {
                        $this.removeClass('open')
                    }, 100));
                }

            }

          }  //if(event.handled !== true)
          return false;

        });

```

---
Tags: 7, theming
---


# Question
Title: connect to mysql with unix socket instead of tcp
I'm not looking for the "use `127.0.0.1`" solution. I want to run the site on my local development environment and use the unix socket to connect to the database. In my `settings` file I've set the host to `'host' => 'localhost',` and I've tried `'unix_socket' => '/tmp/mysql.socket',` as well, but both result in a `PDOException: SQLSTATE[HY000] [2002]` error in the apache logs.

When I connect directly to mysql through the command line I connect through the unix socket, but when I run it through Drupal it only connects through the TCP connection. I am under the impression Drupal will connect through the socket if the `localhost` host name is used, but this doesn't appear to be the case here.

Perhaps there's some other local configuration I'm missing.

# Answer
I quickly figured this out after posting. To connect using a socket use `'unix_socket' => '/tmp/mysql.sock',` not `.socket`.

This allows me to connect to mysql using the unix socket instead of the networking IP address, `127.0.0.1`. This may be an issue with core since I think by default Drupal should connect on this default socket.
> 1 votes

---
Tags: configuration
---


# Question
Title: Prevent the email registration module from appending the user ID as a suffix on new user's username
I'm a newbie in Drupal and I have an issue with the User module (I think).

In my user registration form there is no username field but there is email field provided by the Email Registration module. When users register, Drupal generates a username from given email using its first part before @ and appends user ID to it. For example: if I will try to register with email **user@mysite.com**, Drupal will generate username for my account **user\_123** where **123** \- is user ID.

How can I change this default behavior and prevent Drupal from adding **\_123** to generated username? Is there is any solution to get rid of the username, and use the email?

# Answer
While looking at the project page of Email Registration, it reads:

> A username is generated and assigned based on the user name part of the email address and their user ID. Sites that want to create usernames in their own way can do so by implementing hook\_email\_registration\_name.

And when looking at hook\_email\_registration\_name(), we see how we can alter the username by returning a value.

So, what you need to do is:

* Create a custom module (there is plenty of documentation for that on this site and the rest of the internet).
* Implement hook\_email\_registration\_name() (place this function in your module file and replace `hook` with your module name).
* Have the hook return a new username.

So you need to put something like this in your module file:

```
function mymodule_email_registration_name($edit, $account) {
  $mail = $edit['mail'];
  $mail_parts = explode('@', $mail);
  $username = $mail_parts[0];
  return email_registration_cleanup_username($username);
}

```

This will return the first part of the email as the username. So `john@gmail.com` becomes `john`. `bob@yahoo.com` becomes `bob`. `john@hotmail.com` becomes also `john`... But that was already in use and Drupal does not allow duplicate usernames, so you have a problem. (And you discovered the reason this module by default appends a unique token to the username.)

You could solve this by implementing a small iterator. Appending 1, 2, 3 to every subsequent John but it would result in just as ugly usernames (and for the 100th john you had to do 99 database lookups making this slow).

So I'd like to propose to you Real Name. This nifty module will override the username display everywhere with the value of one or more other profile field. So you add a namefield to the registration, configure Real Name to use that field and the user will never know his username is `john_123` because he will never see it.

I don't know your specific requirements and this might not be suitable for you, or if you can think of another way to enforce uniqueness, you can always use the hook and implement your own method. See what fits you :).
> 3 votes

---
Tags: 7, users, hooks
---


title: Extending the User Registration Form

text:
# Question
Title: Extending the User Registration Form
To add fields to the User Registration one can directly use the **admin/config/people/accounts** page. However, I am required to some other fields to the User Registration like ***food choice*** which is to be selected from drop-down list of foods, ***Email*** and ***Confirm Email*** fields (which should check whether both are same and whether the email was used in db), ***country*** (If UK/US is selected, text field for ***state***, ***postal code*** should appear). Now, I could add the fields to the user registration page, but how can I handle the validations for the fields and how do I show such dropdown list. Am I required to create my module that extends the User Registration form. If so, how do I do this? Thanks.

# Answer
> 1 votes
If your only need is to add new required fields to the user registration form, you do not need modify the form through a module; by marking any user entity field as a **Required field** in the field UI, it will be presented in the registration form as a required field for registration.

If you require custom validation that goes beyond "it must be non-empty" you might need to employ a custom validation handler in a custom module, another helper module (e.g. Field validation), or a custom field module that matches your use case (e.g. Address field module).

---
Tags: forms, users, 8
---


# Question
Title: How to add a custom field to apache solr?
How do you create your own solr field using Drupal 8's search api?

# Answer
> 7 votes
1) Copy /modules/contrib/search\_api/src/Plugin/search\_api/processor/AddURL.php into your own custom module at /src/Plugin/search\_api/processor

2) Rename and rework (see below)

3) Add your extra field to the index at /admin/config/search/search-api/index/myindex/fields

4) Enable the processor on your search\_api index

5) Reindex content and verify in solr that your new custom field is indexed.

http://127.0.0.1:8983/solr/#/mysolrcore/schema-browser?field=sm\_mymodule\_content\_type, click on "Load Term Info" to see data loaded in.

Here's an example:

```
namespace Drupal\mymodule\Plugin\search_api\processor;

use Drupal\search_api\Datasource\DatasourceInterface;
use Drupal\search_api\Item\ItemInterface;
use Drupal\search_api\Processor\ProcessorPluginBase;
use Drupal\search_api\Processor\ProcessorProperty;

/**
 * Adds a custom type filter to the indexed data.
 *
 * @SearchApiProcessor(
 *   id = "mycustom_field",
 *   label = @Translation("Custom Field"),
 *   description = @Translation("Add a custom field to search index"),
 *   stages = {
 *     "add_properties" = 0,
 *   },
 *   locked = true,
 *   hidden = false,
 * )
 */
class CustomField extends ProcessorPluginBase {

  /**
   * machine name of the processor.
   * @var string
   */
  protected $processor_id = 'mycustom_field';

  /**
   * {@inheritdoc}
   */
  public function getPropertyDefinitions(DatasourceInterface $datasource = NULL) {
    $properties = array();

    if (!$datasource) {
      $definition = array(
        'label' => $this->t('Custom Field'),
        'description' => $this->t('custom field'),
        'type' => 'string',
        'processor_id' => $this->getPluginId(),
      );
      $properties[$this->processor_id] = new ProcessorProperty($definition);
    }

    return $properties;
  }

  /**
   * {@inheritdoc}
   */
  public function addFieldValues(ItemInterface $item) {
    $entity = $item->getOriginalObject()->getValue();

    $custom_field = '';

    // Use $entity to get custom field.

    $fields = $this->getFieldsHelper()
      ->filterForPropertyPath($item->getFields(), NULL, $this->processor_id);
    foreach ($fields as $field) {
      $field->addValue($custom_field);
    }

  }
}

```

---
Tags: 8, search
---


# Question
Title: Menu is not creating in admin/settings page?
I am adding a custom module, and wants when someone install the module, menu will be added to add data in the admin/settings page... But i am getting nothing:

Below is the code i wrote.. pricepackages is the module name i want to created

please help me ..

```
function pricepackages_menu()
{
    $items = array();
    $items[] = array(
        'path' => 'admin/settings/favorites/quotes',
        'title' => t('Manage Quotes'),
        //'page callback' => 'drupal_get_form',
        //'page arguments' => array('poke_test_form'),
        'callback' => 'drupal_get_form',
        'callback arguments' => 'pricepackages_settings',
        //'access callback' => 'poke_access_callback',
        'access' => user_access('Access administration pages'),
    );
}

```

Settings hook is like this:

```
function pricepackages_settings()
{
    //$form['#submit'][] = 'poke_test_submit';
    $form['quote_manage'] = array(
        '#title' => t('Select User'),
        '#type' => 'textfield',
    );
    return $form;
}

```

# Answer
```
function pricepackages_menu()
{
    $items = array();
    $items['admin/settings/favorites-quotes'] = array(
        'title' => t('Manage Quotes'),
        'page callback' => 'drupal_get_form',
        'page arguments' => array('pricepackages_settings'),
        //'access callback' => TRUE,
        'access arguments' => array('access administration pages'),
    );
}

```
> 0 votes

# Answer
I have created a module : '**Custom\_menu**' with following file structure

***modules/custom***/custom\_menu/

* custom\_menu.info.yml
* custom\_menu.module

```
        <?php
        /*
         * hook_toolbar()
         */
        function custom_menu_toolbar() {
            /**
             * Custom menu for Catalog
             * Array for $module should be array('Name' => 'machine_name')
             */
            $baseUrl =  \Drupal::request()->getHost().base_path();

            $modules = array(
                'Categories' => 'categories',
                'Products' => 'products'
            );

            $links = array();
            $a=0;
            foreach ($modules as $module => $route) {
                $links[$module] = array(
                    'title' => $module,
                    'type'=>'link',
                    'url' => Url::fromUri($baseUrl.'/admin/content-list/content_type/'.$route),
                    'attributes' => array(
                        'title' => $module,
                    ),
                );
                $a++;
            }

            //content-list/{content_type}
            $shortcut_links = [
                '#theme'=>'links__toolbar_shortcuts',
                '#links'=>$links,
            ];

            // Create the examples toolbar render array.
            $items['admin_menu_catalog'] = array(
                '#type' => 'toolbar_item',
                'tab' => array(
                    '#type' => 'link',
                    '#title' => t('Catalog'),
                    '#url' => Url::fromRoute('<front>'),
                    '#attributes' => array(
                        'title' => t('Catalog'),
                        'class' => array('toolbar-icon', 'toolbar-icon-examples'),
                    ),
                ),

                'tray' => array(
                    '#heading' => t('Catalog'),
                    'shortcuts' => $shortcut_links,
                ),

                '#weight' => 200,
                '#attached' => array(
                    'library' => array(
                        'shortcut/drupal.shortcut',
                    ),
                ),
            );
        }

```

Now you will see Catalog menu in you admin menu bar with child menus : Categories and Products.

Authentic user can see related content only. Also can add content without following the default procedure of the Drupal.
> 0 votes

---
Tags: 7, commerce, hooks
---


title: Drupal node add form is empty: why?

text:
# Question
Title: Drupal node add form is empty: why?
Just transferred my brand new Drupal webshop to shared to host and guess what: it doesn't work.

I can't figure out that why node add page is lacking form? Everything else is in place. And to be more spefic it is just for one content type, other work fine.

I've tried drush rr, drush cc all etc. I've checked permissions etc. I'm using Display Suite forms as template for node add form.

**This all of the rendered form markup that has a empty div container:**

```
<form class="node-form node-content_type-form" enctype="multipart/form-data" action="/content_type" method="post" id="content-type-node-form" accept-charset="UTF-8" novalidate="novalidate"><div>

    </div></form>

```

And this is for anonymous users. For admins it work normally but it also has another theme.

When I tranferred the site I took a archive dump with drush and imported it into shared host.

**UPDATE**

Like always this Drupal like problem seemed very odd. So I decided just to change the theme and see if it has any effect.

Using the base theme of my custom the form is rendered normally.

However, custom theme works just fine on my localhost so I can't tell what is the problem. Seems like a theme issue but on the other hand not.

**UPDATE 2**

Base theme showed some "new" errors on second load. These errors refer to a oooold theme and shows that Drupal is trying to use that tpl file. I assume that this is the core problem which causes different results depending on theme.

```
'/home/user/public_html/sites/all/themes/custom_boot/node-content_type-form.tpl.php

```

**UPDATE 3**

I found the old code that registered this "theme" or template and which is still somehow required/requested on page load:

```
function custom_boot_theme($existing, $type, $theme, $path){

    return array('node__content_type__form'=>
            array(
                'render element' => 'form',
                //'path' => drupal_get_path('theme', 'custom_boot') . '/templates',
                'template'=> 'content-type-node-form',
            'user_register_form'=>
            array(
                'render element' => 'form',
                //'path' => drupal_get_path('theme', 'custom_boot') . '/templates',
                'template'=> 'content-type-node-form',
            ),
        );
}

```

How could I undo this?

**UPDATE 4**

If I remove this old theme and run drush rr, it will give following error every time:

```
    The following theme is missing from the file system: <em class="placeholder">custom_boot</em>. For information about how to fix this, see <a                        [warning]
href="https://www.drupal.org/node/2487215">the documentation page</a>. bootstrap.inc:1128

```

Even though custom\_boot is removed from system table by drush rr, it will still try to find some files related to this removed theme.

**UPDATE 5 - FINDINGS AND POSSIBLE SOLUTIONS**

First of all it seems that the problem is somehow in the current theme. What is it? I don't know.

Secondly, why does this site work perfectly on localhost but not on this live server? Could I make some changes to PHP ini settings that would "look through"/disregard the small hickup of missing theme? I don't understand that why localhost won't die on this missing theme problem...

**UPDATE 6**

Well, since I couldn't get a rid of I had to stick with it. I've just enabled this old theme but which I'm not using. Now the form shows but it is rendered with this old themes custom form template file described above.

BUT, as soon as I visit /admin/structure/types/manage/content-types/fields the form starts failing again. So Display Suite and old theme have some issues.

AND TO ADD, it is all the same if the *content-type-node-form.tpl.php* file has content or not: the form is rendered and I can put any code in there and it won't change or break anything.

# Answer
> 0 votes
Well, now I feel stupid. Eventually it seemed to be a file permissions related issue.

I took this https://www.drupal.org/node/244924 script and modified it per server spec.

After few trials it worked...It certainly didn't seem like a permissions related but maybe they cause various situations.

---
Tags: theming, nodes, forms, wsod
---


# Question
Title: How to delete folder along with the files from database also?
I want to delete selected folder along with all files inside that folder. I tried by using `file_unmanaged_delete_recursive()` It will delete folders and files but it is not removing database entry of files and not even it is making the Status of the file to Zero. So how can I achieve this?

# Answer
> 1 votes
`file_unmanaged_delete_recursive()`, as the name implies, removes any files under a directory without concern to managed files (i.e. files tracked in the database).

In order to remove files from the database, you can make use of the `file_delete()` function in the File API. This function needs the file ID supplied as an argument, so you'll need to perform a query on the database to retrieve it. For example:

```
$files = file_scan_directory('sites/default/files/my_custom_dir', '/.*/', array('recurse' => TRUE));
foreach($files as $file) {
  $scanned_file_uri = file_build_uri($file->uri);
  // @TODO: query file_managed.uri for match with $scanned_file_uri
  // then delete with file_delete();
}

```

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


title: Installing Drush on WSL

text:
# Question
Title: Installing Drush on WSL
How should I install Drush on WSL when running the following command shown in the Drush documentation fails?

```
php -r "readfile('http://files.drush.org/drush.phar');" > drush

```

# Answer
Better to follow this to require with composer: https://www.drupal.org/node/1248790

1. Install composer globaly:

$ curl -sS https://getcomposer.org/installer | php

$ sudo mv composer.phar /usr/local/bin/composer
2. Require drush:

composer global require drush/drush:7.\*

The instructions in drupal.org also show how to add the path so you can use drush from everywhere.

Im working with WSL and it works great.
> 2 votes

---
Tags: drush
---


# Question
Title: How to remove a file from a "Choose file..." dialog?
Or, how to set things up so users can do that, I guess...

The point: Once you've selected a managed file in a standard Drupal "Choose file..." dialog, there doesn't seem to be a way to remove the file, short of refreshing the page. For those cases where the file is optional, something like this ought to be there, and I'm actually a little surprised that it's not there already. I suppose I could throw some jQuery together and hang my own button off the input field, but is there really nothing in core Drupal that will do this (or IS there something, and I'm just missing it or screwing it up somehow)? Thanks!

# Answer
I guess you are refering Drupal 7, as Drupal 8 has by default that option.

---

# D7

### What Drupal (D7) Provides,

**Step-1:** File/Image uploading option in node.

>

**Step-2:** *Example Case:* Suppose I uploaded wrong image instead of `IMG_0065.jpg`, I want to upload `IMG_0068.jpg`.

>

**Step-3:** Just Re-upload the file on the previous file, the new file will be loaded and the previous file will be removed.

>

**Step-4:** Image file uploaded and now als0 you can remove as Remove Button is there.

>

So, In short you want **REMOVE** button at **Step-2**, But the default file uploaded do not have that option. That is the fact. But if you manage, Drupal provide the option of replacing, which is quite similar option of removing.

### Solution using other file uploader Module

Now, instead of using Drupal's Default File uploaded feature, you can download new module called, Drag & Drop Upload. Installation: For this also like default file uploaded, you have to create add a field in content type and in widget option you need to choose Drag and drop instead of file.

Now, following is the image of drag and drop in action, now you can see after just browsing, you can see X mark besides file. Which is the the Step-2 option which was missing in above default setup.

>

***Further Reading:*** *On this link there is a detailed comparison of all type of File Uploading Modules, you can refer more from there: Multiple file upload for node*

---

# D8

By default Drupal 8 has this option as shown in following image.

>
> 2 votes

# Answer
For Drupal 7 removing files occurs after you have saved a file to a Node; then you can mark it for deletion from the file list attached to a node. On Cron run the file is removed from the filesystem.
> 0 votes

---
Tags: forms
---


# Question
Title: Add conditional where condition to hook_views_query_alter()
I was stucked making a few tweaks to a view trying to do the following. In mysql exists the possibility to use WHERE IF to evaluate some variable/operation to apply differents conditions depending on the result/value, like a common IF/ELSE block, is there any way to do it with add\_where() or any other similar method? I need to apply a WHERE condition to the query when the value of a variable called $scope is G and a different when its L, there's any way to achieve that?

What I need to do is to do this query on Drupal 7 Views hooks

```
SELECT * FROM tbl1 AS t1 JOIN tbl2 AS t2 ON t2.entity_id = t1.nid JOIN tbl3 AS t3 ON t3.entity_id = t1.uid  WHERE t1.status = 1 AND t1.type = "article" AND IF(t2.field_alcance_nodo_value = '{char}', t3.field_pais_usuario_value = '{string}', t3.field_pais_usuario_value LIKE '%') ORDER BY t1.changed DESC;

```

but I'm stucked on the IF part... I'm using the hook\_views\_query\_alter() but I don't know if it's enough.

Thank you in advance,

# Answer
You can achieve this using `switch-case` or `if-else` in `mymodule_views_query_alter`.

```
function mymodule_views_query_alter(&$view, &$query) {
  //Get your variable $scope here
  switch($scope) {
    case 'G':
      $query->add_where_expression(0, "$variable = :placeholder", array(':placeholder' => 'value');
      break;
    case 'L':
      $query->add_where_expression(0, "$another_variable = :another_placeholder", array(':another_placeholder' => 'another_value');
      break;
  }
}

```

Hope this helps.
> 1 votes

---
Tags: 7, hooks, views
---


# Question
Title: Need to create a report in Drupal 7 that counts Articles by Author for date range
I am trying to create a simple display that lists all my authors who provided content to my site during a date range (i.e. Jan 1 thru Dec 31) with a count of the number of articles published, as follows:

Joe Smith, 120
Bob Jones, 87
Tom Kelly, 3

While the output is fairly simple, creating it is not (at least for me). I would think this would be a fairly common reporting requirement, so I'm hoping someone has already created it somewhere. If so, I'd love to use it on my site.

# Answer
> 1 votes
Create a view by selecting users and add filter by date.

# Answer
> 0 votes
You dont have to cut past, just install view export module and download data in .xls format.

---
Tags: log-messages
---


# Question
Title: How to display a field twice in a view mode?
I'd like to display a field\_address in a view mode twice, once as the displayed address and once as a google maps directions link. I suppose I could create one custom field formatter that outputs both components, but it seems excessive to create a formatter to display basically what should be two formatters.

Is there a way, say in hook\_entity\_view to display a field twice with two formatters? Basically say $build\['field\_address\_direction'\] = $build\['field\_address'\] and then change the formatter?

# Answer
If you want to display a field twice in `hook_ENTITY_TYPE_view()`, you can get the field object from the first field and clone the field with a different field formatter and custom display settings.

For example to add the body a second time with the field formatter `text_summary_or_trimmed` and a custom trim length of `80`:

```
function mymodule_node_view(&$build, $entity, $display, $view_mode) {
  if (isset($build['body']['#items'])) {
    $build['body_teaser'] = $build['body']['#items']->view([
      'type' => 'text_summary_or_trimmed',
      'settings' => [
        'trim_length' => 80,
      ],
    ]);
  }
}

```

You can clone the current settings this way:

```
$build['body']['#items']->getSettings();

```
> 3 votes

---
Tags: 8, entities
---


# Question
Title: Node Reference, and Entity Reference are great; I need “Menu reference”
Is there a Menu reference module I can use to attach menus to nodes, and render them on the page?

# Answer
I have never used the module, but in theory, Block Reference should be able to solve your problem. If needed, I assume you can combine it with Menu Block to set up the menu blocks you need.
> 4 votes

# Answer
You can control which pages to display blocks (menus) on. It would be quite simple only to show a specific menu in a page and region of your liking.

This is done in the block section.
> 3 votes

# Answer
Yes there is a Menu Reference Module
> 1 votes

# Answer
Consider the Context module. Awesomeness packaged.
> 0 votes

---
Tags: routes
---


# Question
Title: How to add Shipping method for commerce flat rate module?
i am working on drupal commerce's "shipping" part, i want to create two methods for shipping as 1.Free Shipping 2.Express 2-day Shipping for USA .

For "free shipping" condition is if order total is greater than $100 then we can use "free shipping" else it should apply rate $4.

for "Express 2-day Shipping" condition is if order total is less than $140 then we can cost $12 else it is free.

# Answer
The Rules module integrates with Drupal Commerce in order to handle this type of requirement. There are many video tutorials available that explain how to setup various shipping rules.

There is also a module called Conditional Rules that may be useful if you need to have branching logic in your rules.

In this case I think you would only need two rules:

1. Conditions: type of shipping == "Free shipping" AND order total \> $100 Actions: shipping cost = $0
2. Conditions: type of shipping == "Express" AND order total \> $140 Actions: shipping cost = $0

You would set the default pricing for the "Free shipping" to $4 and the for the "express" to $12. The default prices would be overridden by the Rules in those two cases.
> 0 votes

---
Tags: commerce
---


title: Render comment edit form in block

text:
# Question
Title: Render comment edit form in block
I am using following code to render node comment form in a block:

```
$comment_form = drupal_get_form('comment_node_<node_type>_form', (object) array('nid' => $nid));
print drupal_render($comment_form);

```

It is working fine.

Now I need to check if a user has already commented on the node. If the user has not commented than I will show him/her this comment add form.

But in case, the user has already placed a comment for the node, I want to show him/her the edit form for his/her comment, where he/she can make changes and save thus updating the existing comment instead of saving new.

Any suggestions?

# Answer
I found a solution for this case, sharing so that anyone who need similar solution can use it.

Anyone who has similar issue can use the solution below:

```
<?php
    $comment = comment_load($comment_id); // $comment_id = cid of comment whose edit form need to be open

    module_load_include('inc', 'comment', 'comment.pages');
    $form = drupal_get_form('comment_form', $comment);

    return drupal_render($form);
?>

```
> 0 votes

---
Tags: 7, forms, comments
---


# Question
Title: How to get the Route object from an URI?
If I have a `Url` object, or even a simple string representation of path such as `/node/2`, how can I get the full `Route` object?

# Answer
> 12 votes
You can retrieve this information from the Symfony router. This can be accessed in Drupal through the `router.no_access_checks` service.

If you have a simple path (note that the path has a leading slash):

```
$router = \Drupal::service('router.no_access_checks');
$result = $router->match('/node/2');

```

If you have a `Url` object:

```
$router = \Drupal::service('router.no_access_checks');
$result = $router->match($url->toString());

```

This will return an array that includes the route object, as well as other useful information such as the route name and route parameters, the controller, the title callback and even the entity object represented by the URL.

---
Tags: 8, routes, uri
---


# Question
Title: How to create a Rule to create a new entity of type Comment and a body with tokens?
Using **drupal 7** and the Rules module, I'm trying to *"create a new entity"* of type `comment`. What it's strange, is that although all the other fields accept tokens, *"the main body text"* doesn't. Tokens are considered as simple text.

Anyone experienced this and know how to solve it?

# Answer
Have a look at Comment # 10 of the Rules (support) issue titled "Access and Set Comment extra fields". It includes a Rule example that looks like so:

```
{ "rules_test" : {
    "LABEL" : "Comment bot",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "node_update" ],
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_status" } }
    ],
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "comment",
            "param_subject" : "zzz",
            "param_node" : [ "node" ],
            "param_author" : [ "node:author" ],
            "param_comment_body" : { "value" : {
                "value" : "This text will be replaced in the next action.",
                "format" : "filtered_html"
              }
            }
          },
          "PROVIDE" : { "entity_created" : { "new_comment" : "New comment" } }
        }
      },
      { "data_set" : {
          "data" : [ "new-comment:comment-body:value" ],
          "value" : [ "node:field-status" ]
        }
      }
   ]
  }
}

```

The clue to solve your issue (= work around?) is to use that last Rules Action starting with "`data_set`".
> 2 votes

---
Tags: 7, rules, comments, tokens
---


# Question
Title: How to write an Webservice API Wrapper the drupal 7 way
I have been trying to find a standardized way of writing a Webservice API Wrapper the drupal 7 way but I was not able to find any documentation on this. How does one write an Webservice API wrapper for Drupal 7? An example will be much appreciated.

# Answer
The standard solution is to use the Services module, which provides hooks for you to define your own endpoints.

There's also Restful Web Services which has similar functionality but is geared more towards entity API integration.

If you literally want to write your own API from scratch then just use your best judgement - there aren't any Drupal-specific standards for that.
> 1 votes

# Answer
You can try services views, It can be used with views Module.

> Views support for the Services module version 3.x and later.
>
> It has currently two features: \- Create view based resource creating Services display in a view \- Execute any view of the system via views resource call
>
> Demo video http://youtu.be/DZEhJKMeR5w
> 0 votes

---
Tags: 7
---


# Question
Title: Create a Views that displays all unused taxonomy terms
I found this article about how to create a Views to display all active taxonomy terms: https://www.drupal.org/node/770782

I want to achieve the exact contrary: Get a list of all terms that are not used by my nodes.

Can I reach this with Views UI, relashionships, etc?

Any clue is welcome!

# Answer
> 5 votes
This can be achieved by View **relationships and aggregation**

1) Add a new view of view type "term"

2) Add Field Taxonomy: Term Name

3) Add Relationship "Taxonomy term: Content with term"

4) In the View : Advanced section , Enable Aggregation

5) Add new Filter **nid**, `Aggregation type` = **Count DISTINCT** , Select `Relationship` = **node** , `Operator`= **equal to** , `Value`= **0**

# Answer
> 0 votes
Be careful to trust on the proposed solution, if you have unpublished nodes, because unpublished entities do not appear in views

If you use the aggregation view to delete orphaned taxonomy terms, you might loose information of your unpublished nodes. Consider using the "delete orphaned terms" module

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


# Question
Title: Integration with Single Page Application (React)
I have a specific scenario to integrate a single page application (react based) with Drupal (I use version 7) in order to achieve the following:

1. Utilize the CMS capabilities of drupal and provide static content some of it will be public some will be private to authorized users only.
2. Create a totally separate single page application with specific functionality, with react framework and will communicate with a different backend system. I want this app to expose it through drupal, as a page by selecting it from the menu. Only authorized users will be able to enter this section of the drupal app.
3. Being able to pass user details to my single page application, in order to use them to the communication with the backend (for authorization and other operations)

I'm fairly new to Drupal, as far as I understand I will need to develop a module and/or a theme to do that? Additionally, drupal and my application should have a common authentication mechanism,I use OAuth2 server which is provided as a separate instance from drupal and my single page application.

From my research I haven't found any concrete example/documentation on how to achieve this. What I have managed to achieve so far is to be able to utilize my OAuth2 server with the help of OAuth2 Authentication module.

My second part is now missing to integrate my single page application and pass some user details information to it.

# Answer
> 5 votes
To provide the page hosting the React SPA, you will need to implement a custom module. This module would also contains all the JavaScript code of your application. If that's the only usage of React in your site, I suggest bundling everything in the module to make it easier.

I assume you should be able to retrieve the user authentication token and any other needed info in Drupal. You can then pass it to your application using `drupal_add_js()` (or `#attach` in a render array). Your application can then retrieve it with `Drupal.settings`

```
/**
 * Implements hook_menu().
 */
function MODULE_menu() {
  return [
    'admin/APPLICATION/PATH' => [
      'title' => 'Awesome React Application',
      'page callback' => 'MODULE_application_page',
      'access arguments' => 'access administration pages'
    ]
  ];
}

/**
 * Page callback for the application page.
 *
 * @return The page as a render array with #attached JS and CSS code.
 */
function MODULE_application_page() {
  global $user;
  $app_data = clone $user;
  unset($app_data->pass);
  $app_data->token = MODULE_get_user_token();
  $base_assets_path = drupal_get_path('module', 'MODULE');
  return [
    '#type' => 'markup',
    '#markup' => '<div id="MODULE-app-container"></div>',
    '#attached' => [
      'css' => ["$base_assets_path/css/app.css" => ['preprocess' => FALSE]],
      'js' => [
        "$base_assets_path/js/app.js" => ['preprocess' => FALSE],
        [
          'type' => 'settings',
          'data' => ['MODULE' => $app_data]
        ]
      ],
    ]
  ];
}

```

---
Tags: authentication-authorization
---


title: GMap shows on page inspect

text:
# Question
Title: GMap shows on page inspect
I am using GMap Module (in Drupal 7). Map does not show on page load, but when I inspect the web page, map shows up.
I tried reinstalling module but in vain. Map shows in GMap Configuration, but on node page it shows only if user inspects page. I have made no change in default GMap code

If anyone has solution to this issue, please share
A bundle of Thanks.

# Answer
> 0 votes
you need to trigger resize when the map is shown.

Try this code:

```
 $(document).ready(function () {
      $('#mymodal').on('shown', function () {
        google.maps.event.trigger(map, 'resize');
      });
    });

```

Hope this will help you.

---
Tags: 7, google-maps
---


# Question
Title: How to fix drush php configuration on the hosting?
I am facing a pretty award drush problem. In order to run drush I need to use this command on my hosting:

```
/opt/php/bin/php -c /home/pisar/etc/php.ini
                 -d memory_limit=128M /home/pisar/opt/drush.php

```

When I run

```
/opt/php/bin/php -c /home/pisar/etc/php.ini
                 -d memory_limit=128M /home/pisar/opt/drush.php status

```

it works correctly. But when I try to do the update command:

```
/opt/php/bin/php -c /home/pisar/etc/php.ini
                 -d memory_limit=128M /home/pisar/opt/drush.php upc drupal

```

and it fails with the message:

> pm-updatestatus failed

I found out that upc runs drush in subshell with incorrect php. So I added path to php:

```
/opt/php/bin/php -c /home/pisar/etc/php.ini
                 -d memory_limit=128M /home/pisar/opt/drush.php
                 --php=/opt/php/bin/php --debug upc drupal

```

But it also fails without configs. When I pass configs:

```
/opt/php/bin/php -c /home/pisar/etc/php.ini
                 -d memory_limit=128M /home/pisar/opt/drush.php
                 --php=/opt/php/bin/php\ -c\ /home/pisar/etc/php.ini\
                 -d\ memory_limit=128M --debug upc drupal

```

it fails because it tries to run them using quoted php with params:

```
Backend invoke: '/opt/php/bin/php -c /home/pisar/etc/php.ini -d memory_limit=128M' /home/pisar/opt/drush.php --php='/opt/php/bin/php -c /home/pisar/etc/php.ini -d memory_limit=128M'  [command]
 --backend=2 --verbose --debug --root=/home/pisar/site.com/docs/drupal --uri=http://default  pm-updatestatus drupal 2>&1 [1.45 sec, 14.72 MB]
'/opt/php/bin/php -c /home/pisar/etc/php.ini -d memory_limit=128M' /home/pisar/opt/drush.php --php='/opt/php/bin/php -c /home/pisar/etc/php.ini -d memory_limit=128M'  --backend=2      [notice]
--verbose --debug --root=/home/pisar/site.com/docs/drupal --uri=http://default  pm-updatestatus drupal 2>&1 [1.45 sec, 14.73 MB]
The command could not be executed successfully (returned: /opt/php/bin/php -c /home/pisar/etc/php.ini -d memory_limit=128M: not found

```

I put this:

```
export DRUSH_PHP='/opt/php/bin/php'
export PHP_INI='/home/pisar/etc/php.ini'
export PHP_OPTIONS='-d memory_limit=128M'

```

into `~/.profile`, `~/.bash_profile` and `~/.bashrc`. Then ran without `--php`, but nothing helped.

How to fix?

# Answer
I had to use `--php-options` parameter. The working command looks like this:

```
/opt/php/bin/php -c /home/pisar/etc/php.ini -d memory_limit=128M
                    /home/pisar/opt/drush.php --php=/opt/php/bin/php
                    --php-options="-c /home/pisar/etc/php.ini
                    -d memory_limit=128M" upc -y drupal

```
> 1 votes

---
Tags: drush
---


title: Search API Usage

text:
# Question
Title: Search API Usage
I'm new to search api. Can anyone please make me understand about the usage of "Search API" on my opinion below.

As far my understanding, it can index from multiple source like solr, mongodb or any other source that defined in service (as it allowed me to configure multiple server) and can serve search result by combining all the data.

OR

It provide a mechanism to index existing data through configured server?

# Answer
Search API is a module the creates index where are indexed nodes or other entities.

If you want to use it you have to have a "server" (by default the index is the same db of the drupal installation). There are modules that implements connection between search api and server (Solr, Elastic Search, for example).

After you have configured the index you can use Views to build view with data from the search api index and also use facet integration.
> 1 votes

---
Tags: 8, search
---


# Question
Title: Cloned Sites and Original Site Are All Affecting Each Other
I am using Aegir to clone my Drupal 7 sites. I don't have any caching enabled on the original site.

When I clone the site everything appears to work correctly, however changes to the drupal database are mirrored between all my sites. For example, adding a new user will add the user to all the sites.

I have verified that separate databases are specified for each of the sites.

Any ideas what would be causing this?

# Answer
I just figured it out. I have a wildcard SSL setup for my server. By default when you clone a site in Aegir it does not set it up as SSL. However, I was still able to access the cloned site via HTTPS.

**The issue was caused by accessing the site via HTTPS when SSL was not enabled in Aegir for that specific site.**

**As soon as I enabled SSL for the site in Aegir the problem went away.**

I'm not exactly sure what was going on in the backend. It would be great if someone could chime in on that...
> 0 votes

---
Tags: database, aegir
---


# Question
Title: Drupal 7 node body content missing from search results
I am having an issue where my Drupal 7 Search (Custom search installed and enabled) isn't returning all of the results I'd expect it to.

**Here is some background...**

* I'm running Drupal 7 on this site.
* I have roughly 10 content types, but the search only returns 2 content types – `work` and `blog`.
* I am using the core `search module` along with drupal `custom search module`.

**The Issue:**

When I perform a search I am presented with a selection of results from both `work` and `blog` content types. However, the issue is while the `blog` content type produces the expected results pulling from keywords in both the node titles as well as the nodes body content, the `work` content type only returns results where the keyword is found in the node title.

**Attempted fixes:**

* I have confirmed that the site is 100% indexed. Just in case I have re-built the index.
* I went to the `Custom Search Module` settings to confirm that `-Any-` is being used in the `-Any content type-` text field. In addition, in the `Content exclusion` area I've made sure both the `blog` and `work` content types were left unchecked.
* I have confirmed that the `Minimum word length to index` is at 3. My searched words are above 5.
* And lastly, two thoughts I didn't know played into the search results, but were worth looking into are the `Manage Display` settings for both content types under their `Search index` and `Search result highlighting input` tabs. Both of which seem to be identical. So I assume wth my limited knowledge of Drupal's configurations isn't really vital to this issue.

I'm still trying other suggestions found here in StackOverflow and will update this as I come across new options to try as attempted fixes.

If anyone has come across this matter and can lead their considerable knowledge on it, that too is always appreciated.

Thanks in advance!

# Answer
> 1 votes
Okay, so I was able to resolve this issue through a combination the following efforts.

* Under both `content types` and added in new fields to `search index` and `search results highlighting input`.
* Under `Administrator/Configuration/Search and Metadata/Search Settings` I turned off `Simple CJK handling`.
* Under `Custom Search Content Tab` I used the default of `-Any-` and under the Exclusion options left all but my two desired `content types` checked.
* Under `Administrator/Configuration/Search and Metadata/Search Settings` I clicked `re-index site`.
* I then flushed all caches and ran `cron` until the site was once again 100% indexed.

After all that I performed my tests again and everything was coming up as expected. Hopefully this can help others later in their testing.

---
Tags: 7, nodes, search, cron
---


# Question
Title: Custom block: How to know you're in an admin context?
I've developed a custom block which relies on a taxonomy term ID being present in the URL, otherwise it throws a 404.

I've placed this block in a panel page (ctools pages), but now when I try to edit the panel page, I get a 404 response, but only on the "Content" tab of the panel page variant.

What's the proper method for knowing you're on an admin page, or in the context of a panel edit, so that I can skip throwing a 404?

# Answer
> 3 votes
Looks like I just need to call `path_is_admin`

```
if (!path_is_admin(current_path())) {
  drupal_not_found();
  drupal_exit(); // This is needed if we call drupal_not_found() from hook_block_view()
}

```

---
Tags: 7, panels, chaos-tool-suite
---


# Question
Title: How to add terms directly from the content overview?
I have a few taxonomies with custom fields. I would like the user to be able to add terms directly from the content overview page at `admin/content`, and for the terms to be listed there - without having to navigate to the taxonomies page. As if the taxonomies were a content type. Any suggestions?

# Answer
> 0 votes
I think you are looking for something like Inline Entity Form.

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


# Question
Title: Drupal 8 : Get a config settings value being stored in blocs
I have create a block with a form and stored something i called 'submit\_action\_amu\_dud\_form\_block\_settings'

```
 public function blockSubmit($form, FormStateInterface $form_state) {

    $this->configuration['submit_action_amu_dud_form_block_settings'] = $form_state->getValue('submit_action_amu_dud_form_block_settings');

 }

```

in a method of the same class i can retrieve the value

```
      $config = $this->getConfiguration();
      $my_stored value=$config['submit_action_amu_dud_form_block_settings']

```

how can i get it from . module hook\_form\_alter callback ?

```
    function mymodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

if ($form_id == 'amu_dud_form') {
    $form['actions']['submit']['#submit'][] = 'my_submit_method';
}
}

 function my_submit_method(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

//$my_stored_value=??

```

# Answer
You need to load the block if your outside of the class, for that you need it's id.

```
$block = \Drupal\block\Entity\Block::load($bid);
$my_stored_value = $block->get('settings')['submit_action_amu_dud_form_block_settings'];

```

The id can be found in it's annotation if it's custom: `@Block( * id = "my_fancy_block_id"`. If there are several instances of the block this may be altered and can be looked up in the DB, or the block config admin section - check the urls there.
> 2 votes

# Answer
thanks to remy i have been able to retrieve the value from an instance of block this way:

```
//instance of block bid found in db
$block = \Drupal\block\Entity\Block::load('my_blockinstance_bid');
$block_settings = $block->get('settings');
$url=$block_settings['my_stored_setting'];

```

The problem remain then , when having mutliple instance of blocs, to load a block config dynamically corresponding to the settings value that have been stored for the block being displayed on the page ?
> 0 votes

---
Tags: 8, forms, configuration
---


# Question
Title: Fetch fields of a block defined via content type programmatically
I've created a block type via the UI. This is a translatable block with 3 text-fields.

I am using `hook_block_view_alter($build, $block)` to massage the data. However, I can not seem to find the fields neither in `$build` or `$block` vars. Any idea on the fetch the field's values programmatically?

# Answer
You are in the wrong entity. **`block`** is a *config entity* to configure where and how the block is displayed and which plugin is used to build the block.

The plugin can be a core, contrib or custom block class. In your case a core plugin, which fetches content from the database. The content is stored in the content entity **`block_content`**.

So the entity type to modify the fields of a custom block is `block_content` and you have to use this hook:

```
hook_block_content_view_alter(&$build, $block_content)

```
> 3 votes

# Answer
This is not how it is done in Drupal 8. The Drupal 8 way is to define a custom Plugin (a cusotm Block) and the add the data directly in the plugin. No alter is required!

This is how you make a custom block: https://www.drupal.org/docs/8/creating-custom-modules/create-a-custom-block

Also the Drupal 8 block API: https://www.drupal.org/docs/8/api/block-api
> 0 votes

---
Tags: 8, entities, blocks
---


# Question
Title: acquia/solr/D7: indexing additional files outside of a node
I'm trying to set up a way to index uploaded PDFs in such a way that a user can search for a term (`foo`) and get a list of all the nodes with fields that contain `foo` somewhere; and once they've clicked through to a page, they should be able to search for `bar` within the attached PDF and see a list of snippets along with a link to jump to that page in the PDF. In my research, I decided the best way to do this would be to write a module that splits the PDFs into individual pages with filenames that include the page number, index those new documents (along with the parent document), and build my "snippet" results from those new documents. So, for example, when I upload `sample.pdf`, I get the following folder structure:

```
content
 |
 +-- sample.pdf
 |
 +-- sample.pdf_src
 |  |
 |  +-- sample.pdf_1.pdf
 |  +-- sample.pdf_2.pdf
 |  \-- sample.pdf_3.pdf
...

```

That works fine, but where I'm getting stuck is indexing those extra files. For background, I'm using Acquia's Solr module (`apachesolr_search`) with the extra attachments module (`apachesolr_attachments`). Is it even possible to manually index those additional files I broke out? If not, are there any other ways I can get those files into the index? Maybe attach them to the original node where the user uploaded the original PDF? I just don't want to get into a situation where I have 800 attachments to a single node because the one PDF the user uploaded contained 800 pages.

If it were possible to get page numbers out of the original upload when searching for content, that would be the most ideal situation; however, my research indicates it's not possible. I'd be happy to be proven wrong, though.

# Answer
> 0 votes
Decided just to work within the Drupal framework rather than trying to hard-code something special. After I split the PDF, for each page I used `file_save_data()` to register the file in the `file_managed` table, then added the resulting file to the node in a separate file field:

```
$thisSplitURI = "{$splitURI}/{$finalFilename}_{$i}.pdf";
$thisSplitPath = drupal_realpath($thisSplitURI);
$file = file_save_data($contents, $thisSplitURI); // $contents is the value where the raw PDF contents are stored
$file->display = 1;
$node->field_split_pdf_pages[LANGUAGE_NONE][] = (array) $file;

```

Probably not ideal, especially when there's an 800-page document in there, but it gets the job done.

---
Tags: search, acquia-cloud
---


title: Create multiple custom node add pages

text:
# Question
Title: Create multiple custom node add pages
I'm using Display Suite to create custom multiple layouts for content. Is it possible to do something similar to the node/add/mycontent page? I want to be do show/hide and organize fields on the edit and add pages.

# Answer
You can check out Field group module. It allows you organize the fields with different transitions.
> 0 votes

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


# Question
Title: Drupal commerce: How to retrieve VAT number from order ID?
I would like to print the VAT number (provided by module vat\_number) on the invoice PDFs generated by module commerce\_billy, but I can not figure out, how to retrieve VAT number when an order ID is given.

# Answer
It took me a while to figure it out, but now I've found an answer myself:

```
$profile_id = $order->content['commerce_customer_eu_vat_rc']['#items'][0]['profile_id'];
$profile_wrapper = commerce_customer_profile_load($profile_id);
$vat_id = $profile_wrapper->commerce_vat_number['und'][0]['value'];

```
> 0 votes

---
Tags: entities, commerce
---


# Question
Title: Create a view that displays a related term users
* I created a "Group" vocabulary with the terms "Company 1", "Company 2", ...
* I created a field on the account setting.
* I linked my user account "Company 1" and 4 other users.
* I created a view that displays a list of users.

How to display only users associated with the same duration as the currently logged in user?

thank you in advance

```
$view = new view();
$view->name = 'views_groupe';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'users';
$view->human_name = 'Groupe';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Groupe';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'none';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'uid' => 'uid',
  'field_code_groupe' => 'field_code_groupe',
  'field_groupe' => 'field_groupe',
  'name' => 'name',
  'mail' => 'mail',
  'ops' => 'ops',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'uid' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'field_code_groupe' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'field_groupe' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'name' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'mail' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'ops' => array(
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
/* Field: User: Groupe */
$handler->display->display_options['fields']['field_groupe']['id'] = 'field_groupe';
$handler->display->display_options['fields']['field_groupe']['table'] = 'field_data_field_groupe';
$handler->display->display_options['fields']['field_groupe']['field'] = 'field_groupe';
$handler->display->display_options['fields']['field_groupe']['type'] = 'taxonomy_term_reference_plain';
/* Field: User: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['label'] = 'Nom d\'utilisateur';
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
$handler->display->display_options['fields']['name']['link_to_user'] = FALSE;
/* Sort criterion: User: Created date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'users';
$handler->display->display_options['sorts']['created']['field'] = 'created';
/* Contextual filter: User: Groupe (field_groupe) */
$handler->display->display_options['arguments']['field_groupe_tid']['id'] = 'field_groupe_tid';
$handler->display->display_options['arguments']['field_groupe_tid']['table'] = 'field_data_field_groupe';
$handler->display->display_options['arguments']['field_groupe_tid']['field'] = 'field_groupe_tid';
$handler->display->display_options['arguments']['field_groupe_tid']['default_action'] = 'default';
$handler->display->display_options['arguments']['field_groupe_tid']['exception']['title'] = 'Tout';
$handler->display->display_options['arguments']['field_groupe_tid']['default_argument_type'] = 'current_user';
$handler->display->display_options['arguments']['field_groupe_tid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['field_groupe_tid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['field_groupe_tid']['summary_options']['items_per_page'] = '25';
/* Filter criterion: User: Active */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'users';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = '1';
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'groupe';
$translatables['views_groupe'] = array(
  t('Master'),
  t('Groupe'),
  t('more'),
  t('Apply'),
  t('Reset'),
  t('Sort by'),
  t('Asc'),
  t('Desc'),
  t('Nom d\'utilisateur'),
  t('Tout'),
  t('Page'),
);

```

# Answer
> 0 votes
Views query alter should help.

```
/**
 * Implements hook_views_query_alter().
 */
function hook_views_query_alter(&$view, &$query) {
  if ($view->name == "views_groupe") {
  global $user;
  $user_data = user_load($user->uid);
  if (isset($user_data->field_groupe)) {
    $company_name = $user_data->field_groupe['und']['0']['tid'];
    $query->add_table('field_data_field_groupe');
    $query->add_where(0, 'field_data_field_groupe.field_groupe_tid', $company_name, '=');
  }
 }
}

```

Remove all the contextual filters set, only have the filter you set under filter criteria.

# Answer
> 0 votes
You should be able to do this using contextual filters and relations.

1. Add the contextual filter "User: uid".
2. Under "WHEN THE FILTER VALUE IS NOT IN THE URL" select "Provide default value" -\> "User id from logged in user".
3. Add a required relationship: "Taxonomyterm: Content with term."
4. Finally, on top of your view field preferences select your added relationship.

---
Tags: 7, views, users
---


title: Current page url token not using https

text:
# Question
Title: Current page url token not using https
I have the following token set up: \[current-page:url:absolute\] in metatag settings.

If I visit my site: https://www.example.com it displays http://www.example.com where I used the token. Everything else (css,js,etc..) uses https.

# Answer
> 0 votes
Turns out there was a home page rule set up in metatag configuration that had the url hardcoded. Didn't see that at first.

---
Tags: 7, tokens
---


# Question
Title: Add to Cart Forms Buttons disables Boost Module Caching
I've installed boost on my drupal 7 site with commerce setup. Boost is working fine, but any pages with a form, such as an add to cart form. It will disable boost caching. I need a way to ajax load these form buttons after the page is loaded so boost doesnt cache the forms.

What methods are there to solve this solution?

# Answer
> 0 votes
I solve the solution by using the following module:

https://www.drupal.org/project/commerce\_cart\_link

One issue I had to was getting these links to display in a Views output as this module turns the add to cart input fields into url links. There was no option in views to change this:

I did a work around to get this to work. Apparently you can just append the product id to the form of this link:

/cart/add/nojs/\[product-id\]/random-token-variable

I'm not sure what the token is for, but you can just put anything in there and it will still add it to the cart. It works for anonymous, but when your logged in, the link will hit you to an access denied page. I had to do the following to get it to work for authenticated users by commenting out 3 lines in commercie\_cart\_link.module:

I'm not sure what the token is for.

---
Tags: 7, commerce, performance, caching
---


title: Autosubmit exposed filter?

text:
# Question
Title: Autosubmit exposed filter?
Is it possible without change in core files to display exposed filters without "Submit" button and with autosubmint functionality? I mean autosubmit form, not autocomplete.

# Answer
This is not an option at the moment in Drupal 8. This option was removed in this issue There is an issue for it. They are trying to get it into ctools right now. ( 20-10-2016 )
> 1 votes

# Answer
turn ajax "on", change "Exposed form style" to autosubmit, hide submit button
> 0 votes

---
Tags: views, entities, 8
---


title: How do I configure the REST API?

text:
# Question
Title: How do I configure the REST API?
A couple months back I successfully setup a development site to learn about the Drupal 8 REST API with version 8.0.x using the REST UI module for configuration. When I heard about the improvements to the REST Services in Drupal 8.2 I was pretty excited (from my understanding it is now possible to access configuration data such as content types and taxonomy terms) so I setup a new install using version 8.2.1. However, understanding the configuration for 8.2 is pretty daunting, and since it's so new there are very little resources around the setup and configuration.

I was able to locate this resource and I imported the example configuration provided, but was still unsure on how to configure other REST Endpoints.

I used the default configuration provided in the above resource. It looks like this:

```
langcode: en
status: true
dependencies:
 module:
   - basic_auth
   - hal
   - node
id: entity.node
plugin_id: 'entity:node'
granularity: resource
configuration:
 methods:
   - GET
   - POST
   - PATCH
   - DELETE
 formats:
   - hal_json
 authentication:
   - basic_auth

```
* How do I edit the configuration once it's imported via the configuration manager?
* Where can I find the available `plugin_id`'s so that I can configure other resources? Where can I learn more about plugins?
* How would I begin to implement my own REST endpoint?

I know this is a lot to ask, but at the time of writing there is little to no information covering these topics so I figure other people might be confused as well. I would like to create a guide on this, but that would first require that I understand it first.

# Answer
> -2 votes
Since posting this, the documentation on drupal.org/docs/8/ has been updated appropriately.

# Answer
> 1 votes
I search a lot too after 8.2x and this is how i got it working :

Example for a custom user ressource :

> myModule/config/install
>
> rest.resource.user.rest\_ressource.yml

```
langcode: en
status: true
dependencies:
  module:
    - basic_auth
id: user.rest_ressource
plugin_id: 'user_rest_ressource'
granularity: resource
configuration:
  methods:
    - GET
  formats:
    - json
  authentication:
    - basic_auth

```

> In myModule/src/Plugin/rest/resource
>
> UserRestRessource.php

```
<?php

namespace Drupal\myModule\Plugin\rest\resource;

use Drupal\Core\Session\AccountProxyInterface;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Psr\Log\LoggerInterface;

/**
 * Provides a resource to get view modes by entity and bundle.
 *
 * @RestResource(
 *   id = "user_rest_ressource",
 *   label = @Translation("User Rest"),
 *   uri_paths = {
 *     "canonical" = "/api/user/getInfo"
 *   }
 * )
 */
class UserRestRessource extends ResourceBase {

  /**
   * A current user instance.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;

  /**
   * Constructs a Drupal\rest\Plugin\ResourceBase object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param array $serializer_formats
   *   The available serialization formats.
   * @param \Psr\Log\LoggerInterface $logger
   *   A logger instance.
   * @param \Drupal\Core\Session\AccountProxyInterface $current_user
   *   A current user instance.
   */
  public function __construct(
    array $configuration,
    $plugin_id,
    $plugin_definition,
    array $serializer_formats,
    LoggerInterface $logger,
    AccountProxyInterface $current_user) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);

    $this->currentUser = $current_user;

  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->getParameter('serializer.formats'),
      $container->get('logger.factory')->get('restimadiff'),
      $container->get('current_user')
    );
  }

  /**
   * Responds to GET requests.
   *
   *
   *
   * @throws \Symfony\Component\HttpKernel\Exception\HttpException
   *   Throws exception expected.
   */
  public function get() {

      $responseResource=new ResourceResponse(
          array()

      );
    return $responseResource;
  }

}

```

---
Tags: 8
---


title: how to change the colorbox image size?

text:
# Question
Title: how to change the colorbox image size?
I have a content type named gallery and under this, I have created the gallery content which is belong to that content type and added the multiple images but the problem is when I click the thumbnail image color box window opened but small images opened.

# Answer
1. Create a new image style of any size you want to open the image in colobox.
2. Now browse to manage display of your content type.
3. Select the formate 'Colorbox' for image field.
4. Add newly created image style for **Colorbox image style**, please follow below screenshot.
> 1 votes

---
Tags: media, javascript
---


title: Commerce file description as text only

text:
# Question
Title: Commerce file description as text only
I've got a shop selling downloadable product variations. I'd like to display the Commerce Files field description to anonymous users as text only.

Here's how it currently appears for registered users:

The field description visible is an active link...

--

Here's the current display for anonymous users

No description available

--

I can't find anywhere in the UI that allows for displaying the description without a link to all users. Here's the display options .

Any ideas?

# Answer
> 0 votes
I figured this out. ticking the 'display' box on the file field in the product form and settings appropriate permissions worked.

---
Tags: commerce, files
---


title: users forced to reset password

text:
# Question
Title: users forced to reset password
I'm on 7.39 and I get a lot of reports from users that re forced to reset their password every time they visit the site.

I'm honestly clueless about how to debug and haven't been able to find similar support requests on the forums.

Any ideas are extremely welcome

**update** Here's feedback from a user that couldn't even reset:

\*If I use this link: http://www.tambourhinoceros.net/user/user-id/orders/order-id:

> You are not authorized to access this page.

If I try to login ... with this e-mail adress and my password ... nothing happens. If I request a new passwort this message appears

> There was a problem with your form submission. Please wait 6 seconds and try again. You must be a human, not a spam bot, to submit forms on this website. If you insist that you are a human, please try again. If error persists, contact webmaster using contact link at the bottom of this page and give all the details of this error (your browser, version, OS). Form is submitted too fast. Please spend more time filling in the form.

*

# Answer
> 0 votes
I found out it was caused by a conflict between botcha and honeybot. Disabling botcha fixed the issue

# Answer
> 0 votes
You could use the Password Policy module to manage your password policies.

---
Tags: 7, users
---


title: Provide Menu in Module

text:
# Question
Title: Provide Menu in Module
I am looking for a way to provide a whole menu (no menu items) within a module. I could find many ways how to do that in D7, but I really would like to da that in D8.

# Answer
You put the menu in the folder `config/install` of the module.

An example from the devel module:

**/config/install/system.menu.devel.yml**

```
id: devel
label: 'Development'
description: 'Links related to Devel module.'
langcode: en
locked: true

```

Then you can place the menu link items for this menu in `*.links.menu.yml` in the root directory of the module.

**Edit:**

As mentioned in the comment from @mradcliffe, some background info might be helpful. Menus are configuration entities. The storage of the configuration is for performance reasons in the database, but they were at the beginning of D8 in yaml files. If you sync the configuration to the harddisk you will find the configuration in a set of yaml files. You can put any of these yaml files in the config/install folder of your module. But you have to remove the uuid line, because the uuid is only valid for the installation you have exported the yaml file from. The menus are in `system.menu.*.yml`.
> 3 votes

---
Tags: 8, navigation
---


# Question
Title: get node by address field and part of name
I have a content type which have a name field and address field.

I want to retrieve programmatically all the nodes in a specific city and wich contain in his name one or many keywords.

For example i want to search in "Paris" the node wich contain in name the word "beautiful" and/or "shop". Then i can retrieve theses results : \- "My beautiful shop of candies" in "Paris" \- "Fast shop" in "Paris"

The problem is that i don't know how to get nodes by a word containing in :/

Here is my current code :

```
$query  =  new EntityFieldQuery();

$entities  =  $query->entityCondition( 'entity_type', 'node' )
    ->propertyCondition( 'status', 1)
    ->fieldCondition( 'field_adress', 'locality', 'Paris', 'like' )
    ->fieldCondition( 'field_name', 'value', array('beautiful', 'shop', 'money') )
    ->execute();

dsm($entities);

```

I tried to change :

```
->fieldCondition( 'field_name', 'value', array('beautiful', 'shop', 'money') )

```

to

```
->fieldCondition( 'field_name', 'value', array('beautiful', 'shop', 'money'), 'CONTAINS' )

```

but I get this error :

> Warning : addcslashes() expects parameter 1 to be string, array given dans DatabaseConnection-\>escapeLike() (ligne 984 dans /Applications/MAMP/htdocs/fritr/includes/database/database.inc).

# Answer
> 1 votes
You could do this by building the query up in smaller chunks and using a loop to add the field conditions for the mulitple words . I'm not sure how of how you'll be passing the data in but say you have an array of words in $words.

```
$query = new EntityFieldQuery();
$query-->entityCondition( 'entity_type', 'node' )
    ->propertyCondition( 'status', 1)
    ->fieldCondition( 'field_adresse', 'locality', 'Paris' );

foreach ($words as $word){
   $query->fieldCondition('name', 'value', $word, 'CONTAINS');
 }

$result = $query->execute();

```

This code isn't tested and I've written off the top of my head. https://api.drupal.org/api/drupal/includes!entity.inc/function/EntityFieldQuery%3A%3AfieldCondition/7.x

---
Tags: 7, nodes, database
---


# Question
Title: How to hide the submit button on a node add/edit form page within which a entity reference select list has no valid option?
*Registration* content type has a required entity reference field. The widget of this field is a select list, the options are populated with a views entity reference display output. I want to hide(unset) the submit button if the views entity reference display returns no value. I've asked a question here for reference, I'm suggested to post a new question.

# Answer
> 0 votes
You can do this by using hook form FORM ID alter .

Once hooked in you find the $form item for the drop down list. It'll be somewhere like

$form\['field\_my\_entity\_ref'\]\['und'\]\['#options'\]

So you should be able to make a check on the values in that array and if there are none then make the Submit button disabled . My guess is

```
if ( count($form['field_my_entity_ref']['und']['#options']) < 1 ) {

   $form['#submit']['#disabled'] == TRUE;
 }

```

https://api.drupal.org/api/drupal/developer!topics!forms\_api\_reference.html/7.x/#disabled

https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_form\_FORM\_ID\_alter/7.x

---
Tags: entities, forms
---


# Question
Title: Loading third party PHP SDK library from a custom module drupal 7
I am writing a custom drupal module (my first one in my life), and I am trying to load an external library (https://github.com/jwilsson/spotify-web-api-php), and until now I used these methods:

1. Loaded file array in info file

files\[\] = spotify-web-api-php/vendor/autoload.php,spotify-web-api-php/src/Request.php,spotify-web-api-php/src/Session.php,spotify-web-api-php/src/SpotifyWebAPI.php,spotify-web-api-php/src/SpotifyWebAPIException.php
2. I made this function based on another answers here (Copied the library in libraries folder)

function blve\_spotify\_registry\_files\_alter (&$files, $modules) { if (!class\_exists('SpotifyWebAPI\Session')) { $library\_path = function\_exists('libraries\_get\_path') ? libraries\_get\_path('spotify-web-api-php') : 'sites/all/libraries/spotify-web-api-php';

```
$files[$library_path . '/vendor/autoload.php'] = array(
  'module' => 'blve_spotify',
  'weight' => 0,
);

```

} }
3. I used require\_once but will only work on one function

None of these methods worked, when I made a function to call all the loaded files any of the methods or files I need are loaded, please help me to made it work with the required php files. Thanks in advance

# Answer
> 1 votes
Use libraries module to load 3rd party dependencies (easier way), or composer manager to load composer package (better way).

Here you can find some details and examples how to start with libraries module.

# Answer
> 0 votes
Instead of

```
files[] = spotify-web-api-php/vendor/autoload.php,spotify-web-api-php/src/Request.php,spotify-web-api-php/src/Session.php,spotify-web-api-php/src/SpotifyWebAPI.php,spotify-web-api-php/src/SpotifyWebAPIException.php

```

Try:

```
files[] = spotify-web-api-php/vendor/autoload.php
files[] = spotify-web-api-php/src/Request.php
files[] = spotify-web-api-php/src/Session.php
files[] = spotify-web-api-php/src/SpotifyWebAPI.php,
files[] = spotify-web-api-php/src/SpotifyWebAPIException.php

```

# Answer
> 0 votes
in Drupal 7 i used to do a quick & dirty way, surely it's not recommended, but perhaps can help you or give you inspiration:

*In the following example i load a class called Carbon*

1. create a function, i.e. : `_get_carbon()`

function \_get\_carbon() {

```
$carbon_path = function_exists('libraries_get_path') ? libraries_get_path('Carbon') : 'sites/all/libraries/Carbon';
$c = $carbon_path . '/src/Carbon/Carbon.php';
require($c);
$GLOBALS['carbon'] = new Carbon\Carbon();

```

}

2. everytime you need this class, call that function `_get_carbon()`, you'll find the class at `$GLOBALS['carbon']`

---
Tags: files, theming
---


# Question
Title: Error: Cannot redeclare class becuase of entity self reference
I've got 2 problems here.

I have an entity that references itself in field definition (see below).

Problem No.1. I've got a fatal error `PHP Fatal error: Cannot redeclare class Drupal\mymodule\MyEntity` when trying to install the module.

Problem No.2 I now get it every time even when I remove the referencing field and do `drush cr` unless I wrap the class definition in `!class_exists()`.

I swear this is the only file defining the class.

Is there a way to clean this out of wherever drupal has stored it?

And how do I declare this type of self-reference?

```
<?php

namespace Drupal\mymodule;

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

/**
 * @ContentEntityType(
 *     id = "myentity",
 *     label = "My Entity",
 *     base_table = "myentity"
 * )
 */
class MyEntity extends ContentEntityBase
{
    public static function baseFieldDefinitions(EntityTypeInterface $entity_type)
    {
        $fields = [];

        // Standard field, used as unique if primary index.
        $fields['id'] = BaseFieldDefinition::create('integer')
            ->setLabel(t('ID'))
            ->setReadOnly(true);

        $fields['myentity_id'] = BaseFieldDefinition::create('entity_reference')
            ->setTargetEntityTypeId('myentity');

        $fields['name'] = BaseFieldDefinition::create('string');

        return $fields;
    }
}

```

# Answer
> 1 votes
Ok so the problem was in the namespace:

```
namespace Drupal\mymodule;

```

From my observation (can't find this in the Entity API documentation entities are supposed to be placed in the src/Entity (which I did) which imposes the `Entity` namespace. So fixing the namespace solved my issue.

```
namespace Drupal\mymodule\Entity;

```

What a stupid way to spend a half of a day. Looks like I'm too used to class loaders that will simply not find the class if you place it in the wrong directory.

---
Tags: 8
---


# Question
Title: How to show the author of Blocked users's Content as anonymous in Drupal 7?
I have a Content type Board. All authenticated users can add boards. when i displaying the Board's Nodes i am also showing the author name. All going good. But when a user delete his account i set his status as blocked. If a user has been blocked then i want to show Anonymous author on board's node created by that blocked user. I searched here and there but could not find solution. Any Help please Thanks in Advance.

# Answer
> 1 votes
And finally, i solved it by following code:

```
    <?php $author= user_load($uid); ?>
<?php if ($display_submitted): ?>
<span class="submitted">

<!-- For blocked user set the user name as Anonymous -->
  <?php if(user_is_blocked($author->name)): ?>

    <span> <a href="#" title="" class="username" ><?php print t('Anonymous'); ?></a></span>

  <?php else: ?>

    <?php print($user_picture); ?>
    <?php print($submitted);?>

  <?php endif;?>
</span>
<?php endif; ?>

```

thanks

# Answer
> 4 votes
You may use

```
function theme_username($variables)

```

https://api.drupal.org/api/drupal/includes%21theme.inc/function/theme\_username/7.x

$username = $variables\['name'\];

Check if user blocked

```
$variables['name'] = 'anonymous';

```

---
Tags: 7, nodes, users
---