# Question
Title: How to limit and enable Commerce shipping options based on the customer's country?
Very simple use case, using only flat rate shipping, with version 2 of Drupal Commerce Shipping and Drupal Commerce Flat Rate. I have two shipping options customers can choose between if they are in one country (the UK) and two if they're in any other country. Let's call them:

* UK standard
* UK special
* International standard
* International special

I've looked for ways to switch shipping rates on and off using rules, but all I can find is rules that *apply* a particular shipping rate, not rules which enable or disable *options* that the customer can then choose between.

This related question gives a faint outline of how to *apply* rates, but not how to enable or disable options, and likewise this related question, where there are 12 options but all are chosen *for* the customer (and the answers simply say "use rules"). Under the Calculation Rules tab under `admin/commerce/config/shipping/services/flat-rate`, I can't see anything in the "actions" list that looks like it enables or disables a particular rate. Plenty that appear to apply a rate, but not giving the customer a choice or limiting the choice.

This is clearly common and possible, as it's referred to for example in this issue, but I can't find anything on how to do it.

I've tried adding a rule like this through "Configure component" for a particular shipping rate, but it had no effect, the international rate still appears as an option even if the country is "United Kingdom". Here's the rule:

Here's another I tried using "Calculation rules" which, also had no effect:

Everything I can find around enabling or disabling shipping by country is about disabling countries *completely*.

I couldn't find anything in the Commerce Shipping documentation, and there is no Flat Rate documentation.

# Answer
The two crucial pieces of information:

* The **"Configure component"** link alongside each shipping rate under `admin/commerce/config/shipping` (Store \> Configuration \> Shipping) is the place to set validation criteria for a shipping rate to appear as an option.
* In these rules, countries need to be inputted as **two-letter country codes** not the full names.

---

In detail:

* Set up the shipping rates and go to `admin/commerce/config/shipping` (Store \> Configuration \> Shipping)
* For each one:
    + Follow the "Configure Component" link
    + "Add condition"
    + Commerce Order \> Order Address Component Comparison
    + Address value = Shipping Address, Address Component = Country, and tick the Negate box at the very bottom if this is one for "everywhere but" (e.g. international rates)
    + Input the 2-letter country code under Value. You can see what this is by using Inspect Element on a country selector dropdown:
> 2 votes

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


# Question
Title: Get nodes by content type when type key is not in root of nodes array
I am trying to get all nodes by content type. When the key is in the root of nodes array, like `[type]` I can easily retrieve it by, for example:

```
$nodes = node_load_multiple(array(), array('type' => 'page'));

```

But how do I do it when the key is not in the root, like:

```
    [title] => Test 1
    [status] => 1
    [comment] => 0
    [promote] => 0
    [sticky] => 0
    [nid] => 24
    [type] => page
    ...
    [field_worktype] => Array
            (
                [und] => Array
                    (
                        [0] => Array
                            (
                                [value] => some_value
                            )

                    )

            )
   ...

```

So, in the above example, how do I get nodes which `[field_worktype][und][0][value]` equals "some\_value"?

# Answer
With an `EntityFieldQuery`:

```
$query = new \EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->propertyCondition('type', 'page')
  ->fieldCondition('field_worktype', 'value', 'foo');

$result = $query->execute();
if (!empty($result['node'])) {
  $nodes = node_load_multiple(array_keys($result['node']));
}

```

As an aside, the method in your OP (using the `$conditions` array) is deprecated in favour of `EntityFieldQuery` anyway, which can perform the same filters.
> 1 votes

---
Tags: nodes
---


# Question
Title: Understanding the source of a 'Failed to get available update data' errors
When manually checking module updates for a customer site all modules update OK (and are updating fine) but there is an error saying "Failed to get available update data for 2 projects."

I suspect this is due to a custom theme and/or module that cannot update but with quite a few modules on this site. How can I identify what these "2 projects" are? I can't see anything on the admin site. I tried drush with pm-update with verbose and debug but can't see anything.

I'm assuming once identified that the next step would be to lock those modules.

# Answer
If I get your question right, I would suggest the following on a terminal:

```
drush pm-updatestatus 2>&1 | grep "No release history" -B1

```

This should give you all the projects (modules and themes) that you are looking for.

Cheers!
> 1 votes

---
Tags: updating
---


# Question
Title: What is the parent name for the admin menu?
what is the parent name for the admin menu ? if I put system.admin\_structure in the mymodule.links.menu.yml file as below, it places the new menu item under the structure tab on the menu. How do I get it on the first level of the menu.? mymodule.demo:

```
title: Demo Link
  description: 'This is a demo link'
  parent: system.admin_structure
  url: 'internal:/taxonomy/term/3'
  //route_name: entity.taxonomy_vocabulary.overview_form
  menu_name: admin
  weight: -79

```

# Answer
parent:system.admin is the answer , obvious wasn't it.
> 0 votes

---
Tags: 8
---


# Question
Title: Painfully slow, Devel Query logs show culprit
I have been having a few problems with one of my clients site. Its a big site, theres a few thousand nodes, 10k users, and it holds large images galleries with 100+ images that are 500kb each.

At its slowest, the average page load is 45 seconds!! And the worst i when you are logged in.

After enabling devel query logs, this one stands out as the worst...

**3923.69 ms** 1 node\_tag\_new P A INSERT INTO history (uid, nid, timestamp) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2)

Thats the first page load, the second is much much worse....

**65594.921 ms** node\_tag\_new P A UPDATE history SET timestamp=:db\_update\_placeholder\_0 WHERE ( (uid = :db\_condition\_placeholder\_0) AND (nid = :db\_condition\_placeholder\_1) )

What is the history table? Any idea why it is taking so long to run the query?

# Answer
> What is the history table?

This is a table for keeping track of what user has read what node. (To show a new/updated message next to it.)

> Any idea why its taking so long to run the query?

This could be anything, and might be at the server level (not related to Drupal).

First, check if SQL is slow outside Drupal (eg. PHPmyadmin). Run the same query, see what happens.

If SQL is still slow and you have ssh access to the server, try to run some disk speed checks using `sudo hdparm -Tt /dev/sda` and `dd if=/dev/zero of=/tmp/output bs=8k count=10k; rm -f /tmp/output` (assuming Linux). I had a slow site recently that was caused by a malfunctioning hard drive.
> 2 votes

---
Tags: 7, debugging
---


# Question
Title: Batch operation keeps looping after completion
The batch operation I created works fine, until it's done. Once it's done it just loops back and does it again. It will loop through until the VM runs out of resources.

I am fairly certain this has to do with my `completeImport` method. If I throw a syntax error in there it will finish the import successfully but then error out once it gets to that method.

The controller for the batch op: (I ommited methods that had nothing to do with the batch itself. They were for CRUD or building URLs.)

```
class MyModuleController {

  public function import() {
    $endpoints = array(
      'courses' => $this->getEndPoint('courses', NULL),
    );

    foreach ($endpoints as $data_type => $endpoint) {
      $response = $this->getResponse($endpoint);
      $operations = MyModuleController::processResponse($response, $data_type);

      $batch = array(
        'title' => 'Importing ' . $data_type,
        'operations' => $operations,
        'finished' => 'mymodule_complete_import',
        'init_message' => t('Importing...'),
        'progress_message' => t('Operation @current out of @total.'),
        'error_message' => t('Batch failed.'),
        'file' => drupal_get_path('module', 'mymodule') . '/mymodule.import.inc',
      );

      batch_set($batch);

      return batch_process('academy/courses/import');
    }

    return array(
      '#type' => 'markup',
      'value' => t('Imported?'),
    );
  }

  public static function processResponse($response_data, $data_type) {
    $operations = array();

    foreach ($response_data as $data) {
      switch ($data_type) {
        case 'courses':
          // Used to look up if a course was already imported.
          $id = (string) $data->Id;

          $data_array = array(
            'Name'                      => (string) $data->Name,
            'Active'                    => ((string) $data->Active == 'true' ? 1 : 0),
            'CourseCodeForBulkImport'   => (string) $data->CourseCodeForBulkImport,
            'EcommerceLongDescription'  => (string) $data->EcommerceLongDescription,
            'EcommerceShortDescription' => (string) $data->EcommerceShortDescription,
            'ForSale'                   => ((string) $data->ForSale == 'true' ? 1 : 0),
            'Code'                      => (string) $data->Code,
            'Id'                        => $id,
            'OriginalId'                => (string) $data->OriginalId,
            'Price'                     => (string) $data->Price,
            'Description'               => (string) $data->Description,
          );

          break;
      }

      $operations[] = array(
        'mymodule_response_importer',
        array($id, $data_array, $data_type),
      );
    }

    return $operations;
  }

  public static function completeImport() {
    return new RedirectResponse(Url::fromRoute('system.admin_content'));
  }

}

```

mymodule.import.inc:

```
function mymodule_response_importer($id, $data, $data_type, &$context) {
  $entity = MyModuleController::findExisting($data_type, $id);

  switch ($data_type) {
    case 'courses':
      if ($entity === FALSE) {
        MyModuleController::createNode($data);
      }
      else {
        MyModuleController::updateNode($data, NULL, $entity);
      }

      break;
  }
}

function mymodule_complete_import() {
  MyModuleController::completeImport();
}

```

# Answer
> 0 votes
I was able to fix it by using the magic `send()` method for `RedirectResponse` class and building a full URL (mostly) manually.

```
  public static function completeImport() {

    $url = $GLOBALS['base_secure_url'];
    $url .= $GLOBALS['base_path'];
    $url .= Url::fromRoute('system.admin_content')->getInternalPath();
    $url .= '?status=All&type=academy_webinar&title=&langcode=All';

    $redirect = new RedirectResponse($url);

    $redirect->send();
  }

```

---
Tags: 8, batch-operations, page-controller
---


title: How do I update all nodes?

text:
# Question
Title: How do I update all nodes?
I have a custom module which creates a new field with a computed value, which I need to update.
How do I bulk update my nodes for a specific content type?

# Answer
This is just a suggestion, its not well designed solution.

Considering that you already added your field to a Node type and you need update its value...

You can create a function that loads all nodes with specific type:

```
$articles = \Drupal::entityManager()->getStorage('node')->loadByProperties(array('type' => 'article'));;

```

And use a foreach to update your field content:

```
foreach ($articles as $nid => $article) {
  //Change what you need
  //Save your changes
}

```

Now, just run this once, on a new module install function or whatever you want.
> 1 votes

---
Tags: nodes, entities, 8
---


title: How do I change the default theme?

text:
# Question
Title: How do I change the default theme?
I've installed a premium theme in a Drupal 8.1.0. Each time I log in, the site crashes with the the following message.

> An unknown error has occurred.

I then tried to change the default theme using `drush vset bartik` to change the theme for non administrative pages back to the Bartik theme.

I got this error.

> Command variable-set requires Drupal core version 6 or 7 to run.
> The drush command 'vset bartik' could not be executed.

How should I change the default theme with Drush?

# Answer
The correct command should be `drush config-set system.theme default bartik`.

You might need to clear or rebuild your CSS/JS and theme caches with `drush cr`. If the problem still persists, verify the theme hasn't been set in the settings.php file. A theme set in the settings.php file cannot be changed from the user interface.

### Reference
> 27 votes

---
Tags: 8, drush
---


# Question
Title: Custom module to show and store the current user's email address in the database
I'm currently learning myself Drupal module development. I finished a tutorial for showing "Hello World!" in a block. And now I'm trying to show the logged in user's email and make a button to save it in the database. But I have no idea on how to start coding this.

I'm trying to show the logged in user's email. I'm using something like this and make it clickable with a mailto;

As for the purpose of the block, it's the exercise I'm making. The block needs to show the logged in users email with a mailto function on it and a button that adds the email to a newly made database. I suppose this is just for the purpose of adding data to the database.

```
<?php
/**
 * @file
 * Contains \Drupal\email_module\Plugin\Block\EmailBlock.
 */
namespace Drupal\email_module\Plugin\Block;
use Drupal\Core\Block\BlockBase;
/**
 * @Block(
 *   id = "EmailBlock",
 *   admin_label = @Translation("Email Block")
 * )
*/
class EmailBlock extends BlockBase
{
/**
 * {@inheritdoc}
 */
    public function build() {
        global $user;
        return array(
        '#markup' => $this->t('!email' => theme('email', array('account' => $user))),
    );
    }
}

```

Any suggestions to help me set this up?

# Answer
Have a look at the Examples module. It contains well documented examples of many Drupal development techniques.

In your case the DBTNG (Database: The Next Generation) example will show how to get input from a form and save to the database.

To get the email of the current user depends on the version of Drupal you are using.

Under Drupal 7 there's a $user gloabl variable containing the logged in user object. So $user-\>mail will return the email address.

Under Drupal 8, you can use the Drupal::currentUser method to get the user object. Drupal::currentUser()-\>mail should return the email address.

On a form, you can set the defaultValue of form field to the email address and it will prepopulate your field.

Hope this helps!
> 0 votes

# Answer
The solution for showing the email was this in the Block file.

```
<?php

class HelloBlock extends BlockBase
{
/**
 * {@inheritdoc}
 */
    public function build() {
        $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
        $email = $user->get('mail')->value;
        return array(
        '#markup' => $this->t($email),
    );
    }
}

```
> 0 votes

---
Tags: 8, blocks
---


title: deadlock with cache clear

text:
# Question
Title: deadlock with cache clear
I am trying to clear the cache or view status reports in D7 i get the below error.

PDOException: SQLSTATE\[40001\]: Serialization failure: 1213 Deadlock found when trying to get lock; try restarting transaction: DELETE FROM {cache\_bootstrap} WHERE (cid = :db\_condition\_placeholder\_0) ; Array ( \[:db\_condition\_placeholder\_0\] =\> system\_list ) in cache\_clear\_all() (line 167 of /var/web/includes/cache.inc).

How do i fix the serialization error?

Thank you..

# Answer
> 2 votes
The Asynchronous Prefetch Database Query Cache module should handle it. If you want the longer version see How to get rid of Deadlocks and Lock time out type issues?

---
Tags: caching
---


# Question
Title: Will I be able to install an old version when using Mysql 5.6 as database server?
Drupal 5 will go through all the install process with Mysql 5.6? Can even Drupal 5 work with Mysql 5.6?

I tried but tables were not created:

```
mysql> SHOW TABLES;
+-------------------+
| Tables_in_drupal5 |
+-------------------+
| cache_filter      |
| cache_menu        |
| cache_page        |
+-------------------+
3 rows in set (0,00 sec)

```

And apache logs throw a bunch of PHP warnings about Tables not existing:

```
    d May 11 13:37:45.197241 2016] [:error] [pid 25342] [client 192.168.255.26:52348] PHP Warning:  Table 'drupal5.watchdog' doesn't exist\nquery: INSERT INTO watchdog (uid, type, message, seve$
[Wed May 11 13:37:45.198008 2016] [:error] [pid 25342] [client 192.168.255.26:52348] PHP Warning:  Table 'drupal5.watchdog' doesn't exist\nquery: INSERT INTO watchdog (uid, type, message, seve$
[Wed May 11 13:37:45.198664 2016] [:error] [pid 25342] [client 192.168.255.26:52348] PHP Warning:  Table 'drupal5.watchdog' doesn't exist\nquery: INSERT INTO watchdog (uid, type, message, seve$
[Wed May 11 13:37:45.199119 2016] [:error] [pid 25342] [client 192.168.255.26:52348] PHP Warning:  Table 'drupal5.watchdog' doesn't exist\nquery: INSERT INTO watchdog (uid, type, message, seve$
[Wed May 11 13:37:45.199934 2016] [:error] [pid 25342] [client 192.168.255.26:52348] PHP Warning:  Table 'drupal5.watchdog' doesn't exist\nquery: INSERT INTO watchdog (uid, type, message, seve$
[Wed May 11 13:37:45.201507 2016] [:error] [pid 25342] [client 192.168.255.26:52348] PHP Warning:  Table 'drupal5.watchdog' doesn't exist\nquery: INSERT INTO watchdog (uid, type, message, seve$
[Wed May 11 13:37:45.202236 2016] [:error] [pid 25342] [client 192.168.255.26:52348] PHP Warning:  Table 'drupal5.watchdog' doesn't exist\nquery: INSERT INTO watchdog (uid, type, message, seve$
[Wed May 11 13:37:45.202980 2016] [:error] [pid 25342] [client 192.168.255.26:52348] PHP Warning:  Table 'drupal5.watchdog' doesn't exist\nquery: INSERT INTO watchdog (uid, type, message, seve$
[Wed May 11 13:37:45.203677 2016] [:error] [pid 25342] [client 192.168.255.26:52348] PHP Warning:  Table 'drupal5.watchdog' doesn't exist\nquery: INSERT INTO watchdog (uid, type, message, seve$
[Wed May 11 13:37:45.204913 2016] [:error] [pid 25342] [client 192.168.255.26:52348] PHP Warning:  Table 'drupal5.watchdog' doesn't exist\nquery: INSERT INTO watchdog (uid, type, message, seve$
$ile=default

```

And if a reload the page it says that Drupal is already installed and if a try to run update.php get a few more warnings

# Update

If i enter install.php i get this:

```
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
: Function ereg() is deprecated in /var/www/drupal5/includes/file.inc on line 646.
warning: syntax error, unexpected BOOL_TRUE in modules/comment/comment.info on line 3 in /var/www/drupal5/includes/module.inc on line 195.
warning: syntax error, unexpected BOOL_TRUE in modules/drupal/drupal.info on line 3 in /var/www/drupal5/includes/module.inc on line 195.
warning: syntax error, unexpected BOOL_TRUE in modules/node/node.info on line 3 in /var/www/drupal5/includes/module.inc on line 195.
warning: syntax error, unexpected BOOL_TRUE in modules/poll/poll.info on line 3 in /var/www/drupal5/includes/module.inc on line 195.

```

But after that it looks fine...

Tables were created

```
    mysql> SHOW TABLES;
+-------------------------+
| Tables_in_drupal5       |
+-------------------------+
| access                  |
| authmap                 |
| blocks                  |
| blocks_roles            |
| boxes                   |
| cache                   |
| cache_filter            |
| cache_menu              |
| cache_page              |
| comments                |
| file_revisions          |
| files                   |
| filter_formats          |
| filters                 |
| flood                   |
| history                 |
| menu                    |
| node                    |
| node_access             |
| node_comment_statistics |
| node_counter            |
| node_revisions          |
| node_type               |
| permission              |
| role                    |
| sequences               |
| sessions                |
| system                  |
| term_data               |
| term_hierarchy          |
| term_node               |
| term_relation           |
| term_synonym            |
| url_alias               |
| users                   |
| users_roles             |
| variable                |
| vocabulary              |
| vocabulary_node_types   |
| watchdog                |
+-------------------------+
40 rows in set (0,00 sec)

```

and i can enter my local site

# Answer
As reported in Database server \[requirements\], Drupal 5 supports MySQL 3.23.17 or higher, even if it is recommended to use MySQL 4.1. The first Drupal version to explicitly support MySQL 5 is Drupal 7, two major versions later. I doubt Drupal 5 has been updated to fully support MySQL 5, so there could be problems when using the two together, such as the one outlined in Error 1364 upon importing database.mysql with MySQL 5.0+.

More importantly, you could get more issues causes from using Drupal 5 with PHP 5 or higher versions, such us coding using deprecated functions, removed functions, or functions for which the parameters or the result changed. In fact, PHP \[requirements\] expressly states that Drupal 5 doesn't support PHP 5.3.

> Drupal 5 requires PHP 4.4.0 or higher. PHP 5.2 is recommended. Drupal 5.x does not support PHP 5.3.

This is about Drupal 5 core; for any third-party modules, there can be more issues. For example, some modules could not even fully support PHP 5.2, even if Drupal core recommends it.
> 1 votes

---
Tags: 5
---


title: How to create an 'Upload a file' field?

text:
# Question
Title: How to create an 'Upload a file' field?
I have a content entity type, and I would like to have an 'Upload file' field. I have declared the field in my Entity class

```
$fields['file'] = BaseFieldDefinition::create('file')
    ->setLabel(t('Upload a file'))
    ->setDescription(t('Choose file from your computer'));

```

And in EntityForm I am trying to set some settings, because I need to make this dependable later with the '#states'

```
$form['file'] = [
    '#title' => $this->t('File'),
    '#description' => $this->t('Upload a file from your computer'),
    '#type' => 'file',
    '#default_value' => $entity->file->value,
];

```

But at the moment the field is displayed, but I have problems on saving the form. The file is attached, but not getting uploaded and the error says:

> Fatal error: Call to a member function getValue() on a non-object in C:\A plus\drupalsite\core\modules\file\src\Plugin\Validation\Constraint\FileValidationConstraintValidator.php on line 18

# Answer
> 3 votes
```
 $form['File'] = array(
        '#type' => 'managed_file',
        '#title' => t('Choose  File'),
        '#upload_location' => 'public://MyFilesFolder/',
        '#default_value' => $entity->get('File')->value,
        '#description' => t('upload file'),
        '#states' => array(
          'visible' => array(
            ':input[name="File_type"]' => array('value' => t('Upload Your File')),
          ),
        ),
      );

```

---
Tags: entities, 8, files
---


# Question
Title: How can I make the label text on a Views Exposed Filter inline?
In Views 3, it's easy to make the labels of fields appear inline by adjusting the settings at `Format: Show: Settings`.

However, there appears to be no corresponding setting for Exposed Filters. I tried to do it myself in CSS, but adding:

`#edit-field-acc-gender-value-wrapper label`

gives me the horizontal alignment but not the vertical alignment, as you can see below:

How can I fix my CSS, or is there a better way to make the labels for Exposed Filters inline?

# Answer
> 1 votes
You may give a top margin to the label:

```
#edit-field-acc-gender-value-wrapper label{
margin-top: 5px;
}

```

It is not the best way but it will work.

# Answer
> 1 votes
I use the Compact Forms module. This will handle it with javascript, and works with any form - you simply configure the module with the ID of any forms you want it to apply to, e.g. user login, webforms etc.

http://drupal.org/project/compact\_forms

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


# Question
Title: Why is there a hash value at the end of this element ID?
I've created an entityreference to a content type that is just a title and an image, and set the storage settings to unlimited. Now, when I'm on the edit form and I click the "Add Another Item" button, the ID of the input that appears is: `edit-field-photo-1-target-id--nOP2UjZ0zuI`

Why is that `--nOP2UjZ0zuI` at the end, there? It makes it annoying to select, even though I'll be able to search for an ID that starts with edit-field-photo-X-target-id as a workaround, but what does it do?

# Answer
> 2 votes
Here is my guess:

In HTML ID's are suppose to be unique. Since you're adding another item, the ID cannot be the same. Thus, the `--nOP2UjZ0zuI` is probably some random generated string so the ID is unique.

---
Tags: 8
---


# Question
Title: Ionic Framework won't authenticate in browser (works in emulator)
I've set up a simple Ionic Framework app which utilises Drupal 7 Services API to authenticate a user, before hitting some custom end points to retrieve data when logged in.

The issue I'm seeing is when running `ionic serve` to view the app in the browser: `http://localhost:8100/#/auth/login`. I can successfully log in, but when requesting an endpoint, the user is not detected as authenticated.

1. Logging in successfully - see log debug:
2. However, when trying to access a custom end point - the user doesn't appear to be authenticated - the dblog reveals `Anonymous (not verified)`, thus returning `["Access denied for user anonymous"]` in the console. The dblog looks like so:

The odd thing is, if performing the *exact* same steps using POSTMAN or via the iOS emulator when running `ionic emulate ios` all works fine, see dblog now (this is when using emulator):

More info: I'm using the Drupal `CORS` module, with the following set up: `api/*|http://localhost:8100|*|Content-Type,X-CSRF-Token,Authentication, Origin, Cookie|true`

On each request I'm passing the `X-CSRF-Token`. I can't pass a `Cookie` as the console returns `'Refused to set unsafe header "Cookie"`

My `$http` request looks as follows:

```
  this.getEventFeed = function(csrf, payload) {
    var api = FetchGlobals.getUrl();
    var deferred = $q.defer();
    var req = {
     method: 'POST',
     url: api + '/api/rest/event_feed/feed.json',
     headers: {
      'X-CSRF-Token' : csrf,
      'Access-Control-Allow-Credentials' : 'true',
      // 'Cookie' : cookie,
      'Authentication' : cookie
     },
     data: payload,
     // json : true,
    }
    console.log(req);
    $http(req)
    .success(function(data, status, headers, config) {
      var response = {
        'ok' : true,
        'data' : data,
      };
      deferred.resolve(response);
    })
    .error(function(data, status, headers, config) {
      var response = {
        'status' : status,
        'data' : data,
      };
      deferred.resolve(response);
    });
    return deferred.promise;
  };

```

EDIT: It appears to be an issue with the Cookie. As recommended here: https://www.drupal.org/node/1133084#comment-8433677 \- I've added a new header called `Authentication`. I can see from the dblog the user is succesfully being authenticated, however, I receive the error `["CSRF validation failed"]`.

# Answer
> 2 votes
Incase someone faces a similar issue, I managed to find a fix by:

1. Setting up an `ionic proxy` see: http://blog.ionic.io/handling-cors-issues-in-ionic/
2. Sending the `Cookie` with the headers as `Authentication` to bypass the issue `'Refused to set unsafe header "Cookie`. Then adding this code on `hook_init()` https://www.drupal.org/node/1133084#comment-8433677.

---
Tags: 7, services
---


# Question
Title: Can I specify 'greater than' with db_delete()?
I am new to Drupal 8. I can use the following code to delete a record where salary == 45

```
$salary = 45;
$num_deleted = db_delete('test_table')
  ->condition('salary', $salary)
  ->execute();

```

Is it possible to specify a condition like "salary \>= $salary" with db\_delete() or I should use db\_query()?

# Answer
> 4 votes
You can see document Conditional clauses for 7 (**need update document**) or you can see the documentation for `QueryInterface`, in particular for `QueryInterface::condition()`.

> @param $operator Possible values: - '=', '\<\>', '\>', '\>=', '\<', '\<=',
>
> * 'STARTS\_WITH', 'CONTAINS', 'ENDS\_WITH': These operators expect $value to be a literal of the same type as the column.
> * 'IN', 'NOT IN': These operators expect $value to be an array of literals of the same type as the column.
> * 'BETWEEN': This operator expects $value to be an array of two literals of the same type as the column.

. In your case you can use:

```
$salary = 45;
$num_deleted = db_delete('test_table')
  ->condition('salary', $salary, '>=')
  ->execute();

```

---
Tags: database, 8
---


# Question
Title: How to use titles instead of IDs in urls for nodes?
I am managing a site right now (Drupal 6) and the links are all coming out in the form `http://example.com/blog/12553`.

I'd like these urls to be based on the name of the article. I could swear that the site used to do this, but not sure at all where to find this setting or what might have gone wrong. I was looking into 'clean urls' but conclude that the urls are clean (Because they don't have PHP parameters), but I'm not sure.

I'm pretty familiar with PHP and programming... less familiar with Drupal

# Answer
> 2 votes
You should check to see if the pathauto module is installed. If not, I highly recommend downloading, installing and enabling it... It should make very short work of this.

Here's the link for d6

https://www.drupal.org/node/17345/release?api\_version%5B%5D=87

If it is already enabled... then you may have more trouble as the d6 version is no longer maintained... so you may need to do some troubleshooting of this module.

---
Tags: 6, uri
---


# Question
Title: REST interface to custom entity type getting constant 403's
I created my module and the entity definition using the drupal console. It has not been modified at all. My entity is for a user but for various reasons I won't be using the pre existing user entity.

I installed restui, serialization, hal, basic auth. All working fine.

I have created a REST instance for my entity using the UI; POST & GET using json+hal and basic auth.

Using curl (and Postman) I can create and retrieve a node; I can also retrieve a custom user entity that I created through the UI. All the above was easy, no dramas, took no time at all.

Then it came to creating a custom user entity. No dice. I get persistent 403's and nothing in the message (and nothing logged in watchdog which is handy.)

The auth is using an admin account (in fact 2, I created a new one in a display of desperation); admin users have all permissions by default, but I did add extra permissions to authenticated role also in the off chance that it used that internally. (More desperation.)

I'm clearing the caches every 5 minutes also.

I have sent requests using the X-CSRF-Token header using a mix of fresh and old tokens (ie, requesting new ones before a full request and then trying old ones also). Anybody know how often we should be retrieving new tokens?

I've also tried with no tokens.

The issue is that I have no idea where this is falling over, so all I can do is flail my arms around in a vain attempt at hitting something useful (I'm sure this was a dungeons and dragons action?)

The body of my POST request has been changed also, but I'm not convinced that it would throw a 403 if incorrect, I'd assume a 'malformed' response would come back or at least a non 403. Can anybody confirm?

As my entity was created by the console and I can see all the CRUD permissions enabled on my admin roles, where can I go from here?

# Answer
> 1 votes
The answer is quite simple but easy to miss.

The URL I used when I made the GET request; `http://apps.dev/app/apps_user/1?_format=hal_json` is not the same as the URL required to make POST requests.

To make a POST request, you change it to `http://apps.dev/entity/apps_user?_format=hal_json`

None of the URL's in the returned `_links` property are correct for POST requests.

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


# Question
Title: Is it possible to show a view's page in the admin overlay?
I created a view with a page display, which has an path alias, say: node/\*/something/somethingelse Now I would like that, if someone clicks on a link leading to the above path, the view's page is shown in the admin overlay. I tried following:

```
function custom_api_admin_paths_alter(&$paths) {
  $path['node/*/something/somethingelse'] = TRUE;
}

```

But it does not work. What did I wrong?

# Answer
It may be a bit late and unfortunately I can not assist with your php script but you can try the Overlay Paths module which can achieve something similar to what you are trying to do.

It kind of did what I needed and I say kind of because it does not work that well with Views.
> 1 votes

# Answer
You can achieve that by `hook_admin_paths_alter` function

```
function YOURMODULE_admin_paths_alter(&$paths) {
  // Treats your view page as administrative.
  $paths[''node/*/something/somethingelse''] = TRUE;
   }

```

I remember, I've used the abouve method to achieve the same requirement.

Hope it helps.
> 0 votes

---
Tags: views, modal-dialogs
---


title: Dynamic Select Query On Another DB

text:
# Question
Title: Dynamic Select Query On Another DB
Is there a straightforward solution to do the dynamic select statements against another database on the same server? I fooled around with attempting to modify the documentation example to no avail.

```
// Create an object of type SelectQuery and directly
// add extra detail to this query object: a condition, fields and a range
$query = db_select('custom_module_db', 'table_foo')
  ->condition('table_foo.id', 0, '>')
  ->fields(array('id', 'field_1', 'field_2'));

$result = $query->execute();

```

My current database setup looks like this

```
AWS RDS Server
 ->production drupal database
   ->Drupal Installation Tables
 ->custom module database
   ->Custom Module Tables

```

Clarification the below method works fine against the custom module database without adding a specific settings reference for that particular database.

So was looking to see if I can use the db\_select() function in the same way as db\_query() without needing to go in and add another database reference.

```
 $data_set = db_query($query='SELECT * FROM custom_module.db.table_foo WHERE ......)

```

Then grabbing the resultset by

```
$results = $this->WeightedAverageFunction($data_set->fetchAll())

```

# Answer
Add external database name in settings.php(../sites/all/default/settings.php) file of your project. You can set databse in settings.php as follows:

```
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'drupal_db',
      'username' => 'root',
      'password' => '',
      'host' => 'localhost',
      'port' => '8080',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),

  'external' =>
  array (
    'default' =>
    array (
      'database' => 'external_db',
      'username' => 'root',
      'password' => '',
      'host' => 'localhost',
      'port' => '8080',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

```

And you can directly add your query in files.
> 1 votes

---
Tags: database, 8
---


# Question
Title: Is it possible to index custom page content?
I have created certain pages and blocks using web services programmatically.The content of those pages is fetched from outside the existing Drupal installation and they are not getting indexed in search results.

Is it possible to index my custom page titles and links in the search results? Or is there any other way to do this?

# Answer
> 0 votes
Yes of course you can. You can use the hook\_node\_update\_index() for this:

```
function YOURMODULE_node_update_index($node) {
   // here is an example that fetches content from an url and appends it to
   // to the data that will be indexed
   $ch = curl_init();
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
   curl_setopt($ch, CURL_URL, "http://example.com/readme.txt");
   $content = curl_exec($ch);
   curl_close($ch);

   // return the extra content that needs to be indexed for this node
   return $content;
}

```

The above will of course only work if your custom pages are stored as nodes in Drupal. For instance if you have a node that is called `contact` which shows content generated externally, then you need to fetch the same content in `hook_node_update_index()` for this specific node.

---
Tags: search
---


title: csrfToken: reget without logout user

text:
# Question
Title: csrfToken: reget without logout user
I have a site where I use AngularJS to connect to Services module paths.

Now, we know that I need to send (for every put connection) the CSRF token into headers request, and this token is linked to user's session id.

My problem is that some users are currently logged into the system for Drupal (I can see all content for authenticated users ) but when I send a PUT request, Drupal return me the error of invalid CSRF token.

So, how can I retrieve a new CSRF token without logout the user ?

M.

# Answer
To get the CSRF Token, do a GET on:

```
?q=services/session/token

```

Please note that 'services', is not the path to your endpoint, its a built in path provided by the Services module.

After grabbing the token, you then pass the token along in the header for any POST, PUT, and DELETE requests from authenticated users:

```
X-CSRF-Token=abcdefg123456789

```

jDrupal may be of use in this scenario as well, it's a JavaScript API for the Drupal Services module
> 1 votes

# Answer
You can also use jdrupal.js to perform number of operation on Drupal site using services module. Add npm install jdrupal. It will directly retrieve a new CSRF token without logout the user.
> 0 votes

---
Tags: 7, services, csrf
---


title: Ordering Table by column

text:
# Question
Title: Ordering Table by column
I try to add the possibility to order by column in the header of my table element.

I started to use Drupal 8 and I can't find any clear documentation about table on the API site to do what i want...

Thanks in advance.

# Answer
You have to do this while defining the header array like

```
$header = array(
     array(
       'data'  => t('Url'),
       'field' => 'd.path',
       'sort'  => 'asc',
     ),
     array(
       'data'  => t('Text'),
       'field' => 'd.text',
     ),
    );

```

So, this table will have two columns, Url & Text. And it will be sorted in ascending order by column Url.
> 0 votes

---
Tags: forms, 8
---


# Question
Title: Calling two namespaces for formbuilder and controller in d8
I have a d8 form as follows ,and am calling a new class by including the file in the formbuilder class , But its throwing me a class not found error ,although am including the class in the form builder and namespace in the calling class .

```
    namespace Drupal\module_name\Form;

    use Drupal\Core\Form\ConfigFormBase;
    use Drupal\Core\Form\FormStateInterface;
    use Drupal\Core\Form\FormState;

    //included class
    require_once './' . drupal_get_path('module', 'gasf') . '/includes/config_class.inc';

    class ClassName extends ConfigFormBase {

      public function getFormId() {
        return 'class_name';
      }
    /**
     * General form for switching all nodes from one user to another.
     */
      public function buildForm(array $form, FormStateInterface $form_state) {
      $Config = new ConfigClass();
      $operations = array(
          'IP -> vm name',
          'vm name -> IP',
      );

    $argument = empty($argument) ? '' : $argument;
    $operations = empty($operations) ? '' : $operations;

    $form['argument'] = array(
        '#type' => 'textfield',
        '#title' => t('Enter argument here'),
        '#default_value' => $argument,
        '#description' => t('Depending on operation: tcp/ip adress or vm name'),
    );

    $form['operation'] = array(
        '#type' => 'select',
        '#title' => t('Operation:'),
        '#options' => $operations,
        '#description' => t(''),
    );

    $form['submit_lookup'] = array(
        '#type' => 'submit',
        '#value' => t('Lookup'),
    );

    return $form;
}

```

and in the **`config_class.inc`** i have

```
namespace Drupal\module_name\Controller;
namespace Drupal\module_name\Form;

class ConfigClass {

}

```

But its calling the latest namespace only , that is when i use **`namespace Drupal\module_name\Form;`** its working properly , But it wont take effect the **`namespace Drupal\module_name\Controller;`** namespace .That will through error on calling the class from controller ! . How can i use the namespaces for both formbuilder and controller class ? Or is there any other workarounds ?

# Answer
A class can only be in one namespace. There's never a scenario when a class being in two namespaces could be useful, and the language doesn't allow it.

I have no idea what you're trying to achieve, there's no mention of that in your question, so again I'll just reiterate (3rd time now!) that you should learn what namespaces are, what autoloading is, what PSR4 is, and how to use them. Otherwise you're just going to spend your time banging your head against these trivial PHP language issues, and get very little done.
> 3 votes

---
Tags: 8
---


# Question
Title: Drupal integration with external binary program to convert an image?
Using Drupal 8. On a cloud based site, I have a program for converting images into svgs that takes, at times, a few hours of run time. I can easily run the external binary program (configured to run through java as a commandline). At the end I have the program spit out the relevant files. I need to integrate this with Drupal and am wondering the best procedures.

What do I use to grab the image and have an actual file on disk? How can I get the files back into drupal whenever this program finishes. I can easily add in commands to run after the program finishes, and can get the program to run with an exec() but how do I hook the rest of it up? A working proof of concept would be great. Even better if it could run on a spun up virtual computer on google cloud services.

# Answer
Not anything near a working proof of concept, but a hint in the right direction:

You could use FileEntities for the upload of the Files, for example via a FileField on a node.

In hook\_node\_insert() and or hook\_node\_update() you can get the path to the file in the filesystem via:

```
$file = $node->field_source->entity;
$path = FileSystem::realpath($file->getFileUri());

```

You could than trigger the execution of your external program. By using hook\_cron() you could regularly check for results. You could than attach the resulting file to the node like this

```
// Create FileEntity from a local file.
$uri  = file_unmanaged_move($path, 'public://'.$result_filename, FILE_EXISTS_RENAME);
$file = File::Create([
    'uri' => $uri,
]);
$file->save();
// Load node and attach the file.
$node = Node::load($nid);
$node->field_result->setValue([
    'target_id' => $file->id(),
]);
$node->save();

```
> 1 votes

---
Tags: 8, drush, media, cron, files
---


# Question
Title: Dependency injection not working custom form
I have a custom module with a form class, where I am trying to inject a custom service to use within it's submit method:

```
namespace Drupal\my_module\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\my_module\CustomManager;
use Symfony\Component\DependencyInjection\ContainerInterface;

class CustomForm extends FormBase{

  private $custom_manager;

  function __construct(CustomManager $custom_manager) {
    $this->custom_manager = $custom_manager;
  }

  public static function create(ContainerInterface $container) {
    return new static(
    // Load the service required to construct this class.
      $container->get('my_module.manager')
    );
  }

  .....

  public function submitForm(array &$form, FormStateInterface $form_state) {
      // Test service.
      $this->custom_manager->test();
  }

}

```

When I submit the form, I get the following error:

***Fatal error: Call to a member function test() on null***

It seems like my custom service hasn't been instantiated as expected, since the $custom\_manager property is null.

Strange thing is when I debug the constructor, the service ***IS*** being instantiated properly.

Has anyone had this issue before? I can instantiate the service via the global Drupal class, but apparently doing the dependency injection is best practice.

Thanks in advance!

# Answer
I **accidentally declared the $custom\_manager property** of my class as ***private*** instead of ***protected***, and that's why I was unable to access the custom manager object in the form submission method. Whoops!

MPD's answer is theoretically correct though, as class requiring to access services do need to implement the **ContainerInjectionInterface** class.

Worth noting though that the class **FormBase** which we're extending, ***already implements*** **ContainerInjectionInterface**, so we don't need to explicitly do so when creating a custom form.
> 12 votes

# Answer
Not 100% sure this is the problem, but anything with dependencies needs to implement `ContainerInjectionInterface` in one way or another (directly or inherited via the parent class). So, your problem is likely that you need to do

```
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;

class CustomForm extends FormBase implements ContainerInjectionInterface {
  // ...
}

```

That way it will be picked up via discovery by the `ClassResolver` and have the `::create()` method called. Just make sure you do a `drush cr` (or equivalent) to make sure everything gets wired up properly.
> 3 votes

---
Tags: forms, 8, dependency-injection
---


title: Admin links issue

text:
# Question
Title: Admin links issue
So if I am in my admin section

http://example.com/admin/content

and I try and click on

http://example.com/admin/structure

The url is

http://example.com/admin/admin/structure

I set the base\_url but it keeps happening, is there a setting somewhere (in the table or in the admin) where I can edit it?

The base url is

`$base_url = 'http://example.com';`

# Answer
And at the front of this problem is not present? If this problem only in the admin area, then you may have incorrectly configured htaccess or problem in a certain module. Because server settings I think this should not be, but it can be. Therefore, try to deploy the site on another server environments.
> 0 votes

---
Tags: navigation, uri
---


# Question
Title: Get a 404 page already when calling with trailing slash
My SEO agency complains about the following:

Let's assume the URL http://example.com/foo leads to a non-existing page. Then Drupal correctly responds with a 404.

Now,

The SEO agency says that this way I loose "crawl equity".

The **desired behaviour** would be that

What is the best way to achieve this?

# Answer
> 0 votes
Most likely you have a written rule htaссess 301 redirect. Possibly it is written in the code or via modules.

---
Tags: redirection, uri
---


# Question
Title: How do I get the content type name using code?
I'm working on Drupal 8 and I want to get content type machine name and label. Here is my code:

```
$cont_type = node_type_get_types();
foreach ($cont_type as $key => $value) {
  $label = $value->name;
  $machine_name = $key;
}

```

I get the following error message:

> Cannot access protected property `Drupal\node\Entity\NodeType::$name`

Hoe can I get the content type name?

# Answer
To get a property, there is `ConfigEntityBase::get()`. Since `ConfigEntityBase` is a base class for `NodeType`, you can always use `$value->get('name')` to get the value of the *name* property.
> 2 votes

# Answer
name is the label of the node type entity, so you can get that with `$node_type->label()`. That works for any entity type, if what you want is specified as the label key in the entity type annotation.
> 0 votes

# Answer
To get names of content type you can use below function

```
node_type_get_names();

```
> -1 votes

# Answer
```
$cont_type = node_type_get_types();
foreach ($cont_type as $key => $value) {
  $label = $value->get('name');
  $machine_name = $key;
}

```
> -1 votes

---
Tags: nodes, 8
---


title: load() a template file

text:
# Question
Title: load() a template file
I am developing a custom module which allows to bookmark nodes/taxonomy pages in ajax.

So far i can store in cookie via a custom module andsimple ajax code. I am now struggling in refreshing some div in my page. The "div" is actually a stand-alone file stored in my theme's template directory, whent trying to $.load it i get a 500 server error, must be colliding with the url-rewriting or simply the rights.

Is there a way to extract this file from the theme, Store it in the module, call it from my theme's header.tpl.php, And finaly, make it refresh when some jquery triggers ?

# Answer
Finaly i suceeded.

i just used jQuery.load to load the current page and load only the div i needed.
> 0 votes

---
Tags: ajax
---


# Question
Title: Exposed Filter Fulltext Search having the Searched fields as options along with the text box
I have created a exposed fulltext search filter with the searched fields\["tile", "Description","Keywords"\]. This brings the widget to the form as a textfield, which searches the input for all the three fields.

I'm trying to bring the searched fields\["title","Description","Keywords"\] to the form as a radio button list, So that the user can type the input and select under what field to refine the result.

Any help really appreciated!

# Answer
> 0 votes
I found a work around for this. We can create a radio button list in hook\_form\_alter() having the searched fields. Using hook\_search\_api\_views\_query\_alter(), we can alter the fields that are passed in the $query object, so that the result set is returned only for the field that is been searched.

```
function MYMODULE_search_api_views_query_alter(&$view, &$query) {
    if(isset($_GET['your_field_name'])) {
        switch($_GET['your_field_name']) {
            case 'field1':
                $fields = $query->getFields();
                $fields = array( 0 => 'field1_value');
                $query->fields($fields);
            break;
            .....
            .....
          }
        }
      }

```

---
Tags: views, search
---


# Question
Title: How to send a message notification based on a flagged node being linked via entity reference?
I'm trying to figure out how to make the following work: Sending notification based on flagged node being linked via entity reference.

I have a **'News'** content type and a **'Band'** content type, that has a flag called 'fan'. When somebody becomes a fan, I want them to receive a notification via the Message module whenever I link the band to the content type 'News' with the News article I just created.

The content-type setup is as follows:

* Node type 'News' has field: *Entity reference* to content type 'Band'
* The Band content type has a *flag called 'fan'*
* The Message type is called "**user notification center**" and has a field named *field\_mnc\_recipients*, which is an reference to a user(unlimited values)

How I want it to work:

* when a user flags the 'band' and a new article is referenced to the band, I want to notify them with the Message module,
* to make it work, I need to get the user from the flag for that band and insert it into the message field *field\_mnc\_recipients*.

I created a Rules Component as follows:

```
{ "rules_message_tes3" : {
"LABEL" : "message tes3",
"PLUGIN" : "rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules" ],
"USES VARIABLES" : {
  "referencing_node" : { "label" : "referencing_node", "type" : "node" },
  "referenced_node" : { "label" : "referenced_node", "type" : "message" }
},
"IF" : [
  { "node_is_of_type" : {
      "node" : [ "referencing-node" ],
      "type" : { "value" : { "bands" : "bands" } }
    }
  },
  { "entity_is_of_type" : { "entity" : [ "referenced-node" ], "type" : "message" } },
  { "entity_has_field" : { "entity" : [ "referenced-node" ], "field" : "field_mnc_recipients" } }
],
"DO" : [
  { "LOOP" : {
      "USING" : { "list" : [ "referencing-node:flag-fan-user" ] },
      "ITEM" : { "list_item" : "Current list item" },
      "DO" : [
        { "data_set" : {
            "data" : [ "referenced-node:field-mnc-recipients" ],
            "value" : [ "referencing-node:flag-fan-user" ]
          }
        },
        { "entity_create" : {
            "USING" : {
              "type" : "message",
              "param_type" : "user_notification_center",
              "param_user" : [ "site:current-user" ]
            },
            "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
          }
        }
      ]
    }
  }
]

```

} }

And now I got stuck, I based the component on "Sending a message to users of a flagged node when it is referenced" which is close to what I want.

# Answer
> 0 votes
It works, after days and days it finaly works! I used this as a base line for my research: Sending a message to users of a flagged node when it is referenced

Instead of sending an e-mail within the loop, i create a new entity(action), in this case the message notification. After that i fill(set data) in the entity-created:field-mnc-recipients field with the flagging users. This is how it works :)

---
Tags: 7, rules, flags, message-subscribe
---


# Question
Title: Is it possible to create a calculation field using database abstraction layer?
I am trying to work out if it is possible to write the following using Drupal's database abstraction layer. The tricky bit is the second field which is a function to calculate distance. Is it possible to include this calculation field `(3959 * acos(cos(radians(:lat)) * cos(radians(field_bluescope_geolocation_lat)) * cos(radians(field_bluescope_geolocation_lng) - radians(:lng)) + sin(radians(:lat)) * sin(radians(field_bluescope_geolocation_lat)))) AS distance` using the abstraction layer?

```
  $result = db_query_range('SELECT '
  . 'geo.entity_id, '
  . '(3959 * acos(cos(radians(:lat)) * cos(radians(field_bluescope_geolocation_lat)) * cos(radians(field_bluescope_geolocation_lng) - radians(:lng)) + sin(radians(:lat)) * sin(radians(field_bluescope_geolocation_lat)))) AS distance '
  . 'FROM '
  . 'node__field_bluescope_geolocation AS geo '
  . 'INNER JOIN '
  . 'node__field_bluescope_consumer_supp AS consumer_supp '
  . 'ON '
  . 'geo.entity_id = consumer_supp.entity_id '
  . 'WHERE '
  . 'geo.bundle = \'bluescope_business\' '
  . 'AND '
  . 'consumer_supp.field_bluescope_consumer_supp_target_id = 28 '
  . 'ORDER BY distance', 0, 200, [':lat' => $lat, ':lng' => $lng]);

```

# Answer
Yep Haversine should work without a problem. This is slightly modified from a production site which is up and working right now, for example:

```
$lat = 51.5014;
$lng = 0.1419;

$query = db_select('field_geo_latitude', 'f')
  ->fields('f', array('entity_id'))
  ->orderBy('distance');

$earth_radius = 3959;
$expr = "(
  $earth_radius * acos(
    cos(radians(:lat))
  * cos(radians(field_geo_latitude))
  * cos(radians(field_geo_longitude) - radians(:lng))
  + sin(radians(:lat))
  * sin(radians(field_geo_latitude))
  )
)";
$query->addExpression($expr, 'distance', array(':lat' => $lat, ':lng' => $long));

$query->having('distance <= :radius', array(':radius' => 10));

```

Resulting query:

```
SELECT f.entity_id AS entity_id, (
  3959 * acos(
    cos(radians(:lat))
  * cos(radians(field_geo_latitude))
  * cos(radians(field_geo_longitude) - radians(:lng))
  + sin(radians(:lat))
  * sin(radians(field_geo_latitude))
  )
) AS distance
FROM {field_geo_latitude} f
HAVING  (distance <= :radius)
ORDER BY distance ASC

```

When executed all the parameters are replaced as expected.
> 4 votes

---
Tags: 7, database
---


title: Image orientation

text:
# Question
Title: Image orientation
I try to fit portrait and landscape images to one size for Drupal 8. When I set image style (scale and crop 280x220) portrait images are automatically rotated. Then I tried to install Image effects module, but there is not choice Aspect switcher like in ImageCache Actions module for older Drupal. Do you know how to do it? Thank you.

# Answer
> 0 votes
Strange, but it should all work with this module. On this page you can read about this module http://janezurevc.name/image-effects-module-for-drupal-8

---
Tags: 8, media
---


# Question
Title: How to add menu items to system.admin_content parent?
`parent: system.admin_content` route handles `/admin/content` path. I'm trying to add more items to the menu tabs visible on that page.

So I'm doing this:

```
# test.routing.yml
entity.admin.test:
  path: '/admin/content/test_entity'
  defaults:
    _entity_list: 'test_entity'
    _title: 'Test entities'
  requirements:
    _permission: 'administer content types'

# test.links.menu.yml
test.admin:
  title: Test entities
  route_name: entity.admin.test
  # I have also tried using route defined in my entity type annotation
  # route_name: entity.test_entity.collection
  parent: system.admin_content
  description: 'List and edit site test entities.'

```

The route works (I can access page at `/admin/content/test_entity`), but menu item is not displayed. If I change parent to for example `system.admin_structutre` then the menu item is shown on `/admin/structure` list without problems.

# Answer
> 1 votes
> `Dont` use `test.links.menu.yml` instead use `test.links.task.yml`

in `test.links.task.yml` try the below code...

```
entity.admin.test:
  title: 'Test entities'
  route_name: entity.admin.test
  description: 'List and edit site test entities.'
  base_route: system.admin_content

```

---
Tags: 8
---


title: Don't apply sort criteria by default

text:
# Question
Title: Don't apply sort criteria by default
I added sort criteria by price to my catalog view, and in the sort criteria I have only to option to use by default one of them - Ascending or Descending. But I don't want to use any sorting by price by default in catalog, I would like to apply it (one of the option Ascending or Descending) only after user chose an option and pressed button 'Apply' on the sort form. Is there any opportunity to do that?

# Answer
> 2 votes
What would be removed from the directory by default sorting, you need to remove from Sort criteria. And leave the possibility of the sort only Filter criteria

# Answer
> 2 votes
You would need to remove the sort criteria that you have added. Once you remove that, that only the expose filter would work and you would be able to sort the content on the basis of what the user has selected in the Expose filter.

Hope that this help.

---
Tags: 7, views
---


# Question
Title: White screen of death in hook form alter
I have enabled simplenews module in drupal 8 and I am trying to reduce the width of input field from **60** to **30**. I am trying to implement form alter hook and have devel module installed. I used dsm($form\_id); to identify form and then in order to identify the form attribute to change, I tried to use dsm($form), dpm($form) and print\_r($form) and all these are giving white screen of death.

```
function custom_newsletter_form_alter(&$form,  $form_state, $form_id) {
  if ($form_id == 'simplenews_subscriptions_block_2138c21c-6453-4b7d-92d6-9407e427a78a') {
    dsm($form);
    dpm($form);
    print_r($form);
  }
}

```

I have tried different drupal 8 installations both localhosted and web hosted, tried with different themes but I am not able to print form. Is there any other way to identify/target correct form attribute to change like DOM inspecter of firebug?

# Answer
> 1 votes
It seems that `dsm()` and `dpm()` are not supported in Drupal 8. They are replaced by `kint()`. I have enabled the devel kint sub-module and used `kint($form)` to print my form array. You can also use `ksm($form)`.

# Answer
> 0 votes
You can use `\dpm($form)` as per OOP because devel is in a different namespace.

---
Tags: forms, debugging
---


# Question
Title: get menu link Page Settings from View configuration
When I have a node on the main menu, I can find its Menu Settings with an `entityQuery` on the content entity for its menu link, for example:

```
$system_uri = "entity:node/42";
$query = \Drupal::entityQuery('menu_link_content')
  ->condition('menu_name', 'main')
  ->condition('link.uri', $system_uri);
$result = $query->execute();
$menu_link_id = reset($result);
$menu_link = MenuLinkContent::load($menu_link_id);

```

... then get the Menu Link Title and Parent Item with these methods from the relevant class:

```
$menu_link_title = $menu_link->getTitle();
$menu_link_parent = $menu_link->getParentId();

```

I can't do the same thing with a view. Even an `entityQuery` of all `menu_link_content` entities on the `main` menu doesn't return views that are on that menu: only nodes and taxonomy term entities.

And I can't see these settings in what I believed would be the corresponding configuration entity for a View, for example:

```
$view_id = 'frontpage';
$query = \Drupal::entityQuery('view')
  ->condition('id', $view_id);
$result = $query->execute();
$view_id = reset($result);
$view = \Drupal::service('entity.manager')->getStorage('view')->load($view_id);

```

The resulting `Drupal\views\Entity\View` object doesn't look like it has any properties or methods to access the configuration data in the Views UI, specifically the Menu Link Title and Parent under *Page Settings*. What is the correct way to extract this information?

# Answer
The menu tree is built from two sources, menu link content and menu config. For views you find the menu configuration in each view. There are several ways to access this information. You can use the config api to read the values in php, export the view to a yml file and inspect it or use drush.

For example to show the view for block content with drush:

```
drush cedit views.view.block_content

```

This contains this configuration for the page:

```
 page_1:
    display_plugin: page
    id: page_1
    display_title: Page
    position: 1
    display_options:
      display_extenders: {  }
      path: admin/structure/block/block-content
      menu:
        type: tab
        title: 'Custom block library'
        description: ''
        parent: block.admin_display
        weight: 0
        context: '0'
        menu_name: admin
    cache_metadata:
      max-age: 0
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - url
        - url.query_args
        - user.permissions
      tags: {  }

```

After inspection the structure of this array you can use the configuration api to access it in php:

Simple Configuration API
> 0 votes

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


# Question
Title: Relationship between node and other nodes related by node reference to same parent
I've been stuck on this all day and I need help.

I have a video node that has a relationship (node reference) with a playlist node.

There are multiple videos referencing that playlist and there are multiple playlists.

Now here is my issue...

I have my node that plays my video and a view that lists all other videos in the same playlist to the bottom of the node. The views display plugin i'm using is EVA: Entity Views Attachment. This works apart form the fact I don't know now to filter it to only show a list of videos that are in the same playlist (referencing the same playlist node). I am able to get the ID or tokens (eg: field\_video\_playlist) from the video node and pass as an argument but when I setup contextual filter and relationships in the EVA view it returns nothing.

Without the contextual filter and relationship in the view it returns ALL videos.

Any help with this would be very much appreciated.

C

# Answer
Start with a view that lists `Content` of type `video`.

In the ENTITY CONTENT SETTINGS use:

```
Entity type: Node
Bundles: Video
Arguments: Use the ID of the entity the view is attached to.

```

This adds the EVA field to all nodes of type Video and provide the node id to Views. I suppose you have gotten about this far.

Now add a contextual filter to the View, and choose the `Content: nid`. This value will be populated by EVA as just specified in the arguments. This makes the view aware of the node we are currently viewing. If you want to hide the current node from the playlist, you can select `exclude` hidden behind the `more` fieldgroup.

Then add a relationships from the playlist back to the video called `Entity Reference: Referencing entity`.

This includes all other video nodes associated with the same playlist in the view.

As you can see in my preview, when I view Video 1 (node id 2 because 1 was for the playlist), I see the other 2 videos in the playlist (I chose to hide the current node in the contextual filter).

If you DO want to include the current video in the view (you left `exclude` unchecked) it becomes a bit more complicated as you will need to use an extra relation: `Entity Reference: Referenced entity`. Then alter the other reference to use the reference of this one (you might have to change the order).

Then make sure all your fields and filter make use of the last relationship, so they display the title of the attached nodes and not the title of the initial node. It should look something like this:
> 1 votes

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


# Question
Title: Cannot change an existing field's type. in field_update_field() line 240 of field.crud.inc
My instance of drupal is throwing an error. The file that is throwing the error is `modules/field/field.crud.inc`

The error is

> FieldException: Cannot change an existing field's type. in field\_update\_field() (line 240 of modules/field/field.crud.inc).

A local var dump displays the following results.

Variable `$field`

```
array (
  'active' => 1,
  'cardinality' => 1,
  'deleted' => 0,
  'entity_types' =>
  array (
  ),
  'field_name' => 'field_address',
  'foreign keys' =>
  array (
    'format' =>
    array (
      'columns' =>
      array (
        'format' => 'format',
      ),
      'table' => 'filter_format',
    ),
  ),
  'indexes' =>
  array (
    'format' =>
    array (
      0 => 'format',
    ),
  ),
  'locked' => 0,
  'module' => 'text',
  'settings' =>
  array (
    'max_length' => 255,
  ),
  'translatable' => 0,
  'type' => 'text',
)

```

Variable `$prior_field`

```
array (
  'translatable' => '0',
  'entity_types' =>
  array (
  ),
  'settings' =>
  array (
  ),
  'storage' =>
  array (
    'type' => 'field_sql_storage',
    'settings' =>
    array (
    ),
    'module' => 'field_sql_storage',
    'active' => '1',
    'details' =>
    array (
      'sql' =>
      array (
        'FIELD_LOAD_CURRENT' =>
        array (
          'field_data_field_address' =>
          array (
            'country' => 'field_address_country',
            'administrative_area' => 'field_address_administrative_area',
            'sub_administrative_area' => 'field_address_sub_administrative_area',
            'locality' => 'field_address_locality',
            'dependent_locality' => 'field_address_dependent_locality',
            'postal_code' => 'field_address_postal_code',
            'thoroughfare' => 'field_address_thoroughfare',
            'premise' => 'field_address_premise',
            'sub_premise' => 'field_address_sub_premise',
            'organisation_name' => 'field_address_organisation_name',
            'name_line' => 'field_address_name_line',
            'first_name' => 'field_address_first_name',
            'last_name' => 'field_address_last_name',
            'data' => 'field_address_data',
          ),
        ),
        'FIELD_LOAD_REVISION' =>
        array (
          'field_revision_field_address' =>
          array (
            'country' => 'field_address_country',
            'administrative_area' => 'field_address_administrative_area',
            'sub_administrative_area' => 'field_address_sub_administrative_area',
            'locality' => 'field_address_locality',
            'dependent_locality' => 'field_address_dependent_locality',
            'postal_code' => 'field_address_postal_code',
            'thoroughfare' => 'field_address_thoroughfare',
            'premise' => 'field_address_premise',
            'sub_premise' => 'field_address_sub_premise',
            'organisation_name' => 'field_address_organisation_name',
            'name_line' => 'field_address_name_line',
            'first_name' => 'field_address_first_name',
            'last_name' => 'field_address_last_name',
            'data' => 'field_address_data',
          ),
        ),
      ),
    ),
  ),
  'foreign keys' =>
  array (
  ),
  'indexes' =>
  array (
  ),
  'id' => '132',
  'field_name' => 'field_address',
  'type' => 'text',
  'module' => 'text',
  'active' => '1',
  'locked' => '0',
  'cardinality' => '1',
  'deleted' => '0',
  'columns' =>
  array (
    'value' =>
    array (
      'type' => 'varchar',
      'length' => NULL,
      'not null' => false,
    ),
    'format' =>
    array (
      'type' => 'varchar',
      'length' => 255,
      'not null' => false,
    ),
  ),
)

```

# Answer
> 1 votes
This is my solution to this problem, i'm going to also document how I found the solution.

If you see the message that something went wrong stop and look at the logs that Drupal reports back to you and take the time to read them.

In this example I was getting this error due to a specific module and when Drupal was faulting out the module `basic_cart_order` was the last one to be rebuilding based on the logs.

Now that I knew what module was faulting out it was time to find out why. I found the fields that where causing the message `field_address` and I looked within in that module for that value.

```
grep -R "field_address"

```

That brought me over to this file

`sites/all/modules/basic_cart/basic_cart_order/basic_cart_order.features.field_base.inc`

I opened up that file and made a couple of changes to all the fields that where causing a conflict to the database. You can find all the fields that cause the error in your log message. I added a prefix to all the fields with `basic_cart_order`.

*This fixed the problem down to the line that was throwing the error.*

---
Tags: entities, database
---


# Question
Title: How do I make an internal link with CKEditor?
I am using Drupal 8.

Using the standard WYSIWYG editor, when I click on the link button, I only get the option to add a url. I would have thought there would be some capabilities to look up existing pages.

Is there some way to create an internal link?

# Answer
Yes, what you're looking for is covered by the LinkIt project.

> Linkit provides an easy interface for internal and external linking with wysiwyg editors by using an autocomplete field. Linkit has by default support for nodes, users, taxonomy terms, files, comments and basic support for all types of entities that defines a canonical link template.

Once you install the module, you'll need to create a profile (under **Administration \> Configuration \> Content authoring \> Linkit**) for selecting your entities. Following that, configure your text format (under **Administration \> Configuration \> Content authoring \> Text formats and editors**) to use your LinkIt profile.

Once associated, you should be able to add a LinkIt button to your text format toolbar which will let you autocomplete links to your page content.
> 7 votes

# Answer
> I would have thought there would be some capabilities to look up existing pages.

You need to install CKEditor Entity Link OR go with the other answer which has more features.

>
> 1 votes

---
Tags: 8, navigation, wysiwyg
---


title: Why is jQuery 1.6.x not an option?

text:
# Question
Title: Why is jQuery 1.6.x not an option?
All the other versions of jQuery are listed; version 1.6.x is missing.

What is the reasoning for not including 1.6.x in the jQuery Update module?

# Answer
> 2 votes
There are compatibility problems with jQuery 1.6.x & D7. If you'd like to know the details here's the current outstanding feature request for it.

---
Tags: javascript
---


title: Organic-Groups theme selection

text:
# Question
Title: Organic-Groups theme selection
Does anyone know how to use the OG-Theme module to set unique themes for groups?

I can't find a relevant user interface.

# Answer
> 2 votes
Found the readme file online which describes the steps to add theme selection per group.

It can be found @ here.

It uses fields to make the selection as I suspected but the initial configuration is done via a different user interface.

Thanks for your input Steven.

# Answer
> -2 votes
Themekey module will give you gross control over which theme your OG uses.

> From module documentation,
>
> ThemeKey allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties. It can also be easily extended to support additional properties exposed by other modules.

---
Tags: 7, theming, organic-groups
---


# Question
Title: Hierarchical Views Catalog using Taxonomy in Drupal 8
I have the following Taxonomy vocabulary named *Product Catagories*:

Categorie1

* Sub categorie1
* Sub categorie1

Categorie2

* Sub categorie2
* Sub categorie2

If the user click on e.g. *Categorie1* I want to show the child-terms of *Categorie1* in a view.

I followed this tutorial and configured all steps. But in **Drupal 8** I cant't find this step:

> Default validation criteria" for "Taxonomy term" and choose "Convert taxonomy name to ID

Where is a similar option like *Convert taxonomy name to ID* in Drupal 8?

# Answer
Ubercart for Drupal 8 has a catalog example that might be a solution for you

https://ftp.drupal.org/files/projects/ubercart-8.x-4.0-alpha4.tar.gz
> 0 votes

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


# Question
Title: Encrypting db password stored in settings.php
The db password in settings.php is stored as plain text. Is there any way to encrypt that password?

My client says its a security risk even though the file permissions is as should.

# Answer
Security is always a matter of compromises. The question is always what threats do you want to protect against and what level of hindrance are you taking.

For example, you could create a small script that asks for the DB password, stores it in shared memory (with APC/APCu) and then change Drupal `settings.php` to read the DB password from there. Of course, any Apache restart now requires providing the DB password. But, you don't have your password in any file. Compromise, see?

If someone manages to run arbitrary PHP code, for sure they can gain the password but then it doesn't matter much anyways, right?
> 1 votes

# Answer
This is not a Drupal question specifically. Depending on the OWASP security standards you're following keeping the password in plain in settings.php could be considered a risk (in a normal, usual Drupal environment it won't be the case)

This thread on Information Security Stack Exchange discusses the topic, but in my opinion is a little paranoid and most of the options will slow down your site.
> 5 votes

# Answer
It is possible to do this. I have implemented this on my website and also written a post about this here:

http://techrappers.com/post/3508/how-secure-settingsphp-file-drupal

Above articles explain step by step procedure of implementing an encrypted password inside settings.php file with a PHP script and AES-256-CBC encryption method.
> 0 votes

# Answer
Create a new file somewhere on the webserver (mypsswrdfile.php) to which only web admins should have rwx rights to.

In it have them create a variable that holds the password.

$pass = "dbpass";

Include that file in your settings.php and use the variable for the password key.

"password" =\> $pass,
> -2 votes

---
Tags: security, configuration
---


# Question
Title: Why am I getting empty input value on expose filter $form_state variables for taxonomy?
I have created a panel. Inside the panel there is one content pane and one view expose filter present.

Normal exposed filter works properly but Simple hierarchical select does not works as expected: I am getting empty value after submit.

I have checked using `views_exposed_form_alter` hook.

```
$form_state['view']->exposed_input['shs_term_node_tid_depth']

```

Is there any alternative way to set or get the expose filter input?

# Answer
> 0 votes
Apply little trick and my issue solved. Used default taxonomy search and hide it.

```
(function($) {

Drupal.behaviors.tushar_1 = {
  attach: function (context, settings) {
    $('#edit-shs-term-node-tid-depth').change(function(){
      var eid = $('#edit-shs-term-node-tid-depth').val();
      $('#edit-tid ').val(eid);
    });
  }
};

})(jQuery);

```

Solved my issue.

---
Tags: views, panels
---


# Question
Title: Could not find resource node. but node enabled?
In my app, I am fetching data, editing and re-submitting it. That's where I am getting `Could not find resource node.`. However, `node` is enabled under `Resources`. Besides, I am not getting any errors fetching data. I was following this guide. How to handle this situation? My code is as follows:

```
$.ajax({
    url: 'http://www.rejicast.com/services/user/token.json',
    type: 'post',
    dataType: 'json',
    success: function(token) {
        localStorage.token = token.token;
        $.ajax({
            url: 'http://www.rejicast.com/services/system/connect.json',
            type: 'post',
            dataType: 'json',
            beforeSend: function(r) {
                r.setRequestHeader("X-CSRF-Token", localStorage.token)
            },
            success: function(data) {
                $.ajax({
                    url: 'http://www.rejicast.com/oyuncularim.json',
                    type: 'get',
                    dataType: 'json',
                    data: {
                        uid_raw: localStorage.uid
                    },
                    success: function (data) {
                        nid = data.nodes[0].node.nid;
                        console.log(JSON.stringify(data));
                        $("#otherpicture").attr("src", data.nodes[0].node.field_fotograflar.src);
                        /*
                        $("#otherpicture-2").attr("src", data.nodes[1].node.field_fotograflar.src);
                        $("#otherpicture-3").attr("src", data.nodes[2].node.field_fotograflar.src);
                        $("#otherpicture-4").attr("src", data.nodes[3].node.field_fotograflar.src);
                        $("#otherpicture-5").attr("src", data.nodes[4].node.field_fotograflar.src);
                        */
                        $("#name").val(data.nodes[0].node.title);
                        $("#tckn").val(data.nodes[0].node.field_tc_kimlik_no);
                        $("#dob").val(data.nodes[0].node.field_dogum_tarihi_1);
                        $("#email").val(data.nodes[0].node.field_e_posta);
                        $("#tel").val(data.nodes[0].node.field_telefon);
                        $("#tel2").val(data.nodes[0].node.field_telefon_2);
                        $("#address").val(data.nodes[0].node.field_adres);
                        $("#city option:contains('"+data.nodes[0].node.field_yasadigi_sehir+"')").prop("selected", "selected");
                        $("#gender option[innerHTML="+data.nodes[0].node.field_cinsiyet+"]").prop("selected", "selected");
                        $("#chest option:contains('"+data.nodes[0].node.field_sehir+"')").prop("selected", "selected");
                        $("#waist option:contains('"+data.nodes[0].node.field_bel+"')").prop("selected", "selected");
                        $("#thigh option:contains('"+data.nodes[0].node.field_kalca+"')").prop("selected", "selected");
                        $("#weight option:contains('"+data.nodes[0].node.field_kilo+"')").prop("selected", "selected");
                        $("#height option:contains('"+data.nodes[0].node.field_boy+"')").prop("selected",true);
                        $("#eyecolour option:contains('"+data.nodes[0].node.field_goz_rengi+"')").prop("selected", "selected");
                        $("#skincolour option:contains('"+data.nodes[0].node.field_ten_rengi+"')").prop("selected", "selected");
                        $("#shoesize").val(data.nodes[0].node.field_ayak_no);
                        $("#education").val(data.nodes[0].node.field_egitim_duzeyi);
                        $("#training").val(data.nodes[0].node.field_oyunculuk_egitimleri);
                        $("#skills").val(data.nodes[0].node.field_beceriler);
                        $("#languages").val(data.nodes[0].node.field_diller);
                        $("#personal").val(data.nodes[0].node.field_kisisel);
                        $(".videolink").val(data.nodes[0].node.field_videolar);
                    }
                });
            }
        });
    }
});
$("#edit").on("click", function() {
    ActivityIndicator.show("Face in Cast", "Düzeltme yapılıyor, lütfen bekleyin");
    monthNames = [
        "Oca", "Şub", "Mar",
        "Nis", "May", "Haz", "Tem",
        "Ağu", "Eyl", "Eki",
        "Kas", "Ara"
    ];
    date = new Date($("#dob").val());
    day = date.getDate();
    monthIndex = date.getMonth();
    year = date.getFullYear();
    finalDate = day+' '+monthNames[monthIndex]+' '+year;
    var fid = '';
    $.each(fids, function(k,v) {
        fid += '&node[field_fotograflar][und]['+k+'][fid]='+v;
    });
    var cat = '';
    $('#oyuncuKategori input:checked').each(function(k,v) {
        cat += '&node[field_kategorisi][und]['+k+']='+$(this).attr('id');
    });
    $.ajax({
        url:'http://www.rejicast.com/services/node/'+nid+'.json',
        type:'put',
        dataType:'json',
        beforeSend: function(r) {
            r.setRequestHeader("X-CSRF-Token", localStorage.token)
        },
        data:'node[type]=oyuncu&node[title]='+encodeURIComponent($("#name").val())+'&node[language]=und&node[field_tc_kimlik_no][und][0][value]='+encodeURIComponent($("#tckn").val())+'&node[field_sgk_durumu][und][value]='+encodeURIComponent($("#sgk option:selected").val())+cat+'&node[field_telefon][und][0][value]='+encodeURIComponent($("#tel").val())+'&node[field_telefon_2][und][0][value]='+encodeURIComponent($("#tel2").val())+'&node[field_adres][und][0][value]='+encodeURIComponent($("#address").val())+'&node[field_yasadigi_sehir][und][value]='+encodeURIComponent($("#city option:selected").val())+'&node[field_e_posta][und][0][value]='+encodeURIComponent($("#email").val())+'&node[field_cinsiyet][und][value]='+encodeURIComponent($("#gender option:selected").val())+'&node[field_gogus][und][value]='+$("#chest option:selected").val()+'&node[field_bel][und][value]='+$("#waist option:selected").val()+'&node[field_kalca][und][value]='+$("#thigh option:selected").val()+'&node[field_dogum_tarihi][und][0][value][date]='+finalDate+'&node[field_boy][und][value]='+encodeURIComponent($("#height option:checked").val())+'&node[field_kilo][und][value]='+encodeURIComponent($("#weight option:selected").val())+'&node[field_goz_rengi][und][value]='+encodeURIComponent($("#eyecolour option:selected").val())+'&node[field_ten_rengi][und][value]='+encodeURIComponent($("#skincolour option:selected").val())+'&node[field_ayak_no][und][value]='+encodeURIComponent($("#shoesize option:selected").val())+'&node[field_egitim_duzeyi][und][value]='+encodeURIComponent($("#education option:selected").val())+'&node[field_oyunculuk_egitimleri][und][0][value]='+encodeURIComponent($("#training").val())+'&node[field_diller][und][0][value]='+encodeURIComponent($("#languages").val())+'&node[field_beceriler][und][0][value]='+encodeURIComponent($("#skills").val())+'&node[field_kisisel][und][0][value]='+encodeURIComponent($("#personal").val())+'&node[field_videolar][und][0][video_url]='+encodeURIComponent($(".videolink").val())+'&node[field_videolar][und][0][description]='+encodeURIComponent($(".videodesc").val())+'&node[field_yapim_yili][und][value]='+encodeURIComponent(finalDate)+'&node[field_okudum_anladim][und][value]='+encodeURIComponent($(".privacy").is(':selected')?1:0),
        success:function(data) {
            ActivityIndicator.hide();
            navigator.notification.alert("Kaydınız başarıyla düzenlendi", function() {return;}, "Face in Cast", "Tamam");
        },
        error:function(xhr,status,message) {
            console.log(xhr);
            console.log(status);
            console.log(message);
            navigator.notification.alert("Eksik bırakılan alan var, lütfen doldurup tekrar deneyin.", function(){return;}, "Hata", "Tamam");
        }
    });
});

```

UPDATE:

# Answer
> 0 votes
I removed the alias and it worked :) Apparently resource name doesn't work if I assign an alias to it.

---
Tags: 7, ajax, services
---


# Question
Title: Multi-language with domain name specific doesn't work
I am working on a multi-language website. I am setting content in both English and French.

When I use **path prefix** as my detection method, it works fine, like poc-local.com and poc-local.com/fr. When I use **domain** as my detection method, it doesn't work, like fr.poc-local.com.

I am getting a 302 error, and "the page isn't redirecting properly" error. How can I fix this?

# Answer
> 0 votes
I found the answer for this.

I have installed global redirect module and now it's working.

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

But Now I am having another one problem.My language Switcher block is not working.When I switching from one language to another language the recently switched language url displaying for all languages...

---
Tags: 7, i18n-l10n, redirection
---


# Question
Title: How to add time element to open date and close date when adding a quiz
I am using the following modules.

1. Quiz, Version 7.x-4.0-rc2
2. Date, Version 7.x-2.9

When adding a quiz, in the availability options tab, I want to be able to set the time as well.

In the open date and close date, there should be an hour and minute option as well.

I did the following things.
1. In the `hook_form_alter()`, added the below code

```
if($form_id == 'quiz_node_form'){
  $form['quiz_availability']['quiz_open']['#type'] = 'date_select';
}

```

This gave a warning on the `node/add/quiz`page.

> Warning: strlen() expects parameter 1 to be string, array given in date\_default\_date()

2.So added a patch in `date_api_elements.inc`
https://www.drupal.org/files/date-element-default-value-2038057-1.patch This removed the warning but upon adding the date and time in the availability options and saving the form, it throws the huge error below.

> Please supply a valid date. PDOException: SQLSTATE\[01000\]:
>
> Warning: 1265 Data truncated for column 'quiz\_open' at row 1: INSERT INTO {quiz\_node\_properties} (vid, nid, aid, number\_of\_random\_questions, max\_score\_for\_random, randomization, backwards\_navigation, repeat\_until\_correct, quiz\_open, quiz\_close, takes, show\_attempt\_stats, keep\_results, time\_limit, pass\_rate, summary\_pass, summary\_pass\_format, summary\_default, summary\_default\_format, quiz\_always, feedback\_time, display\_feedback, tid, has\_userpoints, userpoints\_tid, allow\_skipping, allow\_resume, allow\_jumping, show\_passed, mark\_doubtful, max\_score) VALUES ....

3.In the `hook_node_presave`, printed the *$node*.

It stores the date as below.

```
  [quiz_open] => 2016-05-12 21:17

```

but it expects the date to be stored like this.

```
 [quiz_close] => Array(
      [month] => 6
      [day] => 11
      [year] => 2016
    )

```

How to store the date as an array or is there an alternative solution to the problem.

# Answer
> 0 votes
You can convert it to an array using the php function substr

```
// lets assume $date = Array ('quiz_open' => '2016-05-12 21:17');

$year = substr($date['quiz_open'], 0, 4); // grabs 2016
$month = substr($date['quiz_open'], 5, 2); // grabs 05
$day = substr($date['quiz_open'], 8, 2); // grabs 12

$date = array ('quiz_close' => array (
                                'day' => $day,
                                'month' => $month,
                                'year' => $year,
                                     )
              );

```

---
Tags: 7, datetime, quiz
---


# Question
Title: Use static function as operations with batch API
I can't get batch to work with a static method as callback function for the operation

```
$batch['operations'][] = ['MyController::MyMethod', [$arg]];

```

If I use a procedural function and call a static method from that, it works.

It could be a solution, but as I have several methods to call during the same batch, I don't want to create a wrapper function.

Does someone know how to make batch API work with static methods?

# Answer
The function that Drupal uses to process the batch operation is `_batch_process()`, which uses the following code to call the operation callback.

```
  // Build the 'context' array and execute the function call.
  $batch_context = array(
    'sandbox'  => &$current_set['sandbox'],
    'results'  => &$current_set['results'],
    'finished' => &$finished,
    'message'  => &$task_message,
  );
  call_user_func_array($callback, array_merge($args, array(&$batch_context)));

```

Since `call_user_func_array()` allows to use a string like `MyClass::myMethod` as callback, the code you wrote should work, if the Drupal autoloading system is able to find the file containing the class definition, which means:

* You need to respect the file structure as per the PSR4 structure expected by Drupal
* You need to fully qualify the class name by adding its namespace

In the case the file containing the class it is not in the directory where Drupal looks for class files, such as in the case the class is contained in a my\_operation\_callbacks.inc put in the same directory containing the module file, then you need to use code similar to the example code shown in Batch operations.

```
$batch = array(
  'title' => t('Exporting'),
  'operations' => array(
    array('my_function_1', array($account->id(), 'story')),
    array('my_function_2', array()),
  ),
  'finished' => 'my_finished_callback',
  'file' => 'path_to_file_containing_myfunctions',
);

```

`$batch['file']` in that code tells Drupal which file it needs to load before executing the operation callbacks.
Even in this case, the class must be referenced using its namespace, which could simply be `\` in the case the class is put in the global namespace.
> 2 votes

---
Tags: 8, batch-operations
---