# Question
Title: How to get services post data(json format) callback function?
I am using services module and rest API its working fine.

But i need to create a `menu callback` where i get the `json post` data and save in database.

How to get the `json` data in menu callback?

# Answer
> Through comments, we determined the OP would like to alter the results of the user registration service resource...

To alter the results of user registration data, implement hook\_services\_request\_postprocess\_alter() in your custom module, for example:

```
/**
 * Implements hook_services_request_postprocess_alter().
 */
function my_module_services_request_postprocess_alter($controller, $args, &$result) {
  if ($controller['callback'] == '_user_resource_register') {
    $result->foo = 'bar';
  }
}

```

This will allow the value of `foo` to be available to your application that is calling the user registration service resource.
> 0 votes

---
Tags: 7, services
---


# Question
Title: How do I programmatically create a list of new users?
I'm trying to use the following drush script, but I keep getting errors. Currently, it is not properly setting the user role to Premium.

```
#!/user/bin/env drush
<?php
  $users = [
      "name" => "email",
      "name" => "email",
      "name" => "email",
      "name" => "email",
      "name" => "email",
      "name" => "email",
      "name" => "email",
      "name" => "email",
  ];
  foreach ($users as $key => $val) {
      drush_invoke("user-create", $val);
      drush_print("Created account for email " . $val);
      drush_set_option("password", $key);
      drush_invoke('user-password', $val);
      drush_print("Created password for email " . $val . " with password " . $key);
      drush_set_option("mail", $val);
      drush_invoke('user-add-role', "Premium members");
      drush_print("Added premium role to " . $val);
  }
?>

```

Is there a better way to achieve this?

# Answer
> 3 votes
If you are having trouble with `drush_invoke`, try `drush_invoke_process`, which has two advantages over `drush_invoke`:

1. It is executed in a separate process, so you can set options explicitly, and do not need to worry about option "pollution" from previous calls to `drush_set_option()`
2. The results of the operation, including all log messages, is returned as structured php data, so you have a better idea of what was done.

Example:

```
$values = drush_invoke_process("@self", "user-add-role", array("Premium members"), array('mail' => $val));

```

You will find the output of the command in `$values['output']`, and structured results (if available) in `$values['object']`.

Note that in general, there is nothing wrong with calling `drush_invoke` as you are doing above; you may use that technique if it works for your use case. It is likely to be faster, but may sometimes be fragile.

# Answer
> 3 votes
Yes, there is a way better way of using `drush` to achieve this and that is using drush php-script:

```
$ drush scr /path/to/create-users.php

```

Create `create-users.php` and put it somewhere:

```
<?php
/*
 * Content of create-users.php (could be located anywhere on the system)
 */

$users = array(
    'name1' => 'name1@domain',
    'name2' => 'name2@domain',
    // ...
);
$role_name = 'Premium members';

$role = user_role_load_by_name($role_name);
foreach ($users as $name => $email) {
  //set up the user fields
  $fields = array(
    'name' => $name,
    'mail' => $email,
    'pass' => user_password(),
    'status' => 1,
    'roles' => array(
        $role->rid => $role->name,
    ),
  );
  //the first parameter is left blank so a new user is created
  $account = user_save('', $fields);
}

```

(Code snippet from http://codekarate.com/blog/create-user-account-drupal-7-programmatically)

# Answer
> 1 votes
It looks like you've omitted the `$val` in your user-add-role invoke.

Drush won't know which user to add the role to!

You have

```
drush_invoke('user-add-role', "Premium members");

```

You should have

```
drush_invoke('user-add-role', "Premium members", $val);

```

If that doesn't solve it, you next might need to check the handling of role name, since it contains a space. A quick test (`drush user-add-role 'Some role' user@example.com`) locally suggests that this should work OK if the Drush command gets the parameter with the space in it.

As far as *"Is there a better way to achieve this?"* goes, yes - you could be checking the results of each command and reporting back failures, rather than moving on to the next step. (If the user account already exists when you call `drush user-create`, your code may want to stop before changing the password for an existing account with `drush user-password`.)

# Answer
> 0 votes
As an alternative option, particularly handy when you many need to rerun with new users/updates, is to use feeds. Then upload/point to a CSV.

---
Tags: 7, drush
---


# Question
Title: Page not found when I try to access my custom module
I create a custom module in Drupal 8. It install/uninstall smoothly. But when I try to access that module then I'm getting that message

```
"Page Not Found." -
Failed to load resource: the server responded with a status of 404 (Not Found)

```

For debuging I made these entries in my setting.php file.

```
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
$conf['error_level'] = 2;

```

But getting no luck. Is there any other ways to debug my code in drupal 8.

Here is my routing file code:

```
custom_module.admin:
  path: '/admin/custom_module'
  defaults:
    _controller: '\Drupal\custom_module\CustomModuleController::custInformation'
    _title: 'Custom Module Title'
  requirements:
    _permission: 'access information'

custom_module.site_page:
  path: '/custom_module'
  defaults:
    _title: 'Custom Module Title'
    _controller: '\Drupal\custom_module\CustomModuleController::custInformation'
  requirements:
    _permission: 'access information'

```

and link.menu.yml file code:

```
custom_module.admin:
  title: 'Custom Module Title'
  parent: system.admin
  description: 'Brief description.'
  route_name: custom_module.admin
custom_module.site_page:
  title: 'Custom Module Title'
  route_name: custom_module.site_page
  menu_name: footer
  enabled: 0

```

& controller file

```
namespace Drupal\custom_module\Controller;

use Drupal\Core\Controller\ControllerBase;

/**
 * Controller routines for contact routes.
 */
class CustomModuleController extends ControllerBase {

  /**
   * Render a list of entries in the database.
   */
  public function custInformation() {
    $header = array('Name');
        $rows[] = array("John");
    $content['table_brief'] = array(
      '#type' => 'table',
      '#header' => $header,
      '#rows' => $rows,
      '#empty' => t('No entries available.'),
    );
    return $content;
  }
}

```

# Answer
> 0 votes
There are several reason for "Page not found." I'm sharing the some points may be helpful to someone who face same issue.

1. Check your php log file. if there is some php error in your code, it also cause page not found. It occur in my case.
2. Check PHP file location, which you mention in routing file. Sometimes php file location not correct.
3. Most important point, check yml file for indentation, if indentation is not proper it also cause "page not found" issue.
4. Check recent log message and try to sort out warning/error if any

@Kiran Tej, my issue has been resolved. In my case by mistake I placed the file directly inside the 'src' folder. Please read above points may be it helpful to you if your issue not resolved yet.

---
Tags: 8
---


title: AJAX event returns same data always

text:
# Question
Title: AJAX event returns same data always
So, this is a simple form, and what the ajax call back does here is that it returns the value of a field that's being changed.

The problem is that, only the value of the first change is returned. If i change the value a second time, the returned value is the same as first. I'm not sure what is happening here, it needs a better pair of eyes.

Here's the code

```
<?php

    //Create raffle form
    function raffle_create_form($form, &$form_state)
    {
        dpm($form_state);
        //Basic raffle info
        $form['raf_raffle_name'] = array(
            '#type' => "textfield",
            "#prefix" => "<h5>Raffle information</h5><hr>",
            "#title" => "Raffle Name:",
            "#required" => TRUE
        );

        $form['raf_allowed_number'] = array(
            '#type' => "textfield",
            "#title" => "Number of allowed members",
            "#required" => TRUE,
            '#element_validate' => array('element_validate_number')
        );

        $form['raf_start_now'] = array(
            "#type" => "checkbox",
            "#title" => "Start raffle now?"
        );

        $form['raf_end_date'] = array(
            "#type" => "date",
            "#title" => "When to close this raffle?",
            "#required" => TRUE
        );

        $form['raf_prize_type'] = array(
            '#type' => "select",
            "#options" => array('gift' => 'Steam Gift', 'hardware' => 'Gaming peripherals'),
            "#title" => "Prize type",
            "#required" => TRUE,
            "#ajax" => array(
                'callback' => 'raffle_create_form_type_steam',
                'wrapper' => 'steam_options',
                'event' => 'change',
                'method' => 'replace',
            ),
        );

        $form['raf_prize_name'] = array(
            '#type' => "textfield",
            "#title" => "Prize name",
            "#prefix" => "<div id='steam_options'></div>",
            "#required" => TRUE
        );

        $form['raf_prize_about'] = array(
            '#type' => "textarea",
            "#resizeable" => true,
            "#title" => "Prize description"
        );

        $form['raf_prize_thumb'] = array(
            '#type' => "file",
            "#title" => "Prize thumbnail"
        );

        $form['raf_prize_link'] = array(
            '#type' => 'textfield',
            '#title' => "Link to product"
        );

        $form['raf_raffle_create'] = array(
            '#type' => 'submit',
            '#value' => "Create Raffle",
        );

        $form['#submit'][] = 'raffle_create_form_submit';

        return $form;
    }

    function raffle_create_form_validate($form, &$form_state)
    {
        dpm($form_state);
    }

    function raffle_create_form_submit($form, &$form_state)
    {

    }

    function raffle_create_form_type_steam($form, &$form_state)
    {
        return $form_state['values']['raf_prize_type'];
    }**

```

# Answer
> 0 votes
Whatever data is returned must be encapsulated in a div element of the same id as the wrapper.

This fixed the problem for me :)

```
function raffle_create_form_type_steam($form, &$form_state)
{
    if($form_state['values']['raf_prize_type'] == 'hardware')
    {
        return "<div id='steam_options'></div>";
    }
    else
    {
        return  $form['raf_steam_option_game_append'] = array(
                '#type' => 'checkbox',
                '#title' => 'Check if Steamer has game in library',
                '#description' => 'Does not allow gamer to join raffle if said gift already exists within gamer\'s steam library',
                "#prefix" => "<div id='steam_options'>",
                "#suffix" => "</div>"
            );
    }

}

```

---
Tags: forms, hooks, ajax, webforms
---


# Question
Title: How to create custom preview for content type in Drupal 7?
I am implementing a content type called "Product" which has some 8 to 10 fields. While creating new product details under that content type "Product" client wants the custom preview of the content.

The default preview while adding content is really weird and it does not look good.

I have searched a lot on google but there is no any contributed module available for it.

So please tell the way other than custom module to implement it ?

# Answer
> 0 votes
Something like Page Preview may help you.

---
Tags: nodes, entities
---


# Question
Title: Drupal Commerce causing database deadlocks
I'm trying to get to the bottom of a known Drupal Commerce bug to do with row locking.

When a user logs in on my development site, Drupal Commerce starts multiple identical queries that look like this, even when the cart is empty:

```
SELECT revision.order_number AS order_number, revision.revision_id AS revision_id, revision.revision_uid AS revision_uid, revision.mail AS mail, revision.status AS status, revision.log AS log, revision.revision_timestamp AS revision_timestamp, revision.revision_hostname AS revision_hostname, revision.data AS data, base.order_id AS order_id, base.type AS type, base.uid AS uid, base.created AS created, base.changed AS changed, base.hostname AS hostname
FROM
commerce_order base
INNER JOIN commerce_order_revision revision ON revision.revision_id = base.revision_id
WHERE  (base.order_id IN  (''203''))  FOR UPDATE

```

They're all started less than a second apart, and they all hang and sit waiting for a transaction lock to be granted. The thread I linked to suggests the problem could be the same user is logged in on different browsers, but there's only one entry in my sessions table, so I'm looking for another cause.

What else could is going on here? The big obvious clue I can see is that I can't seem to run that query without an error - "base.order\_id IN (''203'')) FOR UPDATE" throws a syntax error, and as far as I can see that's not normal usage for IN - it's normally two integers seperated by a comma, like a limit query, like ('1','12'). The order itself is an empty cart: opening the blob file just gives me this:

```
<!DOCTYPE HTML><html lang='en' dir='ltr'><meta charset="utf-8" /><meta name="robots" content="noindex,nofollow" /><meta http-equiv="X-UA-Compatible" content="IE=Edge"><style>html{display: non

```

But I don't know enough about SQL to know if this is something you can do in a join somehow - what's really going on here? And where else should I be looking to debug it?

---

**UPDATE 11/02**: I haven't gotten to the root cause of this, but I've done some more investigating.

* Channel Islander is right, there's nothing screwy with that syntax. I must have just changed it somehow between copy and pasting and trying to get the query to run.
* I truncated the order and order\_revisions table in the dev site, then tried to replicate the bug by adding and removing stuff from my admin user's cart (trying to create a lot of revisions). I couldn't replicate the bug like this, and performance got a lot better from them onwards: page loads when logging in and out sped up by multiple seconds, and I can't even catch this SELECT... FOR UPDATE query in phpMyAdmin's status tab.

This seems to have resolved the issue for now, but truncating both tables is obviously not feasible for a production site. Maybe setting orders at "cart" stage to expire after a certain time would be, though?

# Answer
> 1 votes
Based on your update, you might consider using the Commerce Cart Expiration module.

---
Tags: commerce, database
---


# Question
Title: Adding like condition to db_select for section of string
What I am trying to do is find all of the basic pages where their titles contain 'Meetings' for example January Meetings

Here is what I have tried so far

```
$string = 'Meetings';
    $query = db_select('node', 'n');
    $query->fields('n');
    $query->condition('n.type', 'page', '=');
    $query->condition('n.changed', $time, '<=');
    $query->condition('n.status', 1, '=');
    $query->condition('n.title', '%'.db_like($string), 'LIKE');
    $result = $query->execute();

```

Which hasnt worked as it is trying to find pages that only contain 'Meetings' in their title.

# Answer
> 1 votes
> as it is trying to find pages that only contain 'Meetings' in their title.

Not quite - it's trying to find titles that *end with* the string "Meetings".

For a full wildcard match, the percent needs to be at both ends:

```
$query->condition('n.title', '%' . db_like($string) . '%', 'LIKE');

```

---
Tags: nodes, database
---


# Question
Title: Is it possible to pass configuration values as arguments to services?
I'm writing a module that makes calls to a Web service to read and store data. Here's my services.yml file:

```
services:
  example.connection:
    class: Drupal\Core\Http\Client

```

I've already a settings form (inheriting from ConfigFormBase) that stores a base URL in configuration, and I'd like to pass that as an argument to the Client class's constructor. I've tried this:

```
class ExampleServiceProvider implements ServiceModifierInterface {

  /**
   * Modifies existing service definitions.
   *
   * @param ContainerBuilder $container
   *   The ContainerBuilder whose service definitions can be altered.
   */
  public function alter(ContainerBuilder $container) {
    $base_url = $container->get('config.factory')
        ->get('example_entity.settings')->get('base_url');
    if ($base_url) {
      $arguments = array('base_url' => $base_url);
      $container->getDefinition('example.connection')
        ->setArguments(array($arguments));
    }
  }
}

```

But that gives me HTTP 403 errors for every page on the site. Should it be possible to pass arbitrary arguments like this? Hardcoding a URL into the $base\_url variable works fine.

# Answer
In your services file add the following service:

```
# The bar configuration for the foo module
config.foo.bar.immutable:
  class: \Drupal\Core\Config\ImmutableConfig
  factory: config.factory:get
  arguments: ['bar']
config.foo.bar.mutable:
  class: \Drupal\Core\Config\Config
  factory: config.factory:getEditable
  arguments: ['bar']

```

In your service create method add either `config.foo.bar.immutable` or `config.foo.bar.mutable` service as an argument.
> 2 votes

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


# Question
Title: How to loop through field deltas of an object?
In Drupal 7 I loaded the node/entity I want with node\_load / entity\_load and, if necessary, then I took a field with multiple deltas and take the value I wanted with a foreach loop.

In Drupal 8 how can I do the same in a hook?

For example, this loads my first value of a field:

```
$a_id = $adress->field_a->target_id;

```

In this case an entity reference field. But there are more target\_ids.

So how to take them?

# Answer
> 5 votes
Entity reference fields have a method called `referencedEntities()`.

Usage example:

```
$addresses = $entity->get('address');
foreach($addresses->referencedEntities() as $delta => $address) {
  // Do something with the $address entity
}

```

P.S. If you only want the field then as @Clive mentioned you can just iterate over $addresses.

---
Tags: entities, 8
---


# Question
Title: create and save data to a file in the files folder from cron
I currently have some working example code where when a URL path i defined using hook\_menu has been passed; My custom module will use file\_get\_path() to pull a txt file from another ftp server. It will then return $data. The source data is stored that each line is a record. So I simply read the file one line at a time and use the explode() method to break the data into its components. From that I have it building a string in the format of a JSON at this point I return it to the user as a consumable JSON. This is used for my front end JavaScript. The problem is this data in the txt file changes very little over time. (its updated every night but very little changes).

I would like to reduce my request time by moving the fetch of the txt file to a cron job and build the JSON and save it in a sub directory of the Files directory. That way every request for the JSON data will be quick and not require a file\_get\_contents() and will also not require building the JSON data on every request.

I have been looking into the Files API and the hook\_cron but very few quality examples show how to create a file or run a cron. I just need a simple example where a cron hook saves a simple file to a directory inside the files folder.

I'm using **Drupal 7**

***UPDATE:***

I tried the following: *(objective to make sites/mysite.com/files/myDir/test.txt)*

```
//File Name: MyModule_cron.inc
function MyModule_cron(){
    $baseDir = 'public://myDir';
    $fileContent = "hello world";
    file_prepare_directory($baseDir);
    file_put_contents($baseDir.'/test.txt', $fileContent);
}

```

This is loaded in from an inc file (added into the info file) and I have cleared my cashe then run cron. I then check in the sites `files` folder. The `myDir` is not created along with the file not being made. Is there something i'm missing? I'm not getting any error messages when running cron.

# Answer
> I just need a simple example where a cron hook saves a simple file to a directory inside the files folder.

That would be literally as simple as:

```
function MYMODULE_cron() {
  $path = 'public://foo/bar/';

  if (file_prepare_directory($path, FILE_CREATE_DIRECTORY)) {
    $content = function_to_generate_content();
    file_put_contents($path . 'baz.ext', $content);
  }
  else {
    // Log an error
  }
}

```
> 3 votes

---
Tags: hooks, cron, files
---


# Question
Title: How to list the uploaded files (image file) of unsaved nodes?
From the question What happens if a user uploads an image but doesn't save the node? and its answer, there is a table called `file_managed` and for any uploaded file (an image in my case), it sets `0` in `status` column, and if the image node is saved, it is set to `1`. During each cron run, all files with `0` status will be removed.

I am using bulk\_file\_nodes module to upload the images. Unfortunately, this module sets the status `1` for uploaded files and no matter if their node is saved or not.

I need to accomplish what Drupal core does for unsaved nodes of uploaded files. To do so I have to list those files. There are about 30000 images and about 2500 nodes in my website that are uploaded by people and it is growing very fast every day.

The brute force method is to check the entire `fid` column of `field_data_field_image` table of the database for every file (in fact for every `fid` of `file_managed`) to see if that file is attached to a node or not, I think it is not a good solution at all.

Is there any way else to handle this?

thanks

# Answer
If the image field which contains image of the node type is `field_data_field_image`, the following query returns unassigned uploaded files to nodes:

```
<?php
    $result = db_select("file_managed","fmanage")
        ->fields("fmanage",array('filename'))
        ->fields("fmanage",array('uid'))
            ->fields("fmanage",array('fid'))->execute();
    foreach ($result as $row){
        $fid = $row->fid;
        $result1 = db_select("field_data_field_image","imagefid")
            ->condition("imagefid.field_image_fid",$fid,"=")
        ->fields("imagefid",array('field_image_fid'))->execute();
        if($result1->rowCount() == 0){
            print $row->filename."</br>";
            print $row->uid."</br>";
            print "</br>";
        }
    }
?>

```

Just notice that, the `field_data_field_image` must be the only image field in the website. If there is other image field with another name, the query should search for them too. Because I use the `field_data_field_image` for every image field in my website, I only need to search this table.

I executed the above code and returned the correct result.
> 0 votes

# Answer
The short answer is that there isn't really a way to do this.

The longer version is that you could make some SQL to find all candidates. The issue is that you can see if a file is used somewhere (on entites) on the file\_usage table, but some files wont be "used in that manor. This means that finding a file "not being used" is not the same as it's safe to delete it.

A solution could be to make a cron job, that only checks images that has just been uploaded, but you still have the issue that you might end up deleting files that shouldn't have been deleted.
> 0 votes

---
Tags: 7, nodes, files
---


# Question
Title: How to retrieve a select box option and set the field's value to it?
I have a a taxonomy term select box (called "product\_keyword") in a node that gets its options populated via the Reference Field Option Limit module. There are 3 other taxonomy term reference fields in the node that are responsible for limiting the "product\_keyword" option list all the way down to a single option, and this part is working beautifully.

The "product\_keyword" field is set to Required, so when you actually go in to edit the node, the "product\_keyword" field *appears* to already have this one option selected. However, with the use of the Devel module, I have discovered that this is not the case. There is no #value for the "product\_keyword." I have created a custom module (my very first one ever, in fact) to set this #value, but I am having trouble determining how to choose the right properties to set this. This response by Clive is what I'm trying to wrap my brain around.

My module code is using a hook\_form\_alter function that involves the use of #after\_build:

```
    //Declare the callback for after_build for page node form
function set_keywords_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'part_node_form') {
    $form['#after_build'][] = 'set_keywords_after_build';
  }
}

function set_keywords_after_build($form, &$form_state) {

```

The overall goal is to simply allow this field to be displayed in a view, but one complication is that these 7000+ nodes are being imported via the Feeds module, and the clients should not have to edit each node manually just to hit the Save button (which is the only way the problem can be solved now - VBO can't do it, nor can the Resave Nodes module). I'm not even sure if #after\_build should be involved, and I am also ok with setting the field's #default\_value instead of or in addition to the #value.

EDIT:

In the page array dropdown, for the keyword's select list options:

```
#options (Array, 1 element) 0 (String, 13 characters ) Inker Parts

```

But under '#value," I'm just getting:

```
#value (String, 8 characters ) - None -

```

Under another reference field, "Product Family," where things are functioning normally, I see:

```
#options (Array, 40 elements)
_none (String, 8 characters ) - None -
1401 (String, 5 characters ) AUTOZ

```

.......and so on

and for the #value:

```
    0 (String, 2 characters ) 1401
          $...['content']['system_main']['field_product_family']['und']['#value'][0]

```

In this example, "1401" is the tid, and "AUTOZ" is the term name.

# Answer
> 0 votes
This question looks a little old, but here is an answer for you. Reading your comments you have

```
//Declare the callback for after_build for page node form
function set_keywords_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'part_node_form') {
        $form['#after_build'][] = 'set_keywords_after_build';
    }
}

function set_keywords_after_build($form, &$form_state) {
    $keyword = $form['field_product_keyword']['und']['#options'];
    $form['field_product_keyword']['und']['#value'] = $keyword;
    $form['field_product_keyword']['und']['#default_value'] = $keyword;
    return $form;
}

```

I applaud your efforts, especially that you are attempting to do this clean and proper with a hook\_after\_build. The hook\_after\_build allows your value setting code to run after the Reference Field Option Limit has done its adjustments, so you are certain to be getting the value you want.
I see one mistake in your code, and that is that `#options` is an array of Label =\> Value so that the form can display language in the select field instead of raw values. I think all you need is this one adjustment:

```
// remove the -None- option from the start, then set the next option
array_shift($form['field_product_keyword']['und']['#options']);
$keyword = array_shift(array_keys($form['field_product_keyword']['und']['#options']));
// this is safe because $form is not passed by reference,
// do not do this on $form_state

```

When trying to do things like this, I find it helpful to look inside what it is I am manipulating. If you know the string of references that you need to access some data, you can print it on the form like this:

```
//Declare the callback for after_build for page node form
function set_keywords_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'part_node_form') {
        $form['#after_build'][] = 'set_keywords_after_build';

        // see what our options are, print them as text on the form:
        $form['some_text'] = array(
            '#markup' => '<p>'. $form['field_product_keyword']['und']['#options'][0] .'</p>',
            '#weight' => '-80'
        );
    }
}

```

As you have mentioned you are using the devel module, you could easily throw the #options array into a dpm() or krumo() inside the form alter and get it printed to your form page also.

---
Tags: forms, taxonomy-terms
---


# Question
Title: How do I make a block appear in a panels display based on the state of a field
I have a field that is a single on/off checkbox. Whenever it has been selected it outputs a key of 1 into the panel display, if it hasn't it outputs a 0. I want it to output custom html for a link to another page if it's a 1 and I want it to become disabled/hidden if it's 0. The resulting block/field/html needs to be inputted into a panels display, just like the key currently does.

As of right now, I'm using jquery to do this for me, but it seems like there HAS to be a way to do this with drupal. I've looked into conditional\_fields and field\_conditional\_state but they seemed to be more focused on entering conditional information and not on only making conditional outputs. I'm currently looking into minipanels, panel pages, and context right now to figure this out, but haven't found an easy way of doing it and it feels like I'm overthinking it.

I know that there's a States API that handles this kind of thing, but there's surprisingly little information that I've been able to find on how to apply it to displays. Any help here would be greatly appreciated.

Thanks, Cole

# Answer
> 0 votes
If I understand your case you could : \- have a Static field, containing your link \- use Conditional Fields Module and set up a condition with :

"dependee" = your checkbox "dependent" = your static field (containing your link to another page) condition = dependent is visible if dependee has value 1

---
Tags: 7, theming, entities, panels
---


title: HTTP_RAW_POST_DATA is deprecated

text:
# Question
Title: HTTP_RAW_POST_DATA is deprecated
When using a field collection feed import, I get this error.

> An AJAX HTTP error occurred. HTTP Result Code: 200 Debugging information follows. Path: /batch?id=17839&op=do StatusText: OK ResponseText: Deprecated: Automatically populating $HTTP\_RAW\_POST\_DATA is deprecated and will be removed in a future version. To avoid this warning set 'always\_populate\_raw\_post\_data' to '-1' in php.ini and use the php://input stream instead. in Unknown on line 0 Warning: Cannot modify header information - headers already sent in Unknown on line 0 {"status":true,"percentage":"64","message":""}

I have researched this issue and statistically came up with this solution: change in php.ini always\_populate\_raw\_post\_data = -1

I have changed that and also restarted apache.

I still receive that error. Does anyone have any thoughts to this?

# Answer
You need to edit your `php.ini` and add or uncomment the following line:

```
always_populate_raw_post_data = -1

```

If you've still that error after restarting Apache, you probably edited the wrong file. So as admin, go to *Reports*/*Status*/*PHP* (at `/admin/reports/status/php`) and double-check your value for `always_populate_raw_post_data` and your `php.ini` path.

Note that the above setting will only avoid the warning, see: Changes to PHP-5.6 and this SO post.
> 1 votes

# Answer
As far as I know, it should be disabled.

There is an issue on this in the core Drupal queue.
> 0 votes

---
Tags: ajax, importing-exporting
---


# Question
Title: Using hook_form_alter to change exposed filter from a textfield to a checkbox
While Views in now in Core in Drupal 8, Better Exposed Filters, a popular module for Drupal 7, is not yet ported to Drupal 8. So I need some way to do some of the same things.

I have an underlying Numerical field, and have configured an exposed filter that matches a value of 1 when the field has a value of \> 0, and 0 otherwise. This works, but Views renders the field as a text field. This is very ugly, and you'd think it would be simple enough to change the form field in the exposed filter form to a checkbox. You'd think that changing the '#type' via hook\_form\_alter would do the job.

Except, this does not work. I've tracked the problem down to code in ViewExecutable::\_build($key), around line 1269:

`$rc = $handlers[$id]->acceptExposedInput($this->exposed_data);`

If I change the '#type' of the form field to 'checkbox', $rc is *always* TRUE, even if when the type was still a textfield, $rc would be FALSE. This pretty much guarantees that the view will never return any matching rows.

The problem appears to be that the array ViewExecutable::$exposed\_data have values of 1 (rather than the correct value of '') once type is changed to 'checkbox'. Since ViewExecutable::$exposed\_data has access "public", I still haven't figured out where in the code the wrong values get assigned.

I'm not sure why it's so hard to do something that is normally very simple using form\_alter. Any ideas as to how to get around this problem will make me (and my client) very happy.

# Answer
Just entered this as a bug: https://www.drupal.org/node/2651102. The underlying issue is that Views checks for an empty array (among other things) to see if a filter has a value set. Unchecked checkboxes results in an array of zeros.
> 2 votes

---
Tags: views, 8
---


title: Routing in Drupal 8 for basic pages

text:
# Question
Title: Routing in Drupal 8 for basic pages
I've just begun the transition process from D7 to D8. I installed D8 and added a basic page w/ a menu link. I then began to explore the new D8 routing system and expected to find a .yml file that contained information about where to find the added page but I don't see it. This is not a added module so it doesn't have a moduleName.routing.yml.

I'm looking for a conceptual description of why this does or doesn't follow the new .yml convention.

# Answer
> 2 votes
Node routes are declared using what is known as a route provider. The node route provider class is \Drupal\node\Entity\NodeRouteProvider and it is declared in the annotation of the node class:

```
/*
 * @ContentEntityType(
 *   id = "node",
 *   label = @Translation("Content"),
 *   bundle_label = @Translation("Content type"),
 *   handlers = {
 *     ...
 *     "route_provider" = {
 *       "html" = "Drupal\node\Entity\NodeRouteProvider",
 *     },
 *     ...
 */
class Node extends ContentEntityBase implements NodeInterface {
//  ...
}

```

---
Tags: routes, 8
---


# Question
Title: Should the Drupal 8 sites/default/files/config folder be stored in git with its hash suffix?
New question title: "Should the sites/default/files/config folder be stored in git with it's hash suffix?"

* " Reason I ask this is that this might cause 2 issues:
    + May be a hindrance when comparing code bases of sites, the diff comparison program would not be able to compare the contents of the config folder directly, if the suffixes are different.
    + If the site is a open collaboration project, where the code is put on github or bitbucket publicly, then the config hash suffix which is normally secret would be visible to the public and therefore the folder can be determined but the intent was to use the hash to make the folder harder to guess for security reasons.

Original question title: "Why does the Drupal 8 config folder have a long gibberish-like name, e.g.: config\_wNOLcm... etc?"

* Answer to the question about the 'gibberish' is:

> This sequence is a random hash generated during the installation of your Drupalvsite. It is used to add some protection to your configuration files. Additionally to the default restriction enforced by the .htaccess file within the subdirectories of the config directory that prevents unauthorized users from seeing the content of the directories. As a result, would be really hard for someone to guess the folder's name.

Credit: Drupal 8 Configuration Management, First published March 2015, page 29

Some general references:

https://www.drupal.org/node/2360331#how-do-i-version-my-

# Answer
* In the site install process, Drupal will write the configuration directory path to settings.php.
Any other deployments of the site would then make use of the directory defined in settings.php.
* The hash itself is not information that needs protection, but it helps make the configuration harder to find in case it were not properly protected from public access.
If you're making your entire configuration public in a repository, it is important to check that it does not contain any compromising information (e.g. API keys).

---

The configuration should be protected by .htaccess (which core does by default) if it is in a publicly accessible directory, making it impossible to read and not just difficult to find.

It is possible to move the sync directory to another location.
Pantheon places it in `sites/default/config`, with an .htaccess file to protect it.
Alternately, setting up your repository so that Drupal is not in the root folder (as Acquia does) will allow creating a configuration directory that is outside of the document root.

```
/
|-- docroot
|    |-- core
|    |-- modules
|    |-- ...
|
+-- config
     +-- sync

```
> 5 votes

---
Tags: configuration, files, staging, 8
---


# Question
Title: How to get drush to list ONLY parent folders on module list command?
I use this command to get a list of contrib enabled modules:

```
drush pm-list --type=module --status=enabled --no-core --format=list

```

Problem is, it also lists submodules, for example:

```
admin_menu
admin_menu_toolbar

```

So if I use this to reinstall the modules on another site:

```
Drush dl admin_menu admin_menu_toolbar

```

It causes errors. So I need to drush only:

```
Drush dl admin_menu

```

So how can I get the list of ONLY parent modules?

My goal is to get drush to display list of modules on the source site, but only folder names, not subfolders

# Answer
You are looking for the pm-projectinfo command. See: http://drushcommands.com/drush-8x/pm/pm-projectinfo/

In Drupal, "projects" contain "extensions". An "extension" can be either a module or a theme. `drush pm-list` will show a list of modules and themes; `drush pm-projectinfo` shows a list of projects.

*UPDATE:* If you want to convert an existing site into a reproducible, buildable script, you might also be interested in using Composer. See https://github.com/drupal-composer/drupal-project and https://www.drupal.org/project/composer\_generate
> 3 votes

# Answer
When installing the modules, if you use "drush pm-enable ..." ("drush en ..." for short) drush will sort out the dependencies for you and just download the ones you need.

http://drushcommands.com/drush-7x/pm/pm-enable/
> 1 votes

# Answer
Since I don't have high enough reputation to comment on Greg's, I post a new answer - which is a minor improvement to Greg's answer:

```
drush pm-projectinfo --format=list --fields=x,y --status=enabled

```

This works because the list format returns the array key if multiple fields are selected - no matter what the fields are called ;-) The benefit of this compared to just listing the directory content is that you can use the status filter.
> 1 votes

# Answer
Ok, found a solution. If someone can add how to do this with Drush it would be great, but not sure if possible...

I use the command prompt in Windows 7:

```
C:\layouts\sites\all\modules

```

Then:

```
 DIR /B C:\layouts\sites\all\modules

```

This gives me a very clear, clean list of modules WITHOUT subfolders.

I can then use this list to repopulate sites without errors.
> 0 votes

---
Tags: drush
---


title: Paragraphs preprocess

text:
# Question
Title: Paragraphs preprocess
I want to give content editors the ability to add a Feed of some sort (Maybe Twitter, Tumblr, etc) to a particular node. I'd like to use Paragraphs because I want them to be able to drop this Feed in between various other pieces of content.

The Paragraph Bundle would just have one field to accept the resource URL. I would do all the necessary processing behind the scenes and would send the formatted content back to the node via a twig template.

I've got a version working using a block instead of a paragraph bundle, and I'd like to use the same custom module to allow for a paragraph, but I'm unsure in Drupal 8 how best to structure this.

The best I can come up with, is a preprocess function of some sort- preprocess\_node, or preprocess\_paragraph (which I think exist in D8) that would kick off the whole thing, but I was wondering if there was some kind of base Entity class that has a method I can overwrite or something. (Similar to how the BlockBase class has the "build" method.)

# Answer
> 2 votes
A paragraph is a content entity with fields, that is viewed within its parent entity. It uses exactly the same mechanism to be displays as nodes, comments, and so on. Through field formatters.

You can implement your own field formatter plugin that transforms your (link?) field in any way you want. You receive field items and have to return a render array. That's the only restriction.

Like all plugins, it's a class with an annotation, in a specific namespace/folder. The default formatter for link fields is LinkFormatter. The most important method is viewElements().

---
Tags: 8, theming
---


# Question
Title: Possible to prepopulate an inline entity form multiple with a url parameter?
Is is possible to add multiple entries into an inline entity form field with url parameters

I am able to populate almost any other field with the prepopulate module, just having difficulty with the IEF.

Scenario:

I have two content types of quote, and sales order. each of which has an entity reference of inventory (another content type) which has IEF as its widget.

I want to be able to create a sales order off of the quote, and bring over all the values of the entity reference field to the quote. The issue is i want to maintain the data on the quote, but be able to edit the "same" data on the sales order.

# Answer
Please try with Entity reference autofill and Entityreference prepopulate Modules.

1. Add an entity reference field in your entityform.
2. The entity reference autofill will automatically fill reference value into field. We can load default value from URL. (`?field_name = value`)
3. Entityreference prepopulate will prepopulate the values. (you have to add existing fields for that.)

For more details please refer project page.

Another approach is,

> If you want to do this by coding, Just pass **nid** through url and use node\_load() to load that node and create an entity form submission. If you want to create entity form with node creation use hook\_node\_insert or hook\_node\_presave.

Hope this will help you.
> 3 votes

---
Tags: 7, entities
---


# Question
Title: Adding jQuery to a view (exposed filter: search terms)
I'd like to add some jQuery (for search highlighting) to my Drupal 7 Views with exposed search terms filter. The point is that when a user clicks a search terms (or terms) the jQuery then highlights those words they searched for in the returned results.

I created the following preprocess function in my template.php file:

```
    // add jquery.highlight-5.js just to the search views page
    function themename_preprocess_node(&$variables) {
      if(arg(0) == 'node' && arg(1) == '8' && arg(3) == null) {
        drupal_add_js(drupal_get_path('theme', 'themename') .
'/js/jquery.highlight-5.js');
      }
    }

```

But as I put this together I realize I don't know what to put in arg(1) for my Drupal View. Anyone know how to find out the 'nodeid' of the Drupal View?

# Answer
> 2 votes
Use hook views pre render instead.

```
function themename_views_pre_render(&$view) {

   if ($view->name == 'view_name' && $view->current_display == 'block_1') {
    drupal_add_js(drupal_get_path('theme', 'themename') . '/js/jquery.highlight-5.js');
   }
}

```
* replace **themename** with your theme name
* replace **view\_name** with your view name
* replace **block\_1** with your machine name

---
Tags: views, theming, javascript
---


# Question
Title: Restricted access on reference field type?
I've created a new field in Drupal 8, the field type is an Entity Reference and the type of item is set to *Field Storage*.

When I edit my page, I select the node I want to reference, save and publish, but nothing shows on the page, when I go back into edit, the field it says:

> – Restricted access – (node.field\_field\_name)

What's going on?

# Answer
The reason you see that is that you don't have view access to field storages.

In Drupal Core, there is no access control handler for them because they're managed behind the scenes and never really edited/viewed/deleted. That happens automatically through field configs.

You can add implement `hook_field_storage_config_access()` (look for `hook_ENTITY_TYPE_access()` for documentation) and allow view access to your users. But....

> I'm trying to find a way to create an index for a content type based off of several of the fields found on each page.

I don't understand that. I'm not sure you're on the right track and before spending time to implement access control, I'd try to confirm that.
> 1 votes

---
Tags: entities, 8
---


# Question
Title: Remove "Submitted by [user] on [date]" from content shown on a Views page
How does one remove the "Submitted by \[user\] on \[date\]" bit from content shown on a Views page?

I am assuming it is to remove some php code, but unsure what php file the code lives in. (I tried node.tpl.php)

I am using Drupal 7 Bartik theme.

Thanks in advance.

# Answer
Go to Administration \> Structure \> Content Types. Find the content type on which you want to disable author information, click edit. At the bottom of the edit page you'll click on "Display settings" and uncheck "Display author and date information".

This will disable the display of author info for all content view modes, but you will still be able to pull out this info when constructing a View via Views module if you need to.
> 2 votes

---
Tags: views
---


# Question
Title: How do I save patched core after new upgrade?
I had to apply custom patch on Drupal 7 core and now I'm afraid that after rolling a new minor-upgrade over, it'll overwrite my changes.

Is there any way for me to preserve my changes even after upgrading to a new minor patch of core (in case that this patch haven't been applied to that version I'm upgrading to ), like creating a patched folder or something and make sure that my core stays operational?

# Answer
Normally you should never hack the Drupal core. However, there are few exceptions:

* you're applying patch downloaded from Drupal.org which has been QA tested,
* you're applying patch implemented by people who're extremely familiar with the Drupal code base, development practices, and security model,
* you've tested the patch using unit tests (SimpleTest) included with your Drupal core and you properly document the change (e.g. by practicing proper revision control with your code).

If you decide for that, you should keep the patches well documented and ideally in your repository (e.g. one level up from Drupal docroot level, Drupal core folder, or create new `patches/` folder for that).

Then each time you upgrade your Drupal core, you need to remember to apply those patches again (this should be part of your Drupal upgrade steps).

To automate this, you've the following possibilities:

* using `drush` command to upgrade your core (e.g. as part of the script):

```
drush -y up drupal
find . -name "*.patch" -depth 1 -print -exec sh -c "patch -p1 <'{}'" ';'

```
* using `drush` make, e.g.:

+ `.make` file\` (see: Full example drupal-org.make file)

    ```
    api = 2
    core = 7.x
    projects[drupal][patch][] = http://drupal.org/files/issues/992540-3-reset_flood_limit_on_password_reset-drush.patch
    projects[drupal][patch][] = http://drupal.org/files/issues/object_conversion_menu_router_build-972536-1.patch

    ```
    + YAML file (see: examples/example.make.yml)

    ```
    core: "7.x"
    api: 2
    projects:
      drupal:
        version: ~
        patch:
          - "https://www.drupal.org/files/issues/add_a_startup-1543858-30.patch"

    ```

If you're not working on make files, you can still download Drupal core files into empty folder, this will automatically apply the patch files, maybe consider running some unit test, then replace your generated files into your Drupal core instance.
* upgrading and patching manually in Drupal docroot:

```
curl https://ftp.drupal.org/files/projects/drupal-7.4?.tar.gz | tar xvf - --strip-components=1
patch -p1 < add_a_startup-1543858-30.patch

```
> 4 votes

# Answer
The best practice is to find some way to implement your feature that does not require patching the original core. You should try to read - Why don't we hack core?

Anyway, if you still want (or need) to maintaining your Drupal Core with a patch you can use any of this projects to manage your patches.

> This project seeks to solve the following problems:
>
> * How do I document what patches I've applied to a project?
> * How do I reliably know what patches are applied or not without manually checking every single one?
> * How can I be reminded that I need to reapply a patch after downloading a module update?

> Drush tool for helping with patch management on Drupal, which helps with patching, and upgrading modules.
> 3 votes

---
Tags: 7, upgrading, version-control
---


# Question
Title: How to change DB active config storage of an installed site to config file storage?
The `default.settings.php` says

```

/**
 * Active configuration settings.
 *
 * By default, the active configuration is stored in the database in the
 * {config} table. To use a different storage mechanism for the active
 * configuration, do the following prior to installing:
 * - Override the 'bootstrap_config_storage' setting here. It must be set to a
 *   callable that returns an object that implements
 *   \Drupal\Core\Config\StorageInterface.
 * - Override the service definition 'config.storage.active'. Put this
 *   override in a services.yml file in the same directory as settings.php
 *   (definitions in this file will override service definition defaults).
 */
# $settings['bootstrap_config_storage'] = array('Drupal\Core\Config\BootstrapConfigStorageFactory', 'getFileStorage');

```

I have added above code to my `settings.php` and this is the piece of code I have added in `services.yml` before install.

```

services:
  config.storage.active:
    class: Drupal\Core\Config\FileStorage
    factory_class: Drupal\Core\Config\FileStorageFactory
    factory_method: getActive
    public: false

```

How can I change the DB config storage to file config storage after site install? We have config\_db.module to change it form file storage to DB storage. Do we have a module to change it from DB storage to file storage?

# Answer
Here are the steps I followed:

1) Export settings to your current $config\_directories\['sync'\] directory (by default it is defined in settings.php and it is something like 'sites/default/files/config\_VerYlonGkEY0123/sync')

```
$ drush cex

```

2) Create these directories (should be writable):

```
config/
  active/
  staging/
  sync/

```

3) Copy/paste all files from $config\_directories\['sync'\] to config/active/

4) Add the new settings to settings.php

```
$config_directories = array(
  CONFIG_ACTIVE_DIRECTORY => DRUPAL_ROOT . '/config/active',
  CONFIG_STAGING_DIRECTORY => DRUPAL_ROOT . '/config/staging',
  CONFIG_SYNC_DIRECTORY => DRUPAL_ROOT . '/config/sync',
);

$settings['bootstrap_config_storage'] = array('Drupal\Core\Config\BootstrapConfigStorageFactory', 'getFileStorage');

```

5) Add this to service.yml (in the same directory as the settings.php):

```
services:
  config.storage:
    class: Drupal\Core\Config\CachedStorage
    arguments: ['@config.storage.active', '@cache.config']
  config.storage.active:
    class: Drupal\Core\Config\FileStorage
    factory: Drupal\Core\Config\FileStorageFactory::getActive

```

6) Export the settings to sync:

```
$ drush cex sync

```

Than you should have the settings in config/sync :)
> 1 votes

---
Tags: 8
---


title: Drupal 8 route not found

text:
# Question
Title: Drupal 8 route not found
I keep having a 404 error no matter what I change on my routing file.

I've created a module in `modules\custom` which have :

* An info file in `modules\custom\first_module\first_module.info.yml`:

> ```
> name: First module
> core: 8.x
> type: module
> package: Training modules
> description: First Module created to learn coding in D8
>
> ```

* A Routing file in `modules\custom\first_module\first_module.routing.yml`:

> ```
> first_module_hello_world:
>   path: '/hello-world'
>   defaults:
>     _controller: '\Drupal\first_module\src\Controller\TrainingModule:helloWorld'
>   requirements:
>     _permission: 'access content'
>
> ```

* A controller in `modules\custom\first_module\first_module.routing.yml`:

> ```
> <?php
> /**
>  * @file
>  * Contains \Drupal\hello_world\Controller\HelloWorldController.
>  */
>
> namespace Drupal\first_module\src\Controller;
> use Drupal\Core\Controller\ControllerBase;
>
> /**
>  * Controller routines for hello_world module routes.
>  */
> class TrainingModuleController extends ControllerBase {
>
>  /**
>   * Return the 'Hello World' page.
>   *
>   * @return string
>   *   A render array containing our 'Hello World' page content.
>   */
>  public function helloWorld() {
>   $output = array();
>
>   $output['hello_world'] = array(
>     '#markup' => $this->t('Hello World!'),
>   );
>   return $output;
>  }
> }
>
> ```

Any help would be greatly appreciated !

Edit: The Module is activated and I cleared the cache several times.

# Answer
In `first_module.routing.yml`, controller there is no src and you use 2: ::

```
first_module_hello_world:
    path: '/hello-world'
    defaults:
        _controller: '\Drupal\first_module\Controller\TrainingModule::helloWorld'
        _title: 'hello world'
    requirements:
        _permission: 'access content'

```

Also without src in drupal 8 there si no need to use `return $output;` Alsi class is not good. Class is TrainingModule not TrainingModuleControlle and file need to cole the some TrainingModule

```
namespace Drupal\first_module\Controller;
use Drupal\Core\Controller\ControllerBase;

/**
 * Controller routines for hello_world module routes.
 */
class TrainingModule extends ControllerBase {

 /**
  * Return the 'Hello World' page.
  *
  * @return string
  *   A render array containing our 'Hello World' page content.
  */
 public function helloWorld() {

  return array(
    '#type' => 'markup',
        '#markup' => $this->t('Hello World!'),
  );
 }
}

```

change `first_module_hello_world`: to `first_module_hello_world.help`:

make the file `first_module_hello_world.module` and write this code

```
function first_module_hello_world_help($route_name, $route_match) {
 switch ($route_name) {
  case 'first_module_hello_world.help':
    $output = '';
    return $output;
 }
}

```
> 1 votes

---
Tags: 8, routes
---


# Question
Title: How do I make variables available for all blocks in a page?
In my website I have an inc file containing some values that are needed on all blocks of a page. For reasons related to the performances, I would like not to use the php "require" function in each block. Is there a way to load this file at page level and make the values available in all blocks?

Do I have to do that in the `template_preprocess` function?

# Answer
> 2 votes
Yes this can be done in `hook_preprocess_block`.

inc file:

```
function get_some_vars() {
  static $vars = array();

  if (empty($vars)) {
    $vars['foo'] = expensive_function_1();
    $vars['bar'] = expensive_function_2();
  }

  return $vars;
}

```

.module/template.php file:

```
function MYMODULE_preprocess_block(&$vars) {
  require_once 'my.inc'; // or module_load_include, depends where your code is

  $vars += get_some_vars();
}

```

It's not the exact desired workflow you described in the question, but it has a similar effect; `require_once` will only include the file once per request, and the variables will only be prepared once per request. There is the function call overhead, but given that themes don't have the concept of always-available-vars (as far as I know each theme call is an isolated instance as it were), I think this is the closest you'll get without patching the theme system.

---
Tags: 7, blocks
---


# Question
Title: How to display the user picture on the search page?
I want to show the user picture on the search page. Currently only its show the user email or name, but I want to show the user profile picture.

How can I do that?

**Note**: the search page is about the user type, so when I search some users their picture should be displayed on the search result page.

# Answer
Copy the file `YOUR_SITE/modules/search/search-result.tpl.php` to your theme and modify the code inside with this:

```
<?php
//obtaining the username
$username = explode('(', $title);
$username = trim($username[0]);
//getting the user object
$user = user_load_by_name($username);
?>
<li class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php print render($title_prefix); ?>

  <?php
  /*
   * The following line will print the user picture
   */
  print theme('user_picture', array('account' =>$user));
  ?>

  <h3 class="title"<?php print $title_attributes; ?>>
    <a href="<?php print $url; ?>"><?php print $title; ?></a>
  </h3>
  <?php print render($title_suffix); ?>
  <div class="search-snippet-info">
    <?php if ($snippet): ?>
      <p class="search-snippet"<?php print $content_attributes; ?>><?php print $snippet; ?></p>
    <?php endif; ?>
    <?php if ($info): ?>
      <p class="search-info"><?php print $info; ?></p>
    <?php endif; ?>
  </div>
</li>

```

This will be the output:

**EDIT:** If you want follow another way you can read this: How to access to the user info on the search page?
> 3 votes

---
Tags: 7, theming, users, search
---


# Question
Title: Drupal 8 Ajax Callbacks misbehaving when form element in table
I have a form containing the following element:

```
  $form['check'] = array(
    '#type' => 'checkbox',
    '#title' => t('Test'),
    '#ajax' => array(
      'callback' => array($this, 'updateTestCallback'),
      'event' => 'change',
    ),
  );

```

With the following simple Ajax handler:

```
  public function updateTestCallback(array $form, FormStateInterface $form_state) {
    $triggering_element = $form_state->getTriggeringElement();
    $ajax_response = new AjaxResponse();
    $ajax_response->addCommand(new AlertCommand($triggering_element['#name']." = ".$triggering_element['#value']));
    return $ajax_response;
  }

```

This works perfectly when the control is on a plain form, but I want to have a checkbox on every row of a table, and this is where I'm having problems.

I tried using a `#table` entity, and the checkboxes display correctly, but the Ajax callback event only gets called on every other click (i.e. one click it works, the next nothing happens, the next it works again).

So I should the problem might stem from from the `#table` entity, so I changed the form to build the table manually using `#prefix` and `#suffix` containing the table elements, but this is behaving exactly the same way, so it seems to be the presence of the table elements rather than the way they were generated that's causing the problem.

Here's the current `build_form` function:

```
  public function buildForm(array $form, FormStateInterface $form_state, $mid = NULL, $key = NULL) {
    $form = array(
      '#prefix' => '<div id="memberform">',
      '#suffix' => '</div>',
    );

    // Test checkboxes outside table:
    $form['check'] = array(
      '#type' => 'checkbox',
      '#title' => t('Test'),
      '#ajax' => array(
        'callback' => array($this, 'updateTestCallback'),
        'event' => 'change',
      ),
    );
    $form['check2'] = array(
      '#type' => 'checkbox',
      '#title' => t('Test2'),
      '#ajax' => array(
        'callback' => array($this, 'updateTestCallback'),
        'event' => 'change',
      ),
    );

    $form['table'] = array(
      '#prefix' => '<table id="member-list">',
      '#suffix' => '</table>',
    );

    $form['table']['tbody'] = array(
      '#prefix' => '<tbody>',
      '#suffix' => '</tbody>',
    );
    // Retrieve data and builr one table row per record.
    foreach ($entries = MyStorage::myListLoad() as $entry) {
      $mid = $entry['mid'];
      $is_paid = $entry['is_paid'];
      $row = array(
        '#prefix' => '<tr>',
        '#suffix' => '</tr>',
      );
      $row['first_name'] = array(
        '#markup' => SafeMarkup::checkPlain($entry['first_name']),
        '#prefix' => '<td>',
        '#suffix' => '</td>',
      );
      $row['last_name'] = array(
        '#markup' => SafeMarkup::checkPlain($entry['last_name']),
        '#prefix' => '<td>',
        '#suffix' => '</td>',
      );
      $row["is_approved_".$mid] = array(
        //'#attributes' => array('name' => 'is_approved_'.$mid, 'id' => 'edit_is_approved_'.$mid),
        '#type' => 'checkbox',
        '#title' => t('Is Approved'),
        '#title_display' => 'invisible',
        '#ajax' => array(
          'callback' => array($this, 'updateTestCallback'),
          'event' => 'change',
        ),
        '#prefix' => '<td>',
        '#suffix' => '</td>',
      );
      $form['table']['tbody'][$mid] = $row;
    }
    return $form;
  }

```

Has anyone come across this problem, and can you suggest a way around it?

James

# Answer
It's hard to tell without seeing some code of the table. There is probably an error in the structure of the form array. All form elements must have the correct key in the array, which correspondent with the #name. And this keys and names must be unique in the whole form. If you put a form element in a table, use an extra layer to give the element the right key.
> 1 votes

---
Tags: forms, ajax, 8
---


# Question
Title: How to move the user account/Profile 2 information from the content region to a sidebar region
On the "My Account" page i.e. /user, the account and Profile 2 information is by default residing in the content region. I would like to move everything to the right sidebar region. Any suggestions on how I can achieve this ?

I am using Bartik

Thanks in advance.

# Answer
> 1 votes
You can create a View (show Users) with display "block" and add User:ID as Context Filter. For the Context Filter set "When the filter value is NOT available" to "provide default value - User ID from URL". Add all user fields that you would like to output to your view. Created Views block will then be listed on you Blocks page (structure \> blocks). Once the block is there, you can drag it into the sidebar region.

If you need to remove user profile fields that are rendering in content region by default or override them, you can do so by overriding "modules/user/user-profile.tpl.php" - copying it into your theme's template folder and replacing the line that renders user profile - `<?php print render($user_profile); ?>` with the desired content.

Page Manager Existing Pages \+ Panels is another convenient method of changing the layout of user profile. This method will work in combination with existing layout regions.

---
Tags: 7, users, theming
---


title: Is possible to transfer files with FTP?

text:
# Question
Title: Is possible to transfer files with FTP?
I connected to a site using SSH with Drush. Is there a way to use FTP with Drush?

# Answer
> 6 votes
Drush does not have a built-in wrapper for ftp / sftp, but you can do the same operation using rsync. If you have rsync, setup your drush aliases for it. You can then copy the code and (upload) files for the site via:

`drush rsync @mysite.dev @mysite.live`

You can copy just the (upload) files via:

`drush rsync @mysite.dev:%files @mysite.live:%files`

This will use the same credentials that you already set up to use ssh with Drush.

---
Tags: drush
---


# Question
Title: How to access to the user info on the search page?
When I was trying to resolve this question: How to display the user picture on the search page? I found that in the THEME\_preprocess\_search\_result function I can't access to the user information (I use the user search functionality) the only information about the searched users that I can use is the follow:

```
function THEME_preprocess_search_result(&$variables) {
    dpm($variables);
}

```

I can use the username and the email, I can extract from $variables\['result'\]\['title'\] the username, but I think that the best way is access directly to the uid of the searched user. The problem is that I don't know how access to this information.

So, there is another way to obtain the uid of a searched user?

**EDIT:** I need the info of the system users (drupal users). User is not a content type.

# Answer
> 2 votes
Did you try implementing `hook_preprocess_search_results` (notice the plural search results)?

I haven't tested recently and I'm on a mobile right now. But I'm pretty sure that hook somehow had node objects (should be user objects in your case). Collect the UIDs, run a `user_load_multiple` and then add the user objects to each result for profit in `hook_preprocess_search_results`.

**Update**

I'm no longer on my mobile, so I could actually test this. It turns out that the `user` module does not feed the results set with the user account. I don't think Drupal 7 will receive these features anymore, so you'd have to patch the core `user.module` to achieve that.

Here is a patch if you are interested in going down that path: https://gist.github.com/Ayesh/b1892942b053dc746fb5

---
Tags: 7, users, search
---


# Question
Title: hook_form_user_register_form_alter() does not customize user registration form
I have implemented a `hook_form_user_register_form_alter()`.

```
function hook_form_user_register_form_alter($form, $form_state, $form_id) {
  $form['account']['name']['#description'] = 'This is your login name. It will be displayed on the forums and in comments. This is not your billing information. Spaces are allowed; punctuation is not allowed except for periods, hyphens, apostrophes, and underscores.';
  $form['actions']['submit']['#value'] = 'Continue to subscription and payment page.';
  $form['#submit'][] = 'custom_user_register_submit';

  dpm($form);
}

```

When I use the registration page, I get mixed results. First of all, my `custom_user_register_submit()` function is called when I click the submit button. This is correct.

However, I get no changes to the form elements printed on the user registration page. For example, but button should have custom text. It does not; it uses the default text 'create new account'. Strangely, in the output from my dpm(), the values in those array elements match my custom code! So, it looks like my hook is implemented correctly and the form elements are being changed, but later in the Drupal bootstrap, they are overridden again and brought back to their defaults.

Anybody know a solution?

# Answer
For all Drupal `_alter` hooks, you need to pass the variables you need to change as references.

In your function, declaration, `$form` should be `&$form`. This makes PHP pass a reference of that variable to inside if your function scope, so changes you make to the `$form` array persist.

So the function declaration should look like this (to alter both variables): `hook_form_user_register_form_alter(&$form, &$form_state)`
> 7 votes

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


# Question
Title: Panels not showing default image set in Field settings of content type
The image you upload to be as a default image for all pages where you didn't upload custom images for each page, so it would show same one image from the content type settings.

It works in Preview when editing the node and it shows in non-panel pages.

In Panels it doesn't render entire field. But if you upload the custom image then it does show it. But not the default one.

I don't get it why

# Answer
This is an issue with CTools. Apply the patch from Default value of image field is not shown
> 0 votes

# Answer
For me the solution proposed by Stephen Martin did not work. I had to apply this patch (Comment #22) instead: https://www.drupal.org/node/2437773. This fixed the problem.
> 0 votes

---
Tags: 7, entities, panels
---


# Question
Title: Separate Domain users get redirected to Default domain upon login and content save
I have set up Domain Access module in Drupal correctly, and everything works fine but with an issue. The issue is, that when a subdomain user logs in with his account from his assigned domain, he gets redirected to main domain and finds an access denied page. Then he manually goes to subdomain.domain.com and it works fine then. Similarly, if he save any node from his assigned domain, node works fine, is shown only upon his domain, but upon save, he is redirected to the main domain, and the node path is maindomain.com/urlalias, which causes him to show access denied.If he then goes to subdomain.com/urlalias of the node he just created, it shows fine without any problems. How to settle this issue, I have spent days sorting it out but still no success

# Answer
> 1 votes
After plenty of fatigue , I ended up removing $base\_url from settings.php and the problem was solved. But still I wonder what if I have to ever to use $base\_url again, the problem will again creep up.

---
Tags: domain-access
---


# Question
Title: Sending Email verification when registering programmatically
I have created multi-step form through custom module. I am `using user_save()` function to register the user and `user_mail_notify()` to send the email.

Now I am not sure what should I send in `_user_mail_notify()` so email verification link will work.

I have account settings in the backend as shown in screenshot

and sending **op** value as '**register\_no\_approval\_required**' in `_user_mail_notify()` function. I am receiving verification email in inbox but when I click it then it doesn't work.

However it works when we register through default registration form. Please let me know if anything I am missing to add.

# Answer
> 1 votes
When you create a new account using "user\_save()", What status you passed "0" or "1", If you required email verification then it should be 'status' =\> 0, in user\_save().

# Answer
> -2 votes
Solved, My problem are email service on server.

Now I use smpt (https://www.drupal.org/project/smtp)

It's ok.

---
Tags: 7, users, emails
---


title: Drupal is not sending emails: Why?

text:
# Question
Title: Drupal is not sending emails: Why?
My drupal8 is not send an email. How can I do.

It's not send in every progress (contact, user registration)

Help me please

# Answer
> 1 votes
First you need to determine if it's Drupal not sending the email or if it's the web server where the website is hosted.

Check if the webserver is set up with an application such as 'postfix' in order to send the email. This is easy to test if you can SSH into the server, or you can check with the hosting company.

---
Tags: 8, emails
---


# Question
Title: How to display menu block but deny adding a new instance?
I have a menu which has a block provided by the system automatically. This menu has links that come from a module which defines the menu(config). This menu block can be seen(ie. the block is visible) but it shouldn't be possible to attach another instance of this menu nor put links into it via UI. I do not want the admin so see this menu block in the list of available blocks on the block library page.

So far I have been able to tweak things so that some specific menus are not available for user to put links into or even see them in the menu listing(I have custom list builder for this + some form alterations in place). But when it comes to blocks the issue is that on some places Drupal checks plugin definitions(which are cached so I cannot distinguish if the user is on the "manage blocks" page or somewhere else or if the user has specific permissions and such) and in other places it uses the block entities.

So my question is how can I hide a block from the block library but keep the block displayed when attached to a region? If I remove the plugin definition the bloc kwon' be displayed since the plugin will be non existing. This works in other cases that I have but not int this one.

I think this relates to https://www.drupal.org/node/1975064 but I need to fix this ASAP.

# Answer
> 0 votes
So at the end my solution in regard to blocks was to create route access check for the block.admin\_add route to prevent attaching unwanted blocks, override the controller for the block.admin\_library route by extending the original one and removing unwanted blocks from the list, implementing hook\_block\_access to prevent certain operations on certain blocks and hook\_block\_filter to remove some blocks completely.

---
Tags: 8, blocks, plugins
---


title: drupal 8 image dialog position

text:
# Question
Title: drupal 8 image dialog position
I really hope somebody can help me out with this: I'm designing a Drupal 8 project and I'm using the built-in CKeditor to edit articles. But the image popup renders outside of screen bounds and I can't find how to fix that. There seems to be no way to influence the top parameter of the dialog.

Thanks a lot!

Matt.

# Answer
Im not able to reproduce it on my drupal 8 projects. It might come from your front-end theme. Try to use an administrative theme for edition, like seven.

{yoursite}/admin/appearance At the bottom of the page check use administrative theme for editing.

If the issue doesn't occur anymore on theme seven, you should start by checking in your front-end (custom?) theme for styles on thoses classes :

```
ui-dialog ui-widget ui-widget-content ui-corner-all ui-front editor-image-dialog ui-dialog--narrow ui-dialog-buttons

```
> 1 votes

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


# Question
Title: How to override default page.tpl from a module, for a specific page?
I am coding a module which contains a "please wait" page.

On this page I need to override the default page.tpl template so I can render the "please wait" message alone without all the other regions and "site chrome".

How do I tell drupal not to use the default page.tpl and use my page-special.tpl for the specific "please wait" page ?

**EDIT**

*Please note that I am coding a module, not a theme. So everything should be done from inside the module.*

# Answer
As per Stuart Clark's advice

All you have to do is to create a template, for example : mymodule/theme/special-page.tpl.php

and add this to your module

```
function mymodule_theme(){
  return array(
    'special_page' =>  array(
      'template' => 'theme/special-page',
      'render element' => 'page'
    ),
  );
}

function mymodule_preprocess_page(&$variables, $hook) {
  if ( my_condition() ) {
    $variables['theme_hook_suggestions'][] = 'special_page';
  }
}

```
> 18 votes

# Answer
You see, almost every page callback declared in hook\_menu is wrapped in both html.tlp.php and page.tpl.php. That's because most modules will not declare the menu item's delivery callback, and it defaults to drupal\_deliver\_html\_page. You can declare your own delivery callback and use a custom theme function (see hook\_theme) to render your page. It will also make overrides easier for themers.
> 2 votes

# Answer
You should make a copy of `page.tpl.php` and rename it `page--node--1.tpl.php` Then you can style the new page. When you create the new file, remember to clear the cache. You can find more info here http://drupal.org/node/1089656 and here
> 0 votes

# Answer
You can use this hook

```
function theme_preprocess_page(&$variables, $hook) {
$variables['theme_hook_suggestions'][] = 'page__special';
}

```

but you should have a tpl called page--special.tpl.php
> 0 votes

# Answer
try using this

```
function mymodule_menu()
{
 $items['test'] = array(
        'title' => t('Testing'),
        'page callback' => 'test',
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK,
    );
return $items;
}

function test()
{
    return theme('test');
}
function mymodule_theme(){
    return array(
        'test' => array(
            'template' => 'test'//name of template file, place test.tpl.php in your module
        )
    );
}

```
> 0 votes

# Answer
I cannot find a way to override the html.tpl.php in my module. My use case was to create an "interstitial" page to display pre-roll video or an ad, similar to how forbes.com does it. Here is the user story:

"As a user, my first visit to the site will present me with an interstitial page before viewing content. WHen the page is displayed, a cookie is set in the user's browser preventing the interstitial from displaying on subsequent visits for the next 24 hours."

I created a hook\_menu creating a page with a path called "welcome"

```
/**
 * Implements hook_menu().
 */
function liveinterstitual_menu() {
  $items = array();

  $items['welcome'] = array(
    'title' => 'Welcome to San Angelo LIVE!',
    'page callback' => 'liveinterstitual_welcome_page',
    'page arguments' => array(),
    'access arguments' => array('access content'),
  );
  return $items;
}

```

The page callback is liveinterstitual\_welcome\_page(), and it looks like this:

```
function liveinterstitual_welcome_page() {
  // If you want the sidebars and everything in the theme layer, uncomment the next line
  //return theme('liveinterstitual', array('content' => $content));
  //else, to spit out a static html page, save the page to this module's dir and do this:
  echo file_get_contents( drupal_get_path('module','liveinterstitual') . '/liveinterstitiual.html');
  //Shut down Drupal cleanly
  drupal_page_footer();
}

```

In short, I byassed the entire theme payer by piping the contents of a flat html file. Drupal has similar functions in core that do this by delivering a JSON array for ahah callbacks, for example.

I am open to other ideas, but this one appears to work for now.
> -1 votes

---
Tags: theming, 7
---


# Question
Title: What is the difference between {{ |t}} and {% trans %}?
I notice that Drupal 8 support `{% trans %}` which, according to the Symfony documentation (The i18n Extension), adds gettext support to Twig.

`{{ |t }}`, as far as I know, is the legacy way to add translatable strings into Drupal templates. According to the documentation, `t()` translates a string to the current language or a given language.

Both support multi-language website.

* What are the differences between those extensions?
* When should I use one over the other one?

# Answer
> 25 votes
Both the `{{ |t }}` filter and `{% trans %} ... {% endtrans %}` blocks, when used in the context of Twig template file in Drupal, are part of the Drupal localization system. And translation for strings processed with either one are handled in the same way, and via localize.drupal.org. For simple strings of text they can be used interchangeably, however the `%trans` block has some additional useful features for complex strings.

The difference is that the `t` filter only allows for simple strings, while using a `%trans` block allows the use of dynamic placeholders in the string. Much like using the php `t()` function.

Here's a few examples:

Simple string translation via `t` filter:

`{{ 'Hello Stack Exchange!'|t }}`

String translation with placeholder:

`{% trans %}Hello {{ user.name }}, today's date is {{ date|placeholder }}.{% endtrans %}`

Placeholders are escaped by default, but can also be left-unescaped `{{ var|passthrough }}` or formatted as a placeholder `{{ var|placeholder }}`. This is equivalent to using @string, !string, and %string in the t() function respectively.

You can also use `%trans` blocks in order to format plural strings.

```
{% trans %}
  There is 1 comment.
{% plural count %}
  There are {{ count }} comments.
{% endtrans %}

```

For simple strings there are really no rules about when you should use `|t` vs. `%trans`. So I would recommend using whatever is easiest to read in your template. In my experience using the `|t` filter works well for short strings, while the `%trans` block is easier for longer strings of text.

More information about usage can be found here: https://www.drupal.org/node/2357633 and here https://www.drupal.org/developing/api/8/localization

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


# Question
Title: Cannot login to my drupal site because of php version 5.6
I have installed drupal 7.36 and developed my site on localhost in XAMPP. After I logget out I'm not able to log in again even if name and password is correct. I have only one user created - admin. After I attempt to log in I get a message

> You are not authorized to access this page.

I can still log in. I have tried every solution I found on Internet:

* Log in with another browsers
* Clear all cookies of browser
* Clear all caches
* Truncate all cache\_ tables, truncate sessions and flood tables
* Set `$cookie_domain = 'localhost'` variable in settings.php
* Add `ini_set('session.cookie_domain', '127.0.0.1')` to settings.php
* Restart apache server
* Create another user programatically and log in as new user
* Log in programatically
* Vacuum/reindex database in pgAdmin

Nothing worked for me. It's really simple drupal website. What exactly could cause this problem?

I've reinstalled my site (and lost my database data) and enabled again my theme and all the modules. I was able to log in and log out, repeatedly. But then I logged out one more time and closed the browser. After reopening the browser, I was not able to log in again, even with other browsers.

# Answer
So finally I found that the problem is with php version 5.6 and workaround is:

```
function aikidolm_user_login(&$edit, $account) {
  $_SESSION['aikidolm']['ulogged'] = 1;
}

```

https://www.drupal.org/node/2363219#comment-9366567
> 0 votes

---
Tags: users
---


# Question
Title: How to bulk delete empty taxonomy terms?
The website has thousands of unused (empty) taxonomy terms and I want to **bulk** delete them.

With views all empty terms can be listed but it's not possible to delete them via Views (VBO etc).

I saw that taxonomy terms should be cleaned with `taxonomy_term_delete()` in this question: How to delete true orphaned taxonomy terms. But I don't know where to use it? **Should I create a block and put the code inside it or a custom module or anything else?**

(I also tried the Delete Orphaned Terms module but couldn't be sure if it's working properly. I tried it on a dev. site but couldn't check the results.)

# Answer
> 4 votes
A quick solution:

Go to your folder theme and edit the `node.tpl.php` and put this code at the top of the file:

```
<?php

$query = "
SELECT taxonomy_term_data.tid AS tid
FROM
{taxonomy_term_data} taxonomy_term_data
LEFT JOIN {taxonomy_index} taxonomy_index ON taxonomy_term_data.tid = taxonomy_index.tid
LEFT JOIN {node} node_taxonomy_index ON taxonomy_index.nid = node_taxonomy_index.nid
LEFT JOIN {taxonomy_vocabulary} taxonomy_vocabulary ON taxonomy_term_data.vid = taxonomy_vocabulary.vid
GROUP BY tid
HAVING COUNT(DISTINCT node_taxonomy_index.nid) = '0'
";

$tids = db_query($query)->fetchCol();

foreach ($tids as $tid) {
  taxonomy_term_delete($tid);
}
dpm($tids);
?>

```

Then go to visit one of your nodes and the code will be triggered.

Take into account that if you don't eliminate the code from the `node.tlp.php` then every time that you access a node the code will be triggered.

**EDIT: I (quickly) created a little module for you. Is not the best solution but I tested it and it works.**

file: **delete\_unused\_taxonomy\_terms.info**

```
name = Delete Unused Taxonomy Terms
description = Delete all unused taxonomy terms
core = 7.x
package = Administration

configure = admin/structure/delete_unused_taxonomy_terms

files[] = delete_unused_taxonomy_terms.module
files[] = delete_unused_taxonomy_terms.admin.inc

```

file: **delete\_unused\_taxonomy\_terms.module**

```
<?php

/**
 * @file delete_unused_taxonomy_terms.module
 */

/**
* Implements hook_menu().
*/
function delete_unused_taxonomy_terms_menu() {
  $items['admin/structure/delete_unused_taxonomy_terms'] = array(
  'title' => 'Delete Unused Taxonomy Terms',
  'description' => 'Delete Unused Taxonomy Terms',
  'page callback' => 'drupal_get_form',
  'page arguments' => array('delete_unused_taxonomy_terms_admin_settings'),
  'access callback' => 'user_access',
  'access arguments' => array('administer taxonomy'),
  'type' => MENU_NORMAL_ITEM,
  'file' => 'delete_unused_taxonomy_terms.admin.inc',
  );
  return $items;
}

```

File: **delete\_unused\_taxonomy\_terms.admin.inc**

```
<?php
/**
* @file
* Calls results to administration's pages.
*/

/**
* Form constructor for module configuration.
*
*/
function delete_unused_taxonomy_terms_admin_settings($form_state) {
  $form['#submit'][] = 'custom_form_submit';
  return system_settings_form($form);
}

/**
 * Submit handler
 */
function custom_form_submit($form, &$form_state) {
  $query = "
  SELECT taxonomy_term_data.tid AS tid
  FROM
  {taxonomy_term_data} taxonomy_term_data
  LEFT JOIN {taxonomy_index} taxonomy_index ON taxonomy_term_data.tid = taxonomy_index.tid
  LEFT JOIN {node} node_taxonomy_index ON taxonomy_index.nid = node_taxonomy_index.nid
  LEFT JOIN {taxonomy_vocabulary} taxonomy_vocabulary ON taxonomy_term_data.vid = taxonomy_vocabulary.vid
  GROUP BY tid
  HAVING COUNT(DISTINCT node_taxonomy_index.nid) = '0'";

  $tids = db_query($query)->fetchCol();

  foreach ($tids as $tid) {
    taxonomy_term_delete($tid);
  }
}

```

In your module folder make a folder named **delete\_unused\_taxonomy\_terms** put the 3 files inside and install the module.

Then go to `admin/structure/delete_unused_taxonomy_terms` and click the button.

**Reference:**

# Answer
> 3 votes
There's no need to inject code into your code base; Drush is your friend here.

Create a PHP script with the relevant PHP code that bulk deletes then execute the following in your Drupal environment:

```
drush php-script my_deletion_script.php

```

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


# Question
Title: array_flip(): Can only flip STRING and INTEGER values with nested Field collection
I'm getting the error `Warning: array_flip(): Can only flip STRING and INTEGER values! in EntityAPIController->load()` when using a field collection in another field collection.

Is this a bug in Field collection or the way I load the entities? Either way: How can I solve the warning?

Here's a simplified version of how I load my entities and sub-entities:

```
foreach ($node->field_chapter[$language] as $chapter) {
    $items = entity_load('field_collection_item', $chapter);
    foreach ($items as $item) {
        //Some echo's from fields in $item
        foreach ($item->field_paragraph as $paragraphItem) {
            $paragraphs = entity_load('field_collection_item', $paragraphItem);
            foreach ($paragraphs as $paragraph) {
            //Some echos in paragraph
            }
        }
    }
}

```

# Answer
The problem is with your code.

You need to pass entity\_load an array of entity IDs but the structure of a field on an entity is not just an array of IDs.

`$item->field_paragraph` is an array of field items and field items can come in many different structures based on the type of field. Then there is also the ability to have different languages so the language is part of the structure.

The basic structure is like this:

```
$entity->field_name['language code'][delta]['column_name']

```

I think for field collections the entity id is stored in the "value" column so you would access it like this (this assumes you aren't using multiple languages):

```
$item->field_paragraph[LANGUAGE_NONE][0]['value']

```

That would get you the entity ID of the first item for that field.

It is generally considered better though to use field\_get\_items() like this:

```
// Pass a lang code into field_get_items() if you have a multilingual site.
if ($chapter_items = field_get_items('field_collection_item', $node, 'field_chapter')) {
  $chapter_ids = array();
  foreach ($chapter_items as $chapter_item) {
    $chapter_ids[] = $chapter_item['value'];
  }
  $chapters = entity_load('field_collection_item', $chapter_ids);
  foreach ($chapters as $chapter) {
    // Some echos from fields in $chapter.

    // Pass a lang code into field_get_items() if you have a multilingual site.
    if ($paragraph_items = field_get_items('field_collection_item', $chapter, 'field_paragraph')) {
      $paragraph_ids = array();
      foreach ($paragraph_items as $paragraph_item) {
        $paragraph_ids[] = $paragraph_item['value'];
      }
      $paragraphs = entity_load('field_collection_item', $paragraph_ids);
      foreach ($paragraphs as $paragraph) {
        // Some echos from fields in $paragraph.
      }
    }
  }
}

```

When you are using entities and fields like this it is a good idea to do some debugging to check out the actual structure of the data you're trying to use.
> 1 votes

# Answer
Is `$chapter` and `$paragraphItem` an array? It needs to be even if it's just 1 entity id.

If not you could do

```
$items = entity_load('field_collection_item', array($chapter));
$paragraphs = entity_load('field_collection_item', array($paragraphItem));

```
> 0 votes

---
Tags: entities
---


# Question
Title: Differences between 'Add existing field' and 'Add new field'
It is possible to reuse the already created fields via *Add existing field* option. From optimization perspective and the way Drupal stores and manages such fields in database I would like to know, does adding fields this way cause any extra efficacy or not?

# Answer
> 4 votes
*Add new field* is used to create a new field; *Add existing field* is used to connect the existing field with another content type.

I don't think it's a big difference but it's a good option for developer to attach their fields to other content types. For *existing field*, after you have created the new field, you can attach that field to multiple content types.

See also When should I use an existing field?

# Answer
> 3 votes
***Add new field*** is used to create a new field; a new table for storing that field data will be created in the database. It is a simple and easy way of creating a new field.

***Add existing field*** is used to use an existing field of a content type in another content type. All settings of existing fields will be inherited. **Also**, the same database table will be used to store data, cutting off the number of new tables in the . It is a simple and easy way of creating a new field.

**The main advantage of using the existing field** is that in views and in queries, we can use same field, or same query for different content types, we does not need to create different views or queries of same type.

*Suppose*, we want to create a slider of images(from images of contents from different content types) using a view, if we have used the same field, we can make it very easily, calling one field, else we will need lots of customization to do such simple task.

***It is a good practice to use existing fields whenever possible, even Drupal core fields (title, body, etc) are built in same way.***

# Answer
> 0 votes
Its depends on the size of your website. If it's a huge site with lots of data or small site which may grow in near future then I would suggest you to use new fields.Each field has a database table associated with it and if you use reuse fields then table will grow and at sometime this will affect your site performance. By creating new fields, each field will have its own database table and this will less affect your site performance.

On the other hand, if you are doing any back end code and if your site has manageable amount of data. Then you can use reuse fields which makes coding easy. It will also make life with views easier, since you won't have select a from multiple fields.

In short, for each field Drupal create one database table and when you reuse that field, all the values be saved together in same table.

This article will give you more understanding: https://www.ostraining.com/blog/drupal/re-using-drupal-fields

# Answer
> 0 votes
"Add existing field" is a field that you have already created in some other entity. Say, for example: you have a content type video with field "video". Now you want to use the same "video" field in some other content type. You can do so, by choose add existing field option.

In this way, you prevent database forming an new table for some new field and will use existing table of existing field.

As, every new field creates two new tables in database and you prevent this extra occupying space in database by using existing field option.

# Answer
> 0 votes
The Field UI has two parts:

1.A list of field instances of the element being edited (e.g. Basic page or Tags). In the above image, the field instances are Title and Body.

2.A pair of subforms for adding new field instances. These subforms are:

\*.Add new field. This is used to both create a new field and to add an instance of that field to the element being edited.

\*.Add existing field. This is used to add an instance of a field that already exists.

To add images or tags to a page, you use "Add existing field" because when Drupal is first installed, it predefines the fields Image and Tags.

---
Tags: entities, nodes, database, performance
---


# Question
Title: How to make all menu links without www? (shortened menu links)
I've seen a few sites, not necissarily Drupal sites, in which the menu links, are without `www.` (that is the Cname DNS record).

Drupal 7 shortens links from `http://www.barackobama.com` to be `www.barackobama.com`

I am asking if it is possible to create links without the Cname even, I.E that the final result would be:

```
barackobama.com

```

Can be done from inside the Drupal GUI? If not, please at least example how will you do so from the .htaccess file?

# Answer
No, this is something that is been handle at the server or DNS level. From the GUI, you do not have control of where you application (Drupal) can will run.

If you are running Apache you can add this code to your `.htaccess`

```
RewriteEngine On
RewriteCond %{HTTP_HOST} ^your-site.com [NC]
RewriteRule ^(.*)$ http://www.your-site.com/$1 [L,R=301]

```

Source: Force drupal 7 to place "www" in front of urls
> 2 votes

---
Tags: uri
---


# Question
Title: "Valid date is required for date_1" error while using drupal_form_submit()
Field : **field\_date\_1**
Type : **Date**
Widget : **Pop-up calendar**
The settings for date field is as shown in 2 images

I get the values of a form\_state into the $source\_node and move that to $fs variable.The $source\_node has date field stored as follows :

```
 [field_pt_date_1] => Array
        (
            [und] => Array
        (
                    [0] => Array
                        (
                            [value] => 2010-08-27 00:00:00
                            [timezone] => America/Phoenix
                            [timezone_db] => America/Phoenix
                [date_type] => datetime
                        )
             )

```

)

```
 $fs['values']['field_date_1']['und'][0]['value'] = date('m/d/Y', strtotime($source_node->field_date_1['und'][0]['value']));
  $fs['values']['field_date_1']['und'][0]['timezone'] = $source_node->field_date_1['und'][0]['timezone'];
  $fs['values']['field_date_1']['und'][0]['timezone_db'] = $source_node->field_date_1['und'][0]['timezone_db'];
  $fs['values']['field_date_1']['und'][0]['date_type'] = $source_node->field_date_1['und'][0]['date_type'];

```

......... The errors I am getting after executing the above code is as follows :

**A valid date is required for date\_1.**

```
 drupal_form_submit('form_id', $fs, $source_node);
  $errors = form_get_errors();

```

And when checked the $errors variable I get

```
$errors = Array
(
 [field_date_1][und][0][value] => A valid date is required for <em class="placeholder">date_1</em>.
)

```

# Answer
> 1 votes
I was facing similar kind of problem with drupal\_form\_submit.

After spending too much time following solution is working for me

```
    $datetime = $source_node->field_date_1['und'][0]['value'] ;
    $form_state['values']['field_date_1']['und'][0]['value'] = array(
      'date' => date('d/m/Y', strtotime($datetime)),
      'time' => date('h:ia', strtotime($datetime)),
    );

```

Hope it will help someone

---
Tags: 7, entities, datetime
---


# Question
Title: Updating Drupal core in a Acquia Dev Desktop?
Running the latest Acquia Dev Desktop (with subscription) with Drupal 7.22 core.

I´d like to update the Drupal core to the most recent version, but after reading the documentation on Acquia that is available to unsubscribed users, I wonder if that is at all possible. Any ideas on how one would go about this?

# Answer
The question is a bit old, but I think there are two issues here: upgrading **Acquia Dev Desktop** itself, and upgrading the **Drupal core** of a site in Dev Desktop.

For the first, the answer above gives the link where you can find how to upgrade Dev Desktop.

For the second, Dev Desktop now comes with drush bundled in, so the easiest way to upgrade Drupal core is simply `drush @mysite pm-update`
> 1 votes

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


# Question
Title: Core JavaScript is not included in all pages
I'm developing a theme in Drupal 8. This is my theme.libraries.yml file:

```
default:
 version: 1.x
 css:
  theme:
   css/bootstrap.css: {}
   css/style.css: {}
   css/font-awesome.min.css: {}
   css/animate.min.css: {}
 js:
    js/galip.js: {}

```

When I try to view the source of the front page page, I see the JavaScript files like ready.min.js. jquery.min.js, jquery.once.min.js which I don't see in the login page and other pages.

Why is this happening? How do I include the core JavaScript files in all pages?

# Answer
> 4 votes
Drupal 8 adds little to no javascript by default, and thankfully doesn't force jQuery on us any more :)

You need to declare your dependencies explicitly:

```
default:
 version: 1.x
 css:
  theme:
   css/bootstrap.css: {}
   css/style.css: {}
   css/font-awesome.min.css: {}
   css/animate.min.css: {}
 js:
    js/galip.js: {}
 dependencies:
    - core/jquery
    - core/jquery.once
    - etc...

```

---
Tags: javascript, 8
---