# Question
Title: Using xdebug to find out why a variable is mysteriously set to 0
Thanks in advance for your help! I'm new to xdebug and trying to figure it out. I have a situation I'm trying to debug where a variable is mysteriously set to 0.

I know from xdebug (I'm using PHPStorm) that it happens at this specific line:

```
// breakpoint here: $id_key is 'my_entity_id_key'
$e_entity_ids = my_module_fetch_col_keyed($query, $id_key, $created_column);
// breakpoint here: $id_key is 0

```

It's weird, because `$id_key` is not a reference, nor does the function take a reference as a parameter. Also, after the value has changed to `0`, `$id_key` is blue in the variables pane of the debugger. I should note that `$e_entity_ids` comes out here with the proper value.

I've tried making a copy of the variable and using it to pass to the function instead:

```
$id_key2 = $id_key;
$e_entity_ids = my_module_fetch_col_keyed($query, $id_key2, $created_column);
// breakpoint here: $id_key is 0, and so is $id_key2

```

I'm wondering:

1. How could the value of `$id_key` be mysteriously changing to 0?
2. How can I create a copy of `$id_key` so that it's not changed when I pass the copy to `my_module_fetch_col_keyed()`?
3. What does it mean when a variable name is blue in the variables pane in PHPStorm?

When I step into `my_module_fetch_col_keyed()`, there's a line after which $column is mysteriously `0`, as shown:

```
function my_module_fetch_col_keyed(Query $query, $column, $key_column = NULL) {
  try {
    $result = $query->execute();
  }
  catch (Exception $e) {
    return FALSE;
  }

  if (!isset($key_column)) {
    try {
      // breakpoint here: $column is 'my_entity_id_key'
      $column_results = $result->fetchCol($column);
      // breakpoint here: $column is mysteriously 0
    }
    catch (Exception $e) {
      return FALSE;
    }
    return $column_results;
  }

  try {
    $assoc = $result->fetchAllAssoc($key_column);
  }
  catch (Exception $e) {
    return FALSE;
  }

  $keyed = array();
  foreach ($assoc as $key => $result) {
    $keyed[$key] = $result->{$column};
  }

  return $keyed;
}

```

# Answer
> 0 votes
The key idea here is to use the "step into" functionality of PHPStorm to figure out when the second argument ($column within the function's declaration) gets changed. $id\_key shouldn't change at all if you're describing the calling conventions correctly, the second argument would have to be declared as &$column, i.e., as a *reference* to the variable. So I'm assuming that's what you mean. Otherwise, PHP passes a scalar variable "by value", and won't let any changes made to the variable in the body of the function change the original variable outside of it.

And there's nothing inside of the function that will change it either. Here J. Reynolds is right; you're passing the wrong thing to fetchCol(), which wants an integer. But fetchCol() doesn't modify its argument either.

Since you're using xdebug, this then raises an important question: how are you using it? Is your php process running on the same server as PHPStorm?

I ask this because one thing can definitely go wrong using xdebug: you can be debugging a different file than you think you are, if you're "mapping" a file on your server to a local file. If the file isn't the same, weird things can happen like what you describe. You may not really be on the line you think you are, since xdebug will tell PHPStorm the file line on the server, which may be a different line entirely on your local file. And the values of variables, if they display at all, may have different values than what the code displaying in PHPStorm allows.

Without knowing how you've set up PHPStorm to get to your PHP process, it's hard to know what exactly's going on. But you should describe what technique you're using, so folks can give you a better answer.

---
Tags: database
---


title: Smart crop for drupal 8?

text:
# Question
Title: Smart crop for drupal 8?
I find intresting plugins, for smart image croping:

https://www.drupal.org/project/smartcrop https://www.drupal.org/node/907984 https://www.drupal.org/project/imagefield\_focus

But all of them for drupal 7

Is there a module for Drupal 8? What can I do to install this on Drupal 8?

# Answer
# Image Widget Crop

> Provides an interface for using the features of the Crop API. Module is still under heavy development.
>
> Posted by woprrr
> 0 votes

---
Tags: 8, media
---


# Question
Title: How to configure the default visibility to "Only the listed pages" when adding a block?
When adding a block to the site:

```
Home » Administration » Structure » Blocks

```

the default setting for visibility is set to "All pages except those listed." is there a way to set the default setting to "Only the listed pages"?

I'd guess that this possible w/ a custom module but I'd rather avoid that.

# Answer
Yes, you can add this to you admin theme's (default is Seven) template.php file (so no custom module):

```
function seven_form_block_add_block_form_alter(&$form, &$form_state, $form_id){
  $form['visibility']['path']['visibility']['#default_value'] = BLOCK_VISIBILITY_LISTED;
}

```

or if your admin theme is something else:

```
function ADMINTHEME_form_block_add_block_form_alter(&$form, &$form_state, $form_id){
  $form['visibility']['path']['visibility']['#default_value'] = BLOCK_VISIBILITY_LISTED;
}

```

Refer to hook\_form\_FORM\_ID\_alter for more info.
> 1 votes

# Answer
Nope. The block add admin form is hard-coded to use `BLOCK_VISIBILITY_NOTLISTED` (i.e. "All pages.." option) as the default option; there's no configuration setting there. The only way around this is to form alter it with a module.
> 1 votes

# Answer
You may want to use the Rules block visibility module. Here is a quote from its project page:

> The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
>
> The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless:
>
> * Need to show a block only for users registered more than a month ago?
> * Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
> * What about displaying or hiding a block based on current weather conditions?
>
> All of this can be done by using Rules block visibility.

With that, and as per the "*if you can do it with Rules, you can use it to control block visibility*" above, you've reduced your question to making Rules "***check the path of the current page***" (so that the block is only shown for the listed pages).

For an illustration of how to use this module, refer to my answer to "How to stop a Views block from displaying to admins, such as user/1?".
> 0 votes

---
Tags: blocks
---


# Question
Title: Move XML once they're processed in Feeds
Currently, I'm using Feeds & Feeds XPath Parser for importing XMLs into my Drupal 7.x site. As per the requirement, it's working perfectly fine expect the moving feature.

What I need to do is to move the XML files once they are processed, is there any hook or something which can be helpful for me on this? Suggestions are welcome.

# Answer
I've got similar requirement some time ago, I've got a thread where this patch works very well with Feeds directory fetcher 7.x-2.0-beta5.

```
diff --git a/feeds_fetcher_directory.module b/feeds_fetcher_directory.module
index 24b0137..c37295e 100644
--- a/feeds_fetcher_directory.module
+++ b/feeds_fetcher_directory.module
@@ -29,3 +29,50 @@ function feeds_fetcher_directory_ctools_plugin_api($owner, $api) {
   }
 }

+/**
+ * Implements hook_feeds_after_import().
+ *
+ * @param FeedsSource $source
+ */
+function feeds_fetcher_directory_feeds_after_import(FeedsSource $source) {
+  // We alter import only if fetcher is 'feeds_fetcher_directory_fetcher'.
+  if (get_class($source->importer->fetcher) != 'feeds_fetcher_directory_fetcher' || !$source->importer->fetcher->config['after_processed']) {
+    return;
+  }
+
+  foreach ($source->config['feeds_fetcher_directory_fetcher']['feed_files_fetched'] as $file_path => $value) {
+    // Check if file exist, becouse we could already delete it.
+    if (!file_exists($file_path)) {
+      continue;
+    }
+
+    // Determine whatever this is managed or unmanaged file.
+    $file_unmanaged = FALSE;
+    if (!($file = reset(file_load_multiple(array(), array(
+      'uri' => $file_path
+    ))))) {
+      $file_unmanaged = TRUE;
+    }
+    ;
+
+    // Delete or move file, according to config.
+    switch ($source->importer->fetcher->config['after_processed']) {
+      case FEEDS_FETCHER_DIRECTORY_FETCHER_DELETE:
+        $file_unmanaged ? file_unmanaged_delete($file_path) : file_delete($file, TRUE);
+
+        break;
+      case FEEDS_FETCHER_DIRECTORY_FETCHER_MOVE:
+        // Move file, and save folder substructure.
+        $new_file_name = $source->importer->fetcher->config['move_to_folder'] . '/' . substr($file_path, strlen(($source->importer->fetcher->config['directory'])));
+        file_prepare_directory(dirname($new_file_name), FILE_CREATE_DIRECTORY);
+
+        if ($file_unmanaged) {
+          file_unmanaged_move($file_path, $new_file_name, FILE_EXISTS_RENAME);
+        } else {
+          $file_moved = file_move($file, $new_file_name, FILE_EXISTS_RENAME);
+        }
+
+        break;
+    }
+  }
+}
diff --git a/feeds_fetcher_directory_fetcher.inc b/feeds_fetcher_directory_fetcher.inc
index b48c878..537bb06 100644
--- a/feeds_fetcher_directory_fetcher.inc
+++ b/feeds_fetcher_directory_fetcher.inc
@@ -5,6 +5,9 @@
  *
  * Provides the Feeds Directory Fetcher to feeds.
  */
+define('FEEDS_FETCHER_DIRECTORY_FETCHER_NO_ACTION', 0);
+define('FEEDS_FETCHER_DIRECTORY_FETCHER_DELETE', 1);
+define('FEEDS_FETCHER_DIRECTORY_FETCHER_MOVE', 2);

 /**
  * Fetches a file from a specified directory.
@@ -79,7 +82,7 @@ class feeds_fetcher_directory_fetcher extends FeedsFileFetcher {
       '#type' => 'textfield',
       '#title' => t('Directory'),
       '#description' => t('Specify a URI to scan for feed data, e.g. private://files-to-scan.'),
-      '#default_value' => isset($source_config['source']) ? $source_config['source'] : '',
+      '#default_value' => (isset($source_config['source']) && !empty($source_config['source'])) ? $source_config['source'] : $this->config['directory'],
       '#required' => TRUE,
     );
     $form['reset'] = array(
@@ -116,10 +119,16 @@ class feeds_fetcher_directory_fetcher extends FeedsFileFetcher {
    * Override parent::configDefaults().
    */
   public function configDefaults() {
+    $schemes = $this->getSchemes();
+    $scheme = in_array('private', $schemes) ? 'private' : 'public';
+
     return array(
       'recursive' => TRUE,
+      'directory' => $scheme . '://feeds',
       'filemask' => '/\.txt$/',
       'updated_files' => FALSE,
+      'after_processed' => FALSE,
+      'move_to_folder' => ''
     );
   }

@@ -128,6 +137,16 @@ class feeds_fetcher_directory_fetcher extends FeedsFileFetcher {
    */
   public function configForm(&$form_state) {
     $form = array();
+    $form['directory'] = array(
+      '#type' => 'textfield',
+      '#title' => t('Upload directory'),
+      '#description' => t('Directory to search for files. Prefix the path with a scheme. Available schemes: @schemes.', array('@schemes' => implode(', ', $this->getSchemes()))),
+      '#default_value' => $this->config['directory'],
+      '#states' => array(
+        'visible' => array(':input[name="direct"]' => array('checked' => FALSE)),
+        'required' => array(':input[name="direct"]' => array('checked' => FALSE)),
+      ),
+    );
     $form['filemask'] = array(
       '#type' =>'textfield',
       '#title' => t('File mask'),
@@ -139,6 +158,29 @@ class feeds_fetcher_directory_fetcher extends FeedsFileFetcher {
       '#title' => t('Re-fetch files that are modified'),
       '#default_value' => $this->config['updated_files'],
     );
+    $form['after_processed'] = array(
+      '#type' => 'radios',
+      '#title' => t('After process'),
+      '#options' => array(
+        FEEDS_FETCHER_DIRECTORY_FETCHER_NO_ACTION => t('No action'),
+        FEEDS_FETCHER_DIRECTORY_FETCHER_DELETE => t('Delete files'),
+        FEEDS_FETCHER_DIRECTORY_FETCHER_MOVE => t('Move to folder')
+      ),
+      '#default_value' => $this->config['after_processed']
+    );
+    $form['move_to_folder'] = array(
+      '#type' => 'textfield',
+      '#title' => t('Move to folder'),
+      '#description' => t('Specify a folder, to which files will be moved after being processed. Available schemes: public, private.'),
+      '#default_value' => $this->config['move_to_folder'],
+      '#states' => array(
+        'visible' => array(
+          ':input[name="after_processed"]' => array(
+            'value' => FEEDS_FETCHER_DIRECTORY_FETCHER_MOVE
+          )
+        )
+      )
+    );
     $form['recursive'] = array(
       '#type' =>'checkbox',
       '#title' => t('Recursively scan directory'),
@@ -147,4 +189,50 @@ class feeds_fetcher_directory_fetcher extends FeedsFileFetcher {
     );
     return $form;
   }
+
+  /**
+   * Overrides parent::configFormValidate().
+   *
+   * Ensure that the chosen directory is accessible.
+   */
+  public function configFormValidate(&$values) {
+
+    $values['directory'] = trim($values['directory']);
+
+    // Validate the URI scheme of the upload directory.
+    $scheme = file_uri_scheme($values['directory']);
+    if (!$scheme || !in_array($scheme, $this->getSchemes())) {
+      form_set_error('directory', t('Please enter a valid scheme into the directory location.'));
+
+      // Return here so that attempts to create the directory below don't
+      // throw warnings.
+      return;
+    }
+
+    // Ensure that the upload directory exists.
+    if (!file_prepare_directory($values['directory'], FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS)) {
+      form_set_error('directory', t('The chosen directory does not exist and attempts to create it failed.'));
+    }
+
+    // Validate move_to_folder if after_processed set to "move".
+    if ($values['after_processed'] == FEEDS_FETCHER_DIRECTORY_FETCHER_MOVE) {
+      $values['move_to_folder'] = trim($values['move_to_folder']);
+
+      // Validate the URI scheme of the move_to_folder.
+      $move_to_sheme = file_uri_scheme($values['move_to_folder']);
+      if (!$move_to_sheme || !in_array($move_to_sheme, $this->getSchemes())) {
+        form_set_error('move_to_folder', t('Please enter a valid scheme into the move to folder.'));
+
+        // Return here so that attempts to create the folder below don't
+        // throw warnings.
+        return;
+      }
+
+      // Ensure that the move_to_folder exists.
+      if (!file_prepare_directory($values['move_to_folder'], FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS)) {
+        form_set_error('move_to_folder', t('The chosen directory does not exist and attempts to create it failed.'));
+      }
+    }
+  }
+
 }

```
> 0 votes

# Answer
You can use hook\_feeds\_after\_import to move xml after successful import.

```
/**
 * Invoked after a feed source has been imported.
 *
 * @param FeedsSource $source
 *  FeedsSource object that describes the source that has been imported.
 */
function hook_feeds_after_import(FeedsSource $source) {
  // See geotaxonomy module's implementation for an example.

  // We can also check for an exception in this hook. The exception should not
  // be thrown here, Feeds will handle it.
  if (isset($source->exception)) {
    watchdog('mymodule', 'An exception occurred during importing!', array(), WATCHDOG_ERROR);
    mymodule_panic_reaction($source);
  }else {

        // You can write here you own code to move xml.

   }
 }

```
> 0 votes

---
Tags: 7, feeds
---


# Question
Title: How to disabled Drupal builtin "poormanscron" cron when using Ultimate cron?
I want to disabled Drupal 7 builtin "poormanscron" to then put it into a crontab task as it should, but when using Ultimate cron module i do not see an option to disabled Drupal 7 builtin "poormanscron"

Do i have to uninstall ultimate cron?

# Answer
> 1 votes
You don't need to uninstall any module. The setting you are looking for is on admin/config/system/cron/settings/poorman.

>

Change *Launcher* to *-- Disabled --* from the default *Serial*, and Poormanscron should not run anymore.

If you disable or uninstall the *Ultimate cron* module, Drupal shows the equivalent settings in admin/config/system/cron, at the bottom of the page.

>

In this case, change *Run cron every* to *Never*.

---
Tags: 7, cron
---


title: Getting entityreference field from user

text:
# Question
Title: Getting entityreference field from user
I created additional field for user profile, which is a reference to node (content type - Company).

How can i get values of this field for a current user?

---

```
 $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());

 $field_company= $user->get('field_company')->value; // result is empty

```

---

I know that second string is wrong, but i don't know what should I write. Please, help.

Thanks a lot.

# Answer
> 0 votes
Seeing this change record, this should work:

```
$items = $user->getTranslation($langcode)->get('field_company');

```

# Answer
> 0 votes
For entity reference fields the property containing entity id is `target_id`. So you want to do something like this:

```
$field_company = $user->get('field_company')->target_id;

```

See the `EntityReferenceFieldItemList` docs for more information on the data available with this field.

---
Tags: entities
---


# Question
Title: Content Pane on Landing Page not getting Context
I thought that would be fairly easy: I am working with Panopoly and I have multiple Landing Pages, a Vocabulary, Content Items and a View with a Content Pane.

The user can select one term per Landing Page (term reference) on creating the lp. Also the content items have one of the terms from the vocabulary attached (as well via term reference).

The View lists all the content items with a contextual filter by term. By default the content pane is part of a newly created Landing Page. So, in this simple case, I want the user to pick a term from the vocabulary and subsequently let the content tagged with this term appear on that landing page via the content pane.

What I get working is the contextual filter "Has taxonomy term ID" with "Argument Input: Input on pane config" Now I can pick a term through the IPE.

However for more complex applications I would like to hand the term selected by the user on creation of the Landing Page (in the edit form) to the content pane, so that the user doesn't have to set it on each content pane seperatly.

Any ideas?

# Answer
Ok, the solution is pretty easy, but due to Views complexity it took my some time to figure it out. In my setup, there is no filter available. My mistake was, that I thought there IS a fitler available which is why I did not fill in the upper section. Since my filter is not in the url, I had to select "Load default filter from node page, that's good for related taxonomy terms".

That's all the magic ;)
> 0 votes

---
Tags: views, distributions
---


title: PHP content read file location

text:
# Question
Title: PHP content read file location
i added the module php to enable the insertion of php content now i want to add script that read from xml file.
My question is : where to add the xml file (the path on where to put my public files), i tried to add them under `drupal\sites\default\files` but it doesn't work

# Answer
> -1 votes
It's under the Drupal folder himself.
I check it with `echo getcwd()`

---
Tags: 8
---


title: Display error message daily

text:
# Question
Title: Display error message daily
Is there a way to display error message daily to the user saying that "Your subscription Expiry in x days". And this message needs to popup each and everyday.

I can use `hook_init()`(this will run each and every page load), is there any other hook/option available?

# Answer
> 0 votes
hook\_init is used, when you want to do something while the request is initialized, you could use ***hook\_preprocess\_page*** and there set the message, checking on a custom field you added to your user, storing the date of the last information. If this is not today, then show it and update the field value.

---
Tags: 7, commerce
---


# Question
Title: How can I have Exposed filter of Flag type in views?
I want to add Exposed filters of flag types in Views.

I have many flag types and I want users to be able to select their favorite Flag type to show result.

# Answer
> 0 votes
You can follow these steps:

* You can create taxonomy terms for your flag types.
* Add term reference (taxonomy reference) field in your content type pointing to flag taxonomy.
* In your view, add filter of taxonomy terms then and check exposed filter checkbox.

You can use Better Exposed Filters module for better UI.

# Answer
> 0 votes
The requirement of yours is not doable.

Source - https://www.drupal.org/node/2218305#comment-8579757

You can only expose 1 flag at a time that too by adding a relationship of the flags on the views.

---
Tags: flags, views
---


title: Retrieving the primary Key column

text:
# Question
Title: Retrieving the primary Key column
I have been using this query to query Postgres Table Primary Key Column.

```
SELECT a.attname, format_type(a.atttypid, a.atttypmod) AS data_type
FROM   pg_index i
JOIN   pg_attribute a ON a.attrelid = i.indrelid
                     AND a.attnum = ANY(i.indkey)
WHERE  i.indrelid = 'semstudent'::regclass
AND    i.indisprimary;

```

I want to perform the above query in Drupal. Below is my code:

```
$query=db_select('pg_index', 'i',array('target' => 'import'));
$query->join('pg_attribute' , 'a' ,'a.attrelid = i.indrelid AND a.attnum = ANY(i.indkey)');
$result = $query
    ->fields('a', array('attname','atttypid','atttypmod'))
    ->condition('i.indrelid', '"semstudent"::regclass')
    ->condition('i.indisprimary', true)
    ->execute();

```

The query above create the error below:

> PDOException: SQLSTATE\[22P02\]: Invalid text representation: 7 ERROR: invalid input syntax for type oid: ""semstudent"::regclass" LINE 5: WHERE (i.indrelid = '"semstudent"::regclass') AND (i.indisp... ^: SELECT a.attname AS attname, a.atttypid AS atttypid, a.atttypmod AS atttypmod FROM {pg\_index} i INNER JOIN {pg\_attribute} a ON a.attrelid = i.indrelid AND a.attnum = ANY(i.indkey) WHERE (i.indrelid = :db\_condition\_placeholder\_0) AND (i.indisprimary = :db\_condition\_placeholder\_1) ; Array ( \[:db\_condition\_placeholder\_0\] =\> "semstudent"::regclass \[:db\_condition\_placeholder\_1\] =\> 1 ) in myid\_get\_template\_table\_primary\_key() (line 755 of C:\xampp\htdocs\drupal- 7.34\sites\all\modules\myid\includes\myid\_inputting.inc).

I guess it has something to do with the statement below.

```
->condition('i.indrelid', '"semstudent"::regclass')

```

How do I convert it?

UPDATE:

Suggestions below are appreciated but it doesnt make any changes in my code. I have somehow managed to get it working manually. See code below:

```
 $database = 'import';
 $table = 'semstudent';

 $query=db_select('pg_index', 't1',array('target' => $database));
 $query->join('pg_attribute' , 't2' ,'t2.attrelid = t1.indrelid AND t2.attnum = ANY(t1.indkey)');
 $result = $query
    ->fields('t2', array('attname','atttypid','atttypmod'))
    ->condition('t1.indrelid', myid_get_table_oid($table, $database))
    ->condition('t1.indisprimary', true)
    ->execute();

```

I have made the function `myid_get_table_oid` supplied with two parameters: `$table` and `$database`. $table represents the name of the the table. $database represents the target database.

```
//A function that returns the oid of a particular table.
function myid_get_table_oid($table_name, $database){

    $query=db_select('pg_class ', 't1',array('target' => $database));
    $result = $query
        ->fields('t1', array('relfilenode'))
        ->condition('t1.relname', $table_name)
        ->execute();

    $oid = '';
    foreach($result as $record){
        $oid = $record->relfilenode;
        break;
    }
    return $oid;
}

```

In many instances, the code I made is working but there is one scenario the function returns no primary key. When I use the code above with a particular table `myid_template_27` in my database. The function `myid_get_table_oid` returns an oid `8948915`. But the converted query doesnt return anything.

I am pretty sure that the table `myid_template_27` have a primary key column. It must return the column `biginta`.See image below:

To see if `biginta` really exist on `pg_attribute` table, I made a query below:

```
SELECT t1.indrelid, t2.attname AS attname, t2.atttypid AS atttypid, t2.atttypmod
AS atttypmod
FROM pg_index t1
INNER JOIN pg_attribute t2 ON t2.attrelid = t1.indrelid AND t2.attnum =     ANY(t1.indkey)
WHERE  (t1.indisprimary = true)  AND (t2.attname = 'biginta')

```

The result shows a different `indrelid` `oid` which is different from the value returned by my function `myid_get_table_oid`.

Where did I go wrong?

# Answer
> 3 votes
As some people already mentioned and the error itself describes, this is a variable interpolation/auto-quoting problem.

The most appropriate option here - following the D.O.'s documentation - would be to use `where()`, instead of `condition()`.

> $query-\>where($snippet, $args = array())
>
> The where() method allows for the addition of arbitrary SQL as a conditional fragment. $snippet may contain any legal SQL fragment, and if it has variable content it must be added using a named placeholder. The $args array is an array of placeholders and values that will be substituted into the snippet. It is up to the developer to ensure that the snippet is valid SQL. No database-specific modifications are made to the snippet.
>
> (*Copied from https://www.drupal.org/node/310086*)

And here is a rewrite of your code:

```
$query=db_select('pg_index', 'i',array('target' => 'import'));
$query->join('pg_attribute' , 'a' ,'a.attrelid = i.indrelid AND a.attnum = ANY(i.indkey)');
$result = $query
    ->fields('a', array('attname','atttypid','atttypmod'))
    ->where("i.indrelid = 'semstudent'::regclass")
    ->condition('i.indisprimary', true)
    ->execute();

```

I just tried this and it worked without any problems, hope it works for you too!

# Answer
> 1 votes
Have you tried db\_query It will be clear to write the same query with minimal edit.

```
 db_query('SELECT a.attname, format_type(a.atttypid, a.atttypmod) AS data_type
    FROM   pg_index i
    JOIN   pg_attribute a ON a.attrelid = i.indrelid
                         AND a.attnum = ANY(i.indkey)
    WHERE  i.indrelid = :tablename::regclass
    AND    i.indisprimary', array(':tablename' => $tablename));

```

---
Tags: 7, database
---


# Question
Title: Can't loop through $form_state->setErrorByName?
I want to display an error message if the form field is empty.

```
  public function validateForm(array &$form, FormStateInterface $form_state) {
      $entry = array(
        'name' => $form_state->getValue('name'),
        'lastname' => $form_state->getValue('lastname'),
        'cardnumber' => $form_state->getValue('cardnumber'),
        'month' => $form_state->getValue('month'),
        'year' => $form_state->getValue('year'),
        'cvv' => $form_state->getValue('cvv'),
    );
    foreach ($entry as $key => $value) {
     if (empty($value)) {

      $form_state->setErrorByName($key, $this->t('cannot be empty.'));

        }
     }
  }

```

but I only get:

> cannot be empty.

If I use instead:

```
foreach ($entry as $key => $value) {
  if (empty($value)) {

    drupal_set_message(t('<b>%key</b> cannot be empty.', ['%key' => $key]), 'error');

    }
}

```

Results how I want it:

> **name** cannot be empty.
>
> **lastname** cannot be empty.
>
> **cardnumber** cannot be empty.
>
> **month** cannot be empty.
>
> **year** cannot be empty.
>
> **cvv** cannot be empty.

Except the problem here is that the form input box does not become highlighted in red.

**How can I make it loop through the first method? or is it like that by design?**

# Answer
I think you simply need to replace:

```
$form_state->setErrorByName($key, $this->t('cannot be empty.'));

```

with

```
$form_state->setErrorByName($key, $this->t('<b>%key</b> cannot be empty.', ['%key' => $key]));

```

According to the docs, the first parameter will identify the field and the second will be the message to output.

In your code, the $message string is outputed as expected, you need to prefix it with the $key parameter, the same way you do with `drupal_set_message`.
> 5 votes

---
Tags: forms, 8
---


# Question
Title: Views content show current state - workbench
I have a page that lists all the content and want to display the current state for each node.

But for now I can only see published content on the page. The view of mine is a content view.

Can we make some changes in the view to show current state of nodes as well?

Have tried the Workbench Current state filter as well but it did not work

# Answer
Have you already installed workbench moderation module?

I have used this module and it gives you a Workbench page with the tabs for each state of the nodes. The user can see which nodes are in Draft state and which are in review state.

You can adjust the look and feel of the page using panels and make it the way you want to display the content of each state.

In the views, you can add exposed filters for any other specific field you want to filter.
> 1 votes

# Answer
Instead of using the Filter criteria of the views, simply add a field **Workbench Moderation: State** which would show the present state of the content.

Hoping that this would be helpful.
> 1 votes

---
Tags: views, workbench
---


title: Custom autocomplete field

text:
# Question
Title: Custom autocomplete field
I am trying to create an autocomplete field for users. The following code is fine for username searches but the requirement is for a search by any part of the user's first and last name.

```
$form['user'] = [
  '#type' => 'entity_autocomplete',
  '#target_type' => 'user',
  '#selection_settings' => [
    'include_anonymous' => FALSE,
  ],
];

```

I am wondering what the best way to filter by first and last name is. Is it even possible to use 'entity\_autocomplete'? It doesn't look like any of the EntityAutocomplete class methods would make this possible and I'm not clear on whether or not the '#selection\_handler' and '#selection\_settings' properties could be helpful.

# Answer
> 5 votes
The `selection_handler` element property allows to specify a plugin id of a class that would override the default selection handler for EntityAutocompleteMatcher. A separate plugin would be able to build a different Entity Query.

Create a plugin of EntityReferenceSelection type. This should be a derivative of the DefaultSelection plugin similar to TermSelection.

Then you can override entityQueryAlter to add additional conditions to the entity query.

---
Tags: 8, entities, ajax
---


# Question
Title: file_scan_directory() takes about 10 seconds to execute
Using xhprof I noticed that `file_scan_directory()` takes more than 10 seconds to execute when front page loads. Why should it take such a long time?

This is the output of xhprofile:

# Answer
It sounds like you're affected by a known issue in Drupal 7.

> Most probably, you are hitting Avoid re-scanning module directory when multiple modules are missing. It happens if you have some missing modules in your installation. Try to check your system table:
>
> ```
> SELECT name, filename FROM system WHERE type = 'module' AND status = 1 ORDER BY filename
>
> ```
>
> And clean-up any modules that are still enabled but missing from the filesystem.
>
> Overall, Drupal 7 is way more resource friendly and scalable then Drupal 6, other than some unfortunate regressions like this one.

Looking at those functions, it does look like it's missing a module or maybe a single file of a module. Have a look at drupal\_get\_filename(), it does call the drupal\_system\_listing(), which calls this function if it can't find the requested file. Add a dpm(func\_get\_args()) right before it calls drupal\_system\_listing(), that should tell you which file it isn't finding.
> 14 votes

# Answer
There are several reasons why this issue may arise, and to my great dismay, I now find myself somewhat knowledgeable about those reasons. Frustratingly, if you've just noticed this problem after upgrading Drupal core to 7.33+, this could be a typo in any module, even if you haven't upgraded that module.

## Modules removed from code base

You may wish to first check for the known bug that @Berdir mentions, especially if you've recently been removing "unused" modules from the code base. To find out if you have modules that are enabled but have been removed from the file system you can run a script such as the one mentioned here \- or use mine, written for a multi-site install on a system with drush, to be run from the Drupal base directory:

```
find sites -maxdepth 1 -iname '*.*' -type d | sed -rne 's:sites/(.+):echo \1; drush @\1 sqlq "select filename from system where status = 1" | grep "/" | sed -rne "s_(.+)_test -f \\1 || echo \\1_p" | bash:p' | bash

```

or the following:

```
while read -r file; do [ -f "$file" ] || echo "$file is missing."; done < <(drush sqlq "SELECT filename FROM system WHERE status = 1")

```

If you find a module that has been removed from the code base, follow the directions in the issues that @Berdir mentioned.

## Coding errors

If it's not that, your situation is likely caused by a coding error, such as a file that has been removed but is still being added by a drupal\_add\_js call (from comment 19 in issue #1082892) or an unfortunate typo in a module or theme, e.g. `imagecache_actions` (see https://drupal.org/node/2381357).

In any case, to figure out exactly why this is happening, you need to know exactly which file Drupal can't find. So, as per Berdir's comment, you can temporarily hack `drupal_get_filename` in `bootstrap.inc` by adding a log or message call just before the call to `drupal_system_listing()`. If you have Devel module installed then `dpm` will work; if not, you can use `drupal_set_message` or syslog. Examples:

```
dpm(func_get_args());
drupal_set_message(implode(', ', func_get_args()));
syslog(LOG_WARNING, implode(', ', func_get_args()));

```

Once you know what Drupal is looking for, it's a good bet that you'll be able to figure out where to go from there. My problem was caused by a call to include a file from the non-existent module `imagcache_actions` (note the typo). So, I searched for `imagecache_actions` in my codebase (e.g. `grep -r imagcache_actions .`), and found that version 1.4 of `imagecache_canvasactions.module` uses module\_load\_include outside of any function call, in the file scope, with a typo. Again, this error was only exposed after updating to Drupal 7.33+. I found that an issue had already been created for `imagecache_actions`, applied the patch, and was back in business.
> 4 votes

# Answer
I had a very similar issue - `file_scan_directory()` was killing the site. Turns out a huuge `node_modules` folder embedded within my custom theme for `gulp` was being scanned each cache flush. Moving these files out of the theme folder (and updating some paths in my gulpfile) seemed to fix it for me. Alternatively: I think you can hack `file.inc`:

`'nomask' => '/(\.\.?|CVS|node_modules)$/', // https://www.drupal.org/node/2329453#comment-9360519`
> 2 votes

# Answer
The `file_scan_directory()` is a recursive function which all files that match for a given directory. It's uses `is_dir()` and `opendir()` PHP calls which may be most time expensive in terms of I/O system calls. Simple Drupal bootstrap (e.g. `time drush ev ""`) may call `file_scan_directory` over few thousands times (depending on complexity of your Drupal folder hierarchy, e.g. number of modules and its folders).

In my case I had ~1500 calls to `file_scan_directory` (24 seconds in total consisting 2 calls from `drupal_system_listing` in `common.inc`, then the other calls were split by recursive calls to `file_scan_directory` it-self.

In order to improve the performance on I/O calls, you need to implement the file caching. This can be achieved by installing and enabling OPCache (`opcache.enable=1`) and tweak its settings (see: How to use PHP OPCache?). Using memory-based caching such as memcached/redis is also advised.

When using command-line interface (such as `drush`), you should also enable `opcache.enable_cli=1`.

After the change you can check the more consuming syscalls using some available debuggers.

E.g.

* On Linux using `strace` (hit `Ctrl`-`C` to finish):

```
sudo strace -c -fp $(pgrep -n php)

```
* On Unix using `dtrace` (using PHP's DTrace static probes), e.g.

```
sudo dtrace -n 'inline string NAME = "php"; syscall:::entry /(NAME == strstr(NAME, execname)) || (execname == strstr(execname, NAME))/ { @num[probefunc] = count(); }'

```

---

You can further consider optimizing `drupal_system_listing()` or `file_scan_directory()` by implementing static cache, e.g.

```
--- a/includes/file.inc
+++ b/includes/file.inc
@@ -2104,6 +2104,8 @@ function file_download_access($uri) {
  *   'filename', and 'name' members corresponding to the matching files.
  */
 function file_scan_directory($dir, $mask, $options = array(), $depth = 0) {
+  static $dirs = array();
+
   // Merge in defaults.
   $options += array(
     'nomask' => '/(\.\.?|CVS)$/',
@@ -2120,7 +2122,12 @@ function file_scan_directory($dir, $mask, $options = array(), $depth = 0) {
       if (!preg_match($options['nomask'], $filename) && $filename[0] != '.') {
         $uri = "$dir/$filename";
         $uri = file_stream_wrapper_uri_normalize($uri);
-        if (is_dir($uri) && $options['recurse']) {
+
+        if (empty($dirs[$uri])) {
+          $dirs[$uri] = is_dir($uri);
+        }
+
+        if ($dirs[$uri] && $options['recurse']) {
           // Give priority to files in this folder by merging them in after any subdirectory files.
           $files = array_merge(file_scan_directory($uri, $mask, $options, $depth + 1), $files);

```

Or for caching `file_scan_directory` calls from `drupal_system_listing()`, then check the following patch available at: file\_scan\_directory should be cached.
> 0 votes

---
Tags: 7, performance
---


# Question
Title: How to link Question node to current page?
I would like users to be able to ask questions related to current page without going to another page as it works now in the Relevant Answers module. There is a related issue: http://drupal.org/node/1826492

I can create a custom block with form in it, and create new `Question` node on submit.

How can I link that new node to current page?

# Answer
In your custom block return your form like this.

```
global $user;
// You may need to get your path a different way here?
$original_path = implode('/', args());
// Just set the GET path to the path ^ from there.  The form_alter()
// will pick it up automatically for you on line 86 in relevant_answers.module.
$_GET['path'] = relevant_answers_compress_string($original_path);

$node = (object) array('type' => 'question', 'uid' => $user->uid, 'name' => (isset($user->name) ? $user->name : ''), 'language' => LANGUAGE_NONE);
$form = render(drupal_get_form('question_node_form', $node));

// Return your rendered form.
// You may need to do some stuff with redirecting if its not going to the right page after you submit.
return $form;

```

This is completely untested but should get you down the right path to solving your issue.
> 4 votes

# Answer
Make sure your Question-content type as a field called "node\_reference\_field" with the EntityReference module.

Once that's done, you just need to make sure the nid of the current node is stored in this field. Since you're using a custom block with a generated form, it won't be that hard.
I suggest you try something like:

```
$node = node_load ($form_state['nid']);
$form['node_reference_field']['value'] = $node->nid;

```

I'm not sure about the coding, but with the EntityReference module, you aren't far from a solution.
> 4 votes

# Answer
If I have correctly understood, you want to insert a block inside a node visualization. If so, I would suggest using the **context** module, you just have to insert the condition (usually the path of the content such as node/\*) and set the reaction to block. You could then select you block and put it in one of the regions defined in your theme.
> 2 votes

# Answer
The Relevant Answers module is one of the (separated) add-on modules for the 7.x-3.x version of the Answers module.

In the most recent 7.x-4.x version of the Answers module, this module has been obsoleted and replaced by the **Answers Best Answer** sub-module, which allows for marking any of the answers to a specific question as the best (accepted) answer (to display the blue checkmarks to the left of each answer, and which is replaced by a green checkmark when an answer is marked as the best answer).

With that, out-of-the-Anwers-box, you can now post a (new) answer right below a question, using a form that is similar to creating a new node.

Disclosure: I'm a (co-)maintainer of this module.
> 1 votes

---
Tags: 7
---


# Question
Title: How to build a simple blog where content could be published securely to user groups?
I am developing a PHP application and want to host a blog to communicate with my alpha, beta, and (hopefully) other users. I have some experience with Drupal, so am planning to put it to use.

I installed Acquia Commons. It was impressive, perhaps too impressive for my needs. I started out by trying to remove some of the features, and I found that there's not much documentation freely available for it. (I don't want a paid service - this startup has not made any money).

I am thinking that Drupal Core with Organic Groups added might be sufficient, but I'm not sure since I have not used Organic Groups before. And of course, there could be other distributions or modules that I don't know about too.

So, the question is, if your Drupal skills were pretty basic, how would you go about building a simple blog where content could be published securely to user groups?

EDIT: Maybe my usage of the word 'groups' is confusing the issue. Perhaps I could do this simply by creating different roles, such as Alpha User, Beta User, and assigning users to those roles. In that case, how would I go about restricting access to content based on role?

# Answer
As per your "*... there could be other distributions or modules that I don't know about too.*" in your question: have a look at the Group module (commonly perceived as an alternative for Organic Groups).

Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also. The Group module creates groups as entities, making them fully fieldable, extensible and exportable. Which also makes it integrate very well (out of the box) with commonly used modules such as Rules, Views, etc.

Some more questions you may want to look at for more details:

# Resources
> 1 votes

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


# Question
Title: Retriving nodes by content type using Drupal::entityQuery
I created a content type named `product`. How can I retrive all node of such content type using the `entityQuery` method?

I tried with this, but it doesn't works:

```
$ids = \Drupal::entityQuery('product')
  ->execute();

$products = \Drupal::entityManager()
  ->getStorage('node')
  ->loadMultiple($ids);

```

# Answer
This is how we do this:

```
$ids = \Drupal::entityQuery('node')
  ->condition('type', 'product')
  ->execute();

$products = \Drupal::entityManager()
  ->getStorage('node')
  ->loadMultiple($ids);

```
> 1 votes

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


# Question
Title: Is there a way to let users edit something only if they are a members of an OG?
We have a number of different users who want to edit 'sections' of our website. This mostly aligns to Organic groups.

Is there a way to allow people to edit pages of a group which they are members of?

# Answer
You could, for sure, use the Group module to let users edit something if they are a member of some ***group***. Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also. It is designed to be an alternative to Organic Groups. The Group module creates groups as entities, making them fully fieldable, extensible and exportable.

For this specific question, you'd enable the `gnode` submodule, and for each group type you would define the appropriate permissions (view, edit, delete, etc) for the various Content Types. That's it.

For more details about how Group compares to Organic Groups, refer to my answer to "What are the features of the Group module versus Organic Group module?".

# Resources
> 1 votes

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


# Question
Title: Anyway to clear cache on Drupal 7 without any extra modules or even going to the performance page?
I'm looking for a way to clear cache easily without installing any fancy modules or going to the performance page. Is there a URL I can just visit to clear the cache? Basically try to find the shortest and fastest way to clear cache without much effort.

# Answer
`drush cc all` is the safest bet.

Visiting www.example.com/update.php will also clear the caches, but you need to be logged in. Otherwise, this is a DOS vector.
> 3 votes

---
Tags: 7, caching
---


# Question
Title: How to make custom login URL accessible in maintenance mode
I created a custom login page with custom path (`www.example.com/customlogin`) and blocked access to default login page via `hook_menu_alter()`. The requirement for default login page to return 403 is achieved.

Login page accessed via new path works great, but this page is inaccessible when the website is in maintenance mode.

**Question:** How to make a path accessible in maintenance mode?

*I'd like to find a method that does not require the use of additional modules like Rename Admin Path*

# Answer
> 1 votes
A viable solution for making the path/URL/page available while in maintenance mode is the use of **`hook_menu_site_status_alter()`**.

This hook is called after checking whether the site is offline (*in maintenance mode*) but before the current router item is retrieved and executed.

Code below should be used in a custom module:

```
function CUSTOMMODULE_menu_site_status_alter(&$menu_site_status, $path) {
  // Allow access to my_module/authentication even if site is in offline mode.
  if ($menu_site_status == MENU_SITE_OFFLINE && user_is_anonymous() && $path == 'custom-path') {
    $menu_site_status = MENU_SITE_ONLINE;
  }
}

```

# Answer
> 0 votes
Change the access value in your `hook_menu_alter()` to

```
'access callback' => variable_get('maintenance_mode',0),

```

This way, the normal user login page returns when you change to maintenance mode, but you retain the 403. I have not tested this method.

The issue in general here is that maintenance mode is designed to prevent access to the site while it is in a vulnerable or unstable state. Yet, you have multiple people who have not signed in, thus "anonymous" user session right now, that you want to give access. If you grant the `Use the site in maintenance mode` permisison to `anonymous user` then the site will behave as you request... but that removes the reason for having maintenance mode. I think you need to have a second server where you can do the maintenance test, and then use tagged git states to deploy to the production site.

Maintenance mode just does not work for the arrangement that you have described.

---
Tags: 7, maintenance-mode
---


title: How to highlight search results views?

text:
# Question
Title: How to highlight search results views?
I created a view to replace the search default of my website. So I explained the form in a block. Everything works fine, but I would like to highlight search terms in the results.

# Answer
> 2 votes
You can try to use the Highlight module. From its project page:

> * Highlight the keywords from referrer search engine
> * Highlight the keywords from local search

And I think that you should read this posts:

---
Tags: views, search
---


title: Variable in html.tpl.php

text:
# Question
Title: Variable in html.tpl.php
This seemingly simple task proved more difficult than I imagined.. I'm trying to get a variable from themename\_preprocess\_html to my html.tpl.php.

The code I have in my template.php file:

```
<?php
function themename_preprocess_html(&$variables) {
  $variables['test'] = "Hello world!";
}

```

And in my html.tpl.php file I have:

```
<?php print($test); ?>

```

Unfortunately, the variable isn't displayed in the page. It says:

```
Notice: Undefined variable: test in include()

```

I'm trying to do this so I can use node fields to determine variables in my stylesheet.

Is there any way I can print all available variables in my html.tpl.php?

# Answer
> -1 votes
Try using get\_defined\_vars() to get the list of all the variables on a page.

> get\_defined\_vars — **Returns an array of all defined variables**

Source - http://php.net/manual/en/function.get-defined-vars.php

---
Tags: theming, 6
---


# Question
Title: How to remove the default <div> tags generated by modifying manage display?
We are using a mix of Display Suite using the manage display and Paragraph Module on the content types to help control some of the output of the nodes.

One problem we are trying to resolve is how to remove the extra div tags that are generated for the fields.

The options we have tried are:

1. use custom module to call hook\_preprocess\_entity and hook\_preprocess\_field hooks so that we can add the div classes as needed

* PRO
        + We can rewrite the output to include any classes or values we want
        + Because we are using a module is that the module code can be cached
    * CON
        + We cannot completely control what is outputted as shown below.
2. Write a paragraphs-items-pr\_body\_title.tpl.php file so that we can rewrite the output

* PRO
        + We can control the exact output and remove the div tags outlined below
    * CON
        + I am learning that template files are not cacheable

**Example (issue):**

```
<div class="field field-name-field-title field-type-text field-label-hidden">
     <div class="field-items">
          <div class="field-item even">
               <div> /* field value */ </div>
          </div>
    </div>
 </div>

 <div class="field field-name-field-body field-type-body field-label-hidden">
     <div class="field-items">
          <div class="field-item even">
               <div> /* field value */ </div>
          </div>
    </div>
 </div>

```

**Desired Scenario:**

```
<div class="field-title">
     /* title value */
</div>
<div class="field-body">
     /* body value */
</div>

```

What is the recommended way to resolve the issue?

# Answer
> 1 votes
It seems you are missing the Display Suite Extras submodule (ds\_extras)? You can change the default field templates easily there.

From DS Extras doc:

> Default Field Template
>
> * Default: will output the field as defined in Drupal Core.
> * Reset: will strip all HTML.
> * Minimal: adds a simple wrapper around the field.
> * Expert Field Template: gives full control over the HTML, but can only be set per field.
>
> You can override this setting per field on the "Manage display" screens or when creating fields on the instance level.

admin/structure/ds/list/extras:

Once the Extras submodule activated you will have control by fields. visit the CT "manage display" page and the main CT page (edit). Mode "Minimal" or "Expert" seems what you need.

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


# Question
Title: How can you render fields from an entity reference in node templates? [Drupal 8]
For context, I'm dealing with two content types: article and team\_profile. In article nodes, we have an entity reference field pulling a team\_profile node in to serve as the author information.

I would just render the entity with a new display mode, but our design has the photo set directly above the published date and name, next to one another:

In D7 I would `dpm($content)` and drill down to the node information, double click, and pull out the rest of the reference path. I'm using kint and am able to spit out the entity reference contents to a certain level, `{{ kint(content.field_blog_author[0]['#node']) }}`. The next level I want to access is `values`, but trying the following gives me NULL:

* `content.field_blog_author[0]['#node’][‘values’]`
* `content.field_blog_author[0]['#node’]=>values`
* `content.field_blog_author[0]['#node’]->values`

I'd ultimately like to render the `title` and `field_team_image` fields from the referenced node (seen here in the kint output). I haven't found information about this is the documentation or by searching. Would someone help me get unstuck?

# Answer
#node there is actually the current node.

If you want to access fields and their values, start off with node, not content, which is a render array with the configured fields.

You can access the reference entity like this `{{ node.field_blog_author.entity }}`.

From there, you can continue again to the field of the referenced entity that you want to display. You could try calling the view method, with will view it with the default settings, you can also pass a view mode as a string to it or an array display settings (not sure about the exact syntax for that in twig).

Also, my standard reference, see http://wizzlern.nl/drupal/drupal-8-entity-cheat-sheet for a great overview of content entities, how they're structured and how to access values. Most of that also applies to twig.

And last, when trying to figure out what's in a content entity, use node.toArray(), that gives you an array representation that's very close to how you can access it as an object. While the internal structure is quite different.
> 13 votes

---
Tags: theming, 8, nodes
---


# Question
Title: How to pass computed data from Theme preprocess functions to Twig templates?
My general problem is this: I need to compute some data from PHP, usually using Drupal APIs, then pass computed values to a Twig template (in order to showing it).

For example: I have a template named `node--dog.html.twig` and inside this template I need to show the *total count* of *Dog*s I have inside the website. To do this I will compute from PHP the *total count*, using the `Drupal::entityQuery` API. But then I have to pass this computed value to the Twig template.

I tried to use a theme's *preprocess function* inside the file `<my_theme>.theme`:

```
function customtheme_preprocess_node__dog(&$variables) {
  //
}

```

From here I'm able to do all PHP computations, but I couldn't find any documentation explaining how to pass data to Twig views. Can I use the `$variables` object? Is there any drawbacks? Is there a better approach?

# Answer
> 5 votes
`$variables` is an array, not an object.

But yes, it's the one and only way to pass additional data to the template. Anything you put in there is available in the template then. `$variables['hello'] = 'world';` can be printed with `{{ hello }}`.

---
Tags: theming, nodes, 8
---


# Question
Title: printing an entity reference field in a special display mode
I have an entity reference field. The referenced entity has multiple display modes.

I'd like to print this field 2 two times in a template, with 2 different display modes like so:

{{ content.field\_ref\_entity.display\_mode\_xy }}

and

{{ content.field\_ref\_entity.display\_mode\_yz }}

Is it possible to define the display mode of the referenced entity in field printing? If yes, how?

# Answer
> 0 votes
See my explanation in How can you render fields from an entity reference in node templates? \[Drupal 8\], which touches that topic as well.

In short, not with content, that can only contain a field once, at least without additional modules (not sure if display suite or so can do this). But you can call the view() mode on the field with either the of a view mode from where to pick the configuration or pass it the desired configuration directly. The structure is the same as what stored for the configuration in the entity view display config entities for a field.

Not sure about the exact twig syntax for the array, the view display would be like this: \`{{ node.field\_ref\_entity.view('teaser') }}. You could also prepare it in preprocess and then just print a variable if building that configuration array is too tedious in twig.

---
Tags: theming, 8
---


# Question
Title: Please explain caching in complex render arrays
# The Scenario

In `hook_block_configure()`, I'm displaying a configuration form to users that is represented by a fairly complicated render array. The purpose of the form is to allow users to configure an arbitrary number of buttons as part of a **button set**.

* Each button is individually configurable.
* As part of each button's configuration, the user can select an icon from a list of icons. This list is mostly static, although users can upload additional icons on a per-site basis.
* This module is for use in a Drupal multi-site configuration, where each site can field one or more of these **button sets**.
* Each button configuration also features a preview rendering of the button.
* There is a single rendering of the entire button set on the form as well.

# The Question

How best to use caching within this render array? Is it possible to separately cache portions of the render array? For instance, could I separately cache each button configuration, as well as the icons and the rendered buttons?

While solutions to this exact situation would be appreciated, I'm actually more interested in insight into the finer points of adding caching to a complex render array. I believe that I've read most of the introductory documentation on caching that is readily available on the Internet, but haven't found much regarding more involved render arrays.

## Sources

I found these sources to be very useful in attaining a basic understanding of caching in Drupal:

Thanks to all for your insights!

# Answer
http://omnifik.com/blog/render-arrays-and-cache-drupal-7 is an excellent resource, I use it as a guide when caching render arrays. The nice thing about render arrays is they are recursive. So for the hook\_menu page callback you can have that function return mutiple items. As an example I have the page callback function looks like this

```
function my_page_callback() {
  // Form dumps values in the URL, act on them.
  $input_values_from_form = drupal_get_query_parameters();

  // Get form with URL values set in the form as defaults.
  $input_form = drupal_get_form('my_form', $input_value_from_form);

  // Build table render array.
  $table = array(
    '#theme' => 'table',
    '#pre_render' => array('my_table_pre_render'),
    '#header' => $header,
    '#rows' => $rows,
    '#links' => $links,
    '#url_queries' => $url_queries,
    '#filters' => $filters,
    '#entity_types' => $entity_types,
    '#missing_info' => $missing_info,
    '#attributes' => array('class' => array('table', 'table-striped')),
    '#attached' => array('css' => array(drupal_get_path('module', 'my_module') . '/css/table.css' => array('type' => 'file'))),
    '#cache' => array(
      'keys' => $input_values_from_form,
      // Cache this for 1 hour.
      'expire' => REQUEST_TIME + 3600,
    ),
  );

  // Put them together.
  $page_array = array($input_form, $table);

  return $page_array;
}

```

So this will render the input form first and the table second. Using this you can in theory split up your complex page into many smaller parts caching each array separately.

In the above example theme\_table does most of the work but some other parts get used inside my\_table\_pre\_render so the `'#theme' => 'table',` here is a complex example but it shows how to do this.

Pick the keys for each render array wisely as in make it relevant only to that part of the page; see https://api.drupal.org/api/drupal/includes!common.inc/function/drupal\_render\_cid\_create/7.x
> 1 votes

---
Tags: 7, forms, caching
---


# Question
Title: Why do I get this error when running update.php?
Attempting to update drupal 8.0 to 8.1, when I run update.php, I receive this error:

> An AJAX HTTP error occurred.
> HTTP Result Code: 500
> Debugging information follows.
>
> Path: /update.php/start?id=88&op=do\_nojs&op=do
> StatusText: Internal Server Error

The error log contains the following error:

> PHP Fatal error: Call to undefined method Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher::getListenerPriority() in /var/www/html/vendor/symfony/event-dispatcher/Debug/TraceableEventDispatcher.php on line 107, referer: http://example.com/update.php

Why do I get this error when running update.php?

# Answer
> 0 votes
I still don't know what the issue was, but i got around it.

I was attempting to manually update drupal 8.0 to 8.1.

My update steps:

* Backed up database
* Backed up files
* Deleted core directory
* Deleted the vendor directory
* Deleted all files except the ones I added to the top directory
* Uploaded new files
* Uploaded new 8.1 core directory
* Uploaded new 8.1 vendor directory
* Ran update.php

My fix.

* Restored my sites files and database
* Installed Drush 9 (Check your permissions
* Ran pm-update
* Boom success

Anyways still curious on why the ajax error. My guess would be it was a permission issue.

---
Tags: 8, updating
---


# Question
Title: Using FormState::setError() in Form::submitForm()
I am writing a form in Drupal 8 that provides user values to a web service, which will either act on them or send back an error.

How can I display that error message to the user?

Here's the situation in code:

```
class FooForm extends BarForm implements FormInterface {

  protected $fooClient;

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state {

    $result = $this->fooClient->post($form_state->getValue('bar'));

    if ($result->hasProblems()) {
      // This doesn't seem correct: Posting to a web service is not idempotent.
      $form_state->setErrorByName('bar', $this->t('Problems.'));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

    $result = $this->fooClient->post($form_state->getValue('bar'));

    if ($result->hasProblems()) {
      // This throws a LogicException.
      $form_state->setErrorByName('bar', $this->t('Problems.'));
    }
  }
}

```

Drupal treats 'validate' and 'submit' as two separate steps, but the web service doesn't. The only way to determine if the values are fully 'valid' is to get the web service to look at them, which is an operation that potentially has side effects.

`validateForm()` and other form validation handlers are not supposed to contain business logic, since they may get called multiple times during the life of the form, particularly if AJAX is involved.

However, all errors are meant to be resolved before `submitForm()` and any other submission handlers are called. `FormState::setError()` enforces this by throwing a `LogicException` if you try to create any. Also, submitForm() clears away the user's values, and the next page builds the form from scratch.

I've seen this similar question for Drupal 7. Back then, it was possible (if discouraged and ugly) to use `form_set_error()` in the submit handler or the form builder. As far as I can tell, that flat-out doesn't work in Drupal 8.

How am I supposed to interact with RESTful web services? Is there a way to pass errors up from a form submit handler? Or is there a way to ensure a validation handler runs once, only once, and only if all other validation passes? Or is there some way to do this with multi-step forms?

# Answer
The Drupal form system, isn't really built for what you are trying to do. I see two ways of going about this:

1. ### Webservice validation

If the webservice can do a validation of the data or such a method can be added, you can use the form system as is, and use `::validateForm` to validate via webservice.
2. ### Rebuild form

What you can do, instead of doing a "validation" is to delete your `::validateForm` method entirely and just send the data to the webservice in the `::submitForm`. If the operation fails, you can rebuild the form and display a message to the user. You can make it appear as a validation error even though it technically isn't. Drupal does something like this as well. Fx in `NodeForm::save`

```
public function save(array $form, FormStateInterface $form_state) {
  ...
  $node->save();
  ...
  if ($node->id()) {
    ...
  else {
    // In the unlikely case something went wrong on save, the node will be
    // rebuilt and node form redisplayed the same way as in preview.
    drupal_set_message(t('The post could not be saved.'), 'error');
    $form_state->setRebuild();
  }
}

```

So basically, you can use `$form_state->setRebuild()` and `drupal_set_message` to make something that mimics validation in the submit handler. You can also save data in the store (`$form_state->setStorate($data)`) which you can use the form method to display error message or something else to the user.
> 8 votes

# Answer
@googletorp answer works well. I just want to add one more thing: you cannot use **setError()** in **buildForm()**, therefore, in order to visually indicate which element has problem, you want to set

```
$form['THE_PROBLEM_ELEMENT']['#attributes']['class'][] = 'error';

```
> 0 votes

---
Tags: 8, forms
---


title: Twig templates are not loading

text:
# Question
Title: Twig templates are not loading
I am using Drupal 8 from github:drupal/drupal@a9ac0fbf17, but having problems creating custom template, using Twig template engine.

Here is template file structure:

.
├── README.txt
├── screenshot.png
├── templates
│ └── html.html.twig
└── custom.info.yml

**html.html.twig** file is not being loaded. I have tried to change ownership/permission of the files, but it didn't help. I turned on `twig_debug` and getting:

```
<!-- THEME DEBUG -->
<!-- CALL: _theme('html') -->
<!-- FILE NAME SUGGESTIONS:
   * html--front.html.twig
   * html--node.html.twig
   x html.html.twig
-->
<!-- BEGIN OUTPUT from 'core/modules/system/templates/html.html.twig' -->

```

which, I assume means it is loading default template from `core/modules/system/templates/`.

Here is the content of my **html.html.twig**:

```
{#
/**
 * @file
 * basic html structure of a single Drupal page.
 */
 #}

 <!doctype html>
 <html lang="en">
 <head {{ html_attributes }}>
   <title>{{ head_title }}</title>
   {{ page.head }}
   {{ page.styles }}
   {{ page.scripts }}
</head>
<body {{ attributes }}>
    {{ page_top }}
    {{ page.content }}
    {{ page_bottom }}
    {{ page.scripts('footer') }}
</body>
</html>

```

What might I be missing? let me know if you need more info.
Thanks

# Answer
> 3 votes
To disable cache for development(tiwg + Drupal cache) :

first copy and rename the sites/example.settings.local.php to be sites/default/settings.local.php

then open settings.php file in sites/default and uncomment these lines:

```
# if (file_exists(__DIR__ . '/settings.local.php')) {
#   include __DIR__ . '/settings.local.php';
# }

```

Now open settings.local.php and change the below lines to "TRUE".

```
$config['system.performance']['css']['preprocess'] = FALSE;
$config['system.performance']['js']['preprocess'] = FALSE;

```

and uncomment all these to Disable the render cache and Disable Dynamic Page Cache

```
# $settings['cache']['bins']['render'] = 'cache.backend.null';
# $settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null';

```

for twig cache open "development.services.yml" and update the below parameters.

```
  twig.config:
    debug : true
    auto_reload: true
    cache: false

```

# Answer
> 0 votes
If your template does not load usually is because is been cache. Its recommend to disable the caching twig in Drupal 8 with developing.

The easier way to "**Disable Drupal 8 caching during development**" is using DrupalConsole.

```
drupal site:mode dev

```

Source - Debugging compiled Twig templates

After you disable your cache you can use the `cache:rebuild` Drupal Console command to clear the cache.

```
drupal cache:rebuild

```

---
Tags: 8, theming
---


# Question
Title: How to add payment method field to the footer of an order summary view?
I can add payment method field to fields in my view, but it is not available to add in footer.

Why is it? How could I add it this field in the footer view?

**Note**: My view is an order summary view, showing all line items, I would like to display below of the lite items, what was the payment method used. I think the footer would be a nice place to put this information, but I don't see the token for it. I can see the token to add in fields but not in footer.

# Answer
> 1 votes
Why is it? Fields are meant to go in the fields section and not in the footer.

An easy workaround solution is to create an attachment view contenting only the field in question and attach it after your current view.

1. To do this, in your view, click on +Add and select attachment.

2. Then you should have a cloned copy of your original view. When you add or remove fields make sure you select at top **This attachment (override)**. If you do not do this, your changes will affect all of your views.

3. In your first/original view: In footer click on Add and select Global: View area. Select your attachment view and check mark the inherit contextual filters box.

> **Note:** If your first/original view is a Master, when you add the attachment, you will not have the **For: Display** box,  such as in the last picture (on step 3).
>
> If that is the case, all your views will get an attachment, including the attachment. Therefore, you will have to switch to the attachment view and select "This attachment (override)" and remove the footer from the attachment.

---
Tags: 7, commerce
---


# Question
Title: How to access individual items in $form_state['values'] post-submit
**Question**

After a user has a submitted a form how do I determine how to reference individual form field values in `$form_state['values']` ?

**Examples**

For example, I have several fields in my form, such as 'field\_organization' that would normally be accessed (for CSS) purposes, like so:

`$form['customer_profile_billing']['field_organization']`

I have others in my form that have even more convoluted paths such as

`['und'][0]['another-name']['a-fourth-name']`, etc.

# Answer
You can access `$form_state['values']` of a field in like

```
$variable = $form_state['values']['your_field_name'];

```

After saving you can access like this

```
$variable = $form['your_field_name']['und'][0]['value'];

```

For more information please check

1. $form\_state keys
2. What is $form\_state used for ?

Hope this will help you.
> 1 votes

---
Tags: forms
---


# Question
Title: Can we configure Devel module to pick up images for the image field of a content type only from a specific directory containing images?
A **Yes** or **No** question. Using *Drupal 7.43*. *Devel* module generates polycolor image content of a content-type which has an *image* field. But I need only a few specific images on my contents of that content type and I need Devel module to pick up images from a specific directory on my system(in the same drupal environment directory) and then randomly associate them with contents. Can this be done by changing **Devel's configurations**? Suggestions are welcome for alternative solutions to this problem.

# Answer
> 0 votes
Yes.

There are at least two modules providing this or similar features:

HTH

---
Tags: nodes, media, debugging
---


# Question
Title: Redirect 'user' and 'user/uid' to 'users/name'
I have been trying to redirect the default user url of '/user' to the url alias of '/users/username'.

If i go to '/user/uid' it redirects properly but if i type in '/user' the url doesn't redirect.

Using hook\_preprocess\_user\_profile() I can print arg(0) and arg(1) with drupal\_set\_message() and it display that arg(1) exists as the uid on '/user'.

I have tried

```
function mymodule_preprocess_user_profile(&$vars) {
  global $user;
  //print_r($vars);
  if (arg(0) == 'user' && arg(1) == $user->uid){
    //drupal_set_message('0'.arg(0).'1'.arg(1));
    drupal_goto("users/$user->name");
  }
}

```

but this end up in an endless redirect. Is it possible to even accomplish this?

# Answer
> 1 votes
By redirecting `/user` you'll be redirecting the login page to a user page. When someone goes to `/user` and logs in they are automatically redirected to `/user/username`. Unless you have login disabled(not advised) I can't see what you want to achieve, can you explain further?

Redirects are best handled by the path redirect module

or using rules in `.htacces` or `etc/apache2/httpd.conf`

# Answer
> 0 votes
After some testing, I realise if you visit /user, the $\_GET\['q'\] (which produces the arg's) returns /user/uid, so it looks like you are on the /user/uid page even though you are not.

I placed the code below into my themes template.php and it will redirect /user to /user/uid. If you have URL aliases enabled, this will then redirect to that.

```
function MYTHEME_preprocess_page(&$page) {

  if (request_uri() == base_path().'user' && $page['user']->uid != 0 ) {
    $path = 'user/' . $page['user']->uid;
    drupal_goto('user/1');
  }
}

```

I wanted to do the same on my site, but I use the me-alias module. The following code worked in my themes template.php. Re the above problem of /user looking like /user/uid, this is okay in this case because I am going to a new path (/user/me), instead of being stuck in the /user/uid loop. This also changes all the /user/uid/\* pages too.

```
function MYTHEME_preprocess_page(&$page) {

  $path = $_GET['q'];
  if (arg(0) == 'user' && arg(1) == $page['user']->uid) {
    $path = str_replace('user/' . arg(1), 'user/me', $path);
    drupal_goto($path);
  }
}

```

# Answer
> 0 votes
You can redirect by using trigger. Drupal provide you basic functionality to do the changes after login by few steps..

1. Open with your admin by given url : admin/config/system/actions
2. Chose from CREATE AN ADVANCED ACTION and select Redirect to URL..
3. Type Label like - Redirect to URL - users #
4. URL - user
5. Now enable module triger in admin/modules page.
6. Go to - admin/structure/trigger/user
7. Choose an action from TRIGGER: AFTER A USER HAS LOGGED IN
8. And assign to Redirect to URL - users #

Now these 8 steps will short out your problem. Logout and again login to check functionality.

Thanks.. Vishal Nigam

---
Tags: 6, hooks, users
---


# Question
Title: Unable to send user-entered data to PayPal along with credit card info
I need help. I used this as a guide. When my user fills out and pays for something on my site using a product form the information they supplied in the form (other than their payment) is not being sent to PayPal. So I built this module to send the information using the module I'm supposed to hook into. However, it throws no errors but still sends no data to PayPal.

```
    if ($payment_method['base'] == 'commerce_paypal_wpp') {

    $order_wrapper = entity_metadata_wrapper('commerce_order',
$order);
    $shipping_info = $order_wrapper->customer_profile_billing-
>commerce_customer_address->value();

             $nvp += array(
                    'ORGANIZATION' => $shipping_info['field_organization'],
            'NAME' => $shipping_info['field_name'],
         );
    }
}

```

Am I perhaps referencing my user-entered data incorrectly?

Here's how the fields show with dpm($form) \[before the user submits the form\]:

Name:

```
$form['customer_profile_billing']
['commerce_customer_address']['und'][0]'name_block']['name_line']

```

Organization:

`$form['customer_profile_billing']['field_organization']`

# Answer
> 1 votes
From your above code i have seen that `dpm($form)` showing 2 fields. when you submit your data in form please ensure that your order is created or not. Becuase in your code you are getting customer order details and pass it to the `array()` (which is empty). Thats why it not going to **Paypal** website. Please check your custom code.

`hook_commerce_paypal_api_request_alter(&$nvp, $order, $payment_method):` What this function will do, it will alter the array before pass this data to paypal website. So you must ensure that array data you are passing to paypal is not empty or you can check the condition for it.

---
Tags: commerce
---


# Question
Title: Panels are wrapping the content into weird <strong> tags
I am new to panels, using panels module to set the page that contains 3 views on it (nothing wrong with these views), when I add the content, the output displays weird tags those are wrapping the content there fore the layout on the front end gets disturbed.

Here is the link to my website page : http://lookwhatwemadeyou.com/trillist/news-press , find "Recent from the Blog" Section.

Q: How to remove these extra tags? where these tags are coming from as I didn't create any custom layout. Is there any way to control the layout other then overriding the panel layouts templates?

```
<div class="info-node panel-main">
  <div class="panel-flexible panels-flexible-4 clearfix">
      <div class="panel-flexible-inside panels-flexible-4-inside">
      <div class="panels-flexible-region panels-flexible-region-4-center panels-flexible-region-first panels-flexible-region-last ">
          <div class="inside panels-flexible-region-inside panels-flexible-region-4-center-inside panels-flexible-region-inside-first panels-flexible-region-inside-last">
          <div class="">
              <div class="panel-pane pane-custom pane-1">
              <h2 class="pane-title"> Latest News </h2>
              <div class="pane-content">
                  <p><strong>Lorem ipsum is a dummy text.Lorep ipsum is a dummy text. Lorem ipsum is a dummy text.Lorep ipsum is a dummy text.</strong></p>
                </div>
            </div>
              <div class="view view-news-press view-id-news_press view-display-id-block view-dom-id-3f0fd15282c7a83bbd1836b458a38681">
              <div class="view-content">
                  <div class="views-row views-row-1 views-row-odd views-row-first">
                  <div class="col-sm-12 border_post">
                      <div class="col-sm-5">
                      <div class="post_img"><img width="425" height="300" src="sites/default/files/styles/list_style_425x300/public/post_2.png?itok=iDl8-7nV" typeof="foaf:Image"> </div>
                    </div>
                      <div class="col-sm-6">
                      <div class="post_text">
                          <h3> <a href="/trillist/news-6">News 6</a> </h3>
                          <h5> By:<span datatype="" property="foaf:name" typeof="sioc:UserAccount" about="/trillist/users/admin" xml:lang="" class="username">admin</span> | <span content="2016-04-19T15:45:00+05:00" datatype="xsd:dateTime" property="dc:date" class="date-display-single">Tuesday, April 19, 2016 - 15:45</span> </h5>
                          <div class="post_desc">
                          <p>Lorem ipsum is a dummy text.Lorep ipsum is a dummy text. Lorem ipsum is a dummy text.Lorep ipsum is a dummy text. Lorem ipsum is a dummy text.Lorep ipsum is a dummy text.</p>
                        </div>
                          <div class="post_btn"><a class="btn-dark" href="/trillist/news-6">Learn More<i class="fa fa-angle-right"></i></a></div>
                        </div>
                    </div>
                    </div>
                </div>
                </div>
            </div>
              **</strong></strong></div>
          <strong><strong> </strong></strong> </div>**
        </div>
    </div>
    </div>
</div>

```

the view's template.tpl.php file is

```
<div class="col-sm-12 border_post">
  <div class="col-sm-5">
    <div class="post_img">
      <?php print $fields['field_image']->content; ?>
    </div>
  </div>
<div class="col-sm-6">
  <div class="post_text">
    <h3> <?php print $fields['title']->content;  ?>  </h3>
    <h5> By:<?php print $fields['name']->content; ?> | <?php print $fields['field_date']->content; ?> </h5>
    <?php $body =$fields['body']->content;
      $bodycontent =  strlen( $body ) > 230  ? substr( $body, 0, 227 ) .'...' : $body;   ?>
      <div class="post_desc"><?php print $bodycontent ;   ?></div >
    <?php if(!empty($fields['field_link']->content)) {
      $link=$fields['field_link']->content;
    }
    else {
      $link=$fields['path']->content;
    }?>
    <div class="post_btn">
      <a href="<?php echo $link; ?>" class="btn-dark">Learn More
        <i class="fa fa-angle-right"></i>
      </a>
    </div>
  </div>
</div>

```

# Answer
> 3 votes
There was some issue in the template file.

You have used

```
$bodycontent =  strlen( $body ) > 230  ? substr( $body, 0, 227 ) .'...' : $body;   ?>
<div class="post_desc"><?php print $bodycontent ;   ?></div>

```

Instead of using that, we should use the Rewrite result of the body and add the trim length. Along with that we should do **STRIP HTML TAGS** to strip off all the tags thats there in the body when showing a listing page.

# Answer
> 0 votes
When you look at the **source** you will notice that most of the strong tags only open and never close. That means the browser is compensating and closing it for you on a best guess scenario. In my experience these type of errors are usually the result of outputting partial html formatted strings in Views. As only the first part of the string is printed the closing tag never makes it into the output.

Go through your Views and make sure that you **STRIP HTML TAGS** from the strings that are printed partially. These will normally be the body fields.

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


title: Getiing error during email send process

text:
# Question
Title: Getiing error during email send process
I am using PepiPost mail service for sending an email. PepiPost mail service provides an SDK for send sending mail. They provided a sample code for sending mail.

When I send the mail getting the following error message:

> Unable to send e-mail. Contact the site administrator if the problem persists.

But mail is sent to the corresponding user and user can receive the mail.

I have created a Custom mail system call by implementing **MailSystemInterface**. The code is available in the here. Although this is the code I placed in `mail()` function.

```
class TestMailSystem implements MailSystemInterface {
  require_once __DIR__.'/includes/vendor/autoload.php';

  use PepipostAPIV10Lib\Controllers\Email;

  public function format(array $message) {
    // Join message array.
    $message['body'] = implode("\n\n", $message['body']);
    return $message;
  }

public function mail(array $message) {

$email = new Email();

$data = array(
      'api_key'   =>  '************',
      'recipients'    =>  $message['to'],
      'email_details' => array(
        'from'          =>  $message['from'],
        'subject'       =>  $message['subject'],
        'content'       =>  $message['body'],
        'fromname'      =>  $message['fromname'],
        'tags'          =>  'test',
        'replytoid'     =>  $replyto,
      ),
      'X-APIHEADER' => array('UserID1','UserID2'),
      'settings' => array(
        'footer'        =>  true,
        'clicktrack'    =>  true,
        'opentrack'     =>  true,
      ),
    $response = $email->sendJson( $data );
}

}

```

When I send the mail getting the following error message:

> Unable to send e-mail. Contact the site administrator if the problem persists.

User receives the email. What would the reason for the error message be?

# Answer
`MailSystemInterface::mail` has a particular return value:

> TRUE if the mail was successfully accepted for delivery, otherwise FALSE.

The caller uses that to determine whether or not the mail was sent successfully, so just return `TRUE` when the mail succeeds and the error will stop.
> 1 votes

---
Tags: 7, emails
---


title: Dynamic configuration form

text:
# Question
Title: Dynamic configuration form
i need to do a configuration file wich allow an admin to select a lot of terms from a vocabulary. Then i want to make a form with 2 select field : Vocabulary and Terms. So, i can select the vocabulary i want and a lot of terms of a vocabulary but i don't know to show all terms of the selected vocabulary.

My code :

```
/*
 * ==================================
 * CONFIGURATION MODULE
 * ==================================
 */
function food_truck_form_admin() {
  $form = array();
  $form['vocabulary'] = array(
      '#title' => 'Vocabulary',
      '#type' => 'select',
      '#options' => food_truck_form_vocabularies()
  );
  $form['terms'] = array(
      '#title' => 'Terms',
      '#type' => 'select',
      '#multiple' => TRUE,
      '#options' => food_truck_form_terms('marqueurs')
  );

  return system_settings_form($form);
}

/**
 * Implementation of hook_menu()
 */
function food_truck_form_menu() {
  $items = array();
  $items['admin/settings/food_truck_form'] = array(
      'title' => 'Food-Truck Configuration',
      'description' => 'Global configurations',
      'page callback' => 'drupal_get_form',
      'page arguments' => array(
          'food_truck_form_admin'
      ),
      'access arguments' => array(
          'administer food_truck_form settings'
      ),
      'type' => MENU_NORMAL_ITEM
  );

  return $items;
}

/*
 * ==================================
 * OTHER FUNCTIONS
 * ==================================
 */

/*
 * Return a term list of a vocabulary by it's machine name or null
 */
function food_truck_form_terms($machine_name) {
  if (! empty($machine_name)) {
    $vid = taxonomy_vocabulary_machine_name_load($machine_name)->vid;
    $terms = taxonomy_get_tree($vid);
    foreach ($terms as $data) {
      $output[$data->tid] = $data->name;
    }
    return $output;
  }
  return NULL;
}
/*
 * Retur a vocabulary list or null
 */
function food_truck_form_vocabularies() {
  $vocabulary = taxonomy_get_vocabularies();
  if (count((array) $vocabulary) != 0) {
    foreach ($vocabulary as $data) {
      $output[$data->vid] = $data->name;
    }
    return $output;
  }

  return NULL;
}

```

# Answer
> 0 votes
Thanks, i've did this and this work perfectly :

```
/*
 * ==================================
 * CONFIGURATION MODULE
 * ==================================
 */
/**
 * Implementation of hook_admin()
 */
function food_truck_form_admin() {
  $form = array();
  $form['vocabulary'] = array(
      '#title' => 'Vocabulaires',
      '#type' => 'select',
      '#options' => food_truck_form_vocabularies(),
      '#ajax' => array(
          'callback' => 'terms_callback',
          'wrapper' => 'terms-wrapper',
          'event' => 'change'
      )
  );
  $form['terms'] = array(
      '#title' => 'Types de marqueurs',
      '#type' => 'select',
      '#prefix' => '<div id="terms-wrapper">',
      '#suffix' => '</div>',
      '#multiple' => TRUE,
      '#options' => food_truck_form_terms('marqueurs')
  );
  return system_settings_form($form);
}

/**
 * Implementation of hook_menu()
 */
function food_truck_form_menu() {
  $items = array();
  $items['admin/settings/food_truck_form'] = array(
      'title' => 'Food-Truck Configuration',
      'description' => 'Global configurations',
      'page callback' => 'drupal_get_form',
      'page arguments' => array(
          'food_truck_form_admin'
      ),
      'access arguments' => array(
          'administer food_truck_form settings'
      ),
      'type' => MENU_NORMAL_ITEM
  );

  return $items;
}

/**
 * CALLBACKS
 */
function terms_callback($form, &$form_state) {
  $machine_name = $form['vocabulary']['#options'][$form_state['values']['vocabulary']];
  $form['terms']['#options'] = food_truck_form_terms($machine_name);
  return $form['terms'];
}
/*
 * ==================================
 * OTHER FUNCTIONS
 * ==================================
 */

/*
 * Return a term list of a vocabulary by it's machine name or null
 */
function food_truck_form_terms($machine_name) {
  if (! empty($machine_name)) {
    $vid = taxonomy_vocabulary_machine_name_load($machine_name)->vid;
    $terms = taxonomy_get_tffree($vid);
    foreach ($terms as $data) {
      $output[$data->tid] = $data->name;
    }
    return $output;
  }
  return NULL;
}
/*
 * Retur a vocabulary list or null
 */
function food_truck_form_vocabularies() {
  $vocabulary = taxonomy_get_vocabularies();
  if (count((array) $vocabulary) != 0) {
    foreach ($vocabulary as $data) {
      $output[$data->vid] = $data->machine_name;
    }
    return $output;
  }

  return NULL;
}

```

---
Tags: 7, taxonomy-terms, configuration
---


# Question
Title: How can I see anonymous visitors in real time Google Analytics?
I can't see anonymous visitors in real-time in Google Analytics, I can only see registered users. But I need see all visitors in Real-time\>Overview , including anonymous visitors.

In the Google Analytics module all roles are set.

# Answer
> 3 votes
First of all this is not a Drupal Question, but anyways. You can see Google Analytics for Anonymous users in your Google webmasters dashboard. Drupal has nothing to do with this.

Drupal Module for Google Analytics has only one function - Tell Google that it's your website and track its activities. Google does the real work of tracking.

---
Tags: users, google-analytics
---


# Question
Title: Create a view of users to show their profile visits
I need to track the IP address in order to have a good idea on how many users visit each profile. This report will be available only to the admin.

I have used User Visits Advanced module

**The problem is that even user can also see his profile visits by using this module.I was also trying to figuring out how to create view of recent visitors using this module but finally unsuccessful.**

I just want to create view report of users and their respective profile visits .

# Answer
You can achieve this by simply creating a rule for profile clicks and add an action i.e. a counter that accepts +1 everytime the event occurs (Rules module). To create a profile click action, all you need is the uid (user ID) which can be like this `example.com/user?q=uid`. create a field in my accounts which stores this value and keep it hidden with display suite. In views, show the profile as fields and choose the uid and your recent field to display profile visits. Style it with css. sorry for bad english I am spanish
> 0 votes

---
Tags: views
---


# Question
Title: Create new table in existing module without affecting existing table data
I have my custom module `myCustomModule` in `drupal 7` website along with installation file to create table.

I Have already saved lot of content in table but I need to create a new table in same module without affecting the previous table data.

if I add something new in `.INSTALL file`, I have to uninstall and install module which will remove the existing data content from my table.

Is there a way to create new table for existing module without affecting existing table data.

How do I update my module structure without affecting previous things.

\[or last option for me is to create a new module and have separate table but I dont want to create so many modules \]

Please help , I need to do it for `Drupal 7`

**EDIT**

I followed this link and tried below and cleared cache after updating my code

```
/**
 * Create new database table {new_table}.
 */
function my_module_update_7101() {
 $schema['new_table'] = array(
     'description' => 'Table for storing information about static media asset .',
        'fields' => array(
            'aid' => array(
                'type' => 'serial',
                'not null' => TRUE,
                'description' => 'Primary Key: Unique aggregator static media asset ID.',
            ),
            'asset_title' => array(
                'type' => 'varchar',
                'length' => 255,
                'not null' => TRUE,
                'default' => '',
                'description' => 'Title of the static media asset title',
            ),
            'asset_file_path' => array(
                'type' => 'varchar',
                'length' => 255,
                'not null' => TRUE,
                'default' => '',
                'description' => 'CDN url path for asset.',
            ),
            'status' => array(
                'description' => 'status field for the static media assets',
                'type' => 'int',
                'length' => 1,
                'not null' => TRUE,
                'default' => 1,
            ),
        ),
        'primary key' => array('aid'),
    );

  db_create_table('new_table', $schema['new_table']);
}

```

It does not seem to update my table

# Answer
Approach to generate a new table without affecting existing table's data.

Declare the table structure in **hook\_schema** because for any new user who will install this module later should get this table so we have to code it here in **hook\_schema**.

/\** * hook\_schema(). \*/

```
function my_module_schema() {
  $schema = array();
  $schema['new_table'] = array(
    'description' => 'Table for storing information about static media
asset .',
    'fields' => array(
      'aid' => array(
        'type' => 'serial',
        'not null' => TRUE,
        'description' => 'Primary Key: Unique aggregator static media asset ID.',
      ),
      'asset_title' => array(
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
        'description' => 'Title of the static media asset title',
      ),
      'asset_file_path' => array(
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
        'description' => 'CDN url path for asset.',
      ),
      'status' => array(
        'description' => 'status field for the static media assets',
        'type' => 'int',
        'length' => 1,
        'not null' => TRUE,
        'default' => 1,
      ),
    ),
    'primary key' => array('aid'),
  );
  return $schema;
}

```

For the users who have already installed the module and want to create a new table can write a **hook\_update\_n()** as below.

/\** * hook\_update\_n(). \*/

```
function my_module_update_7001() {
  $schema = my_module_schema();
  if(!db_table_exists('new_table'))
    db_create_table('new_table', $schema['new_table']);
}

```

Here we will get all the schema and creating the 'new\_table' by using **db\_create\_table()**.

Hope this will resolve your issue. Thanks.
> 3 votes

# Answer
See hook\_update\_n(), particularly the *Adding a new table* heading.

> 1. Add the new table to mymodule\_schema() in mymodule.install.
> 2. Create a mymodule\_update\_N() function to create mytable 2 with the Schema API function db\_create\_table():

Afterwards run database updates and it will create the new table (example.com/update.php or `drush updb`).
> 1 votes

---
Tags: 7, updating
---


# Question
Title: How to compare current year with an integer field in Rules?
I would like to compare the current year with an integer field (let's say a "year of subscription" field) using Rules (if the field value is lower than the current year, the user has no access to a specific action on the website).

I have tried many different things, data comparison, text comparison, PHP custom etc. but I did not manage to create this "apparently" simple condition.

I guess I am missing something (a date/time comparison somewhere? the right PHP code to extract the year of the current date? echo date('YY')? strtotime? mktime?).

Could anyone help me? Thanks in advance.

# Answer
Add the rule as follows:

1. Event

Your event
2. Conditions:

a. Entity has field

-\> Data Selector = node

-\> Field Value = your date field (mine is field\_bp\_year)

b. Execute custom PHP code

-\> Value =

`return intval([node:field-bp-year]) < intval(date("Y"));`

where you add the replacement pattern for your date field (mine was field-bp-year)
3. Actions:

Your action

NOTE: I treated my year as four digits. If you only want 2 digits then use `date("y")`.
> 2 votes

---
Tags: rules, datetime
---