title: Where do I place this module?

text:
# Question
Title: Where do I place this module?
In Drupal 8, I created A content type (*Field\_sideshow*). The requirements for a module I downloaded are the following.

* Libraries API
* jQuery Cycle plugin
* JCarousel

I downloaded the jCarousel module and placed it in modules/contrib/, the jQuery Cycle plugin in libraries/jquery.cycle/.

Where do I place the Libraries API module?

# Answer
> 1 votes
From Installing contributed modules (Drupal 8):

> The downloaded module package will be in a compressed file format such as 'tar.gz' and needs to be extracted to /modules or a subdirectory of /modules in the Drupal root directory

Given that you have a conveniently named "contrib" subfolder already under /modules, it might make sense to put it in there. But it's up to you.

---
Tags: 8, theming
---


# Question
Title: Multilanguage setup breaking View results layouts
**Background:**

We're trying to setup multilanguage options on our site (to allow English/Welsh options). We're using the Internationalization module primarily, with the language detection set to URL.

**The problem:**

The static content pages work fine, but when a page containing views is translated it seems to break the order and div styling of the Views results.

Any ideas what might be causing this (e.g. have I missed a setting in the Block/View somewhere to apply a div style to the translated version of the page)?

E.g. see below - in pic 2, the results are wrongly shown single column rather than in a 4 column grid, and are displayed *before* the rest of the main content rather than *after*):

**Comparison of default (www.../resources) and translated (www.../cy/resources) page layouts**

# Answer
> 0 votes
Turns out this was due to an error in the logic of a custom template not taking in to account variable languages.

---
Tags: i18n-l10n
---


# Question
Title: Display multiple node edit forms on one page with one submit button
Is there a module allowing to edit nodes as a list, like in a spreadsheet, not one by one? For example, display a list of nodes on a page (e.g. 100 nodes) with each node having input boxes instead of displayed fields, or a mixture of both. Each input box is associated with a field, if the field has value then this value is already inserted in the input box and available for editing. After making changes press "Save" and it would update all those nodes with relevant field values. It's like editing a spreadsheet.

# Answer
This can be done with Views and Editable Fields. You then create a page view with the Editable fields for the nodes and your all set. Keep in mind load times and performance by narrowing down the number of WYSIWYG fields and reference fields.
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: Find Menu Link Title given URL alias, to replace node Title in breadcrumbs
In Drupal 8, how can one determine the Menu Link Title of a node, given its URL and other information like its route & parameters?

This is to modify the core path-based breadcrumbs (`PathBasedBreadcrumbBuilder.php`) to use the Menu Link Title of a node, as breadcrumb link text, rather than the node's Title field. This would have to be a common requirement, since the default D8 breadcrumbs would be very long in deep menus with wordy titles. For example, we would need:

> Home \> Design \> Drupal

instead of the D8 default:

> Home \> Introduction to Our Design Services \> Drupal 8: The Best CMS for Everything

for all nodes in the "Drupal" sub-menu.

The default breadcrumb service method `PathBasedBreadcrumbBuilder::build` uses a bunch of injected services to look up & check routes to each ancestor pathname of the node URL, then ultimately `TitleResolver::getTitle` to get the titles for those routes. We would just need a way of looking up the corresponding `MenuLinkContent` instead so we could then get the menu title via `MenuLinkContent::getTitle`.

I have tried to outline the problem for the Drupal Module Development forum (change Breadcrumbs from Node Title to Menu Link Title) but got no response when asking how to simply bridge the gap between the space of URLs/routes and the space of menu link content. Maybe this means it's not possible without a traversal of the menu: if so I would deeply appreciate some idea of where to start with that approach.

# Answer
If you've got a `RouteMatch` (e.g., your breadcrumb builder passing you the `$route_match` argument), you can use the `MenuLinkManager` service (`@plugin.manager.menu.link`), which when injected into your module could be used like the following (e.g., for the `main` menu):

```
$route_name = $route_match->getRouteName();
$route_parameters = $route_match->getRawParameters()->all();
$route_links = $this->menuLinkManager->
  loadLinksByRoute($route_name, $route_parameters, 'main');
$route_link = reset($route_links);

$menu_title = $route_link->getTitle();
$menu_url = $route_link->getUrlObject();

```

Regarding the breadcrumb implementation: that link and all its ancestors would be also be available via `MenuLinkManager::getParentIds`, as plugin IDs in the reverse order as they would appear in the breadcrumb trail:

```
$menu_plugin_id = $route_link->getPluginId();
$menu_parents = $this->menuLinkManager->getParentIds($menu_plugin_id);

```
> 0 votes

# Answer
The sandbox module "wb\_breadcrumbs' did the trick for me: https://www.drupal.org/sandbox/oles89/2367919
> 0 votes

---
Tags: 8, routes, entities, path-aliases, breadcrumbs
---


# Question
Title: Why are store translation files stored in the database?
I have set up a fresh minimal Drupal 7 site. When I add 2 more language files e.g. French and German the database increases up to 3MB.

Why does Drupal store translation files to the database? What about performance? Wouldn’t it be much faster to load language files from the file system?

# Answer
> 2 votes
It's not likely that loading the translation files from disk would result in a faster page load time than it does from the database -- in fact I would expect it to be much slower. *This is essentially the job of a database: store and organize a large amount of data on disk and provide other programs the parts they need quickly.* Drupal (and all similar CMS's) are built on the assumption that for processing the content you are better off pulling from the database, and translations are basically just content. Disk-based optimizations usually help when you are trying to deliver unprocessed data as quickly as possible i.e. it's often faster to have the web server pull an image file off a disk instead of loading a script that loads a binary field from a database, and then streams it down.

There are several reasons that the database is likely faster for most use cases:

* To keep translations flexible and manageable there are actually many files that go into translating the back-end (each module can have its own PO file for each language). For a production site you'd then also be looking for a place to store all the translated content so we aren't looking at loading one file, but tens or hundreds of files to process.
* Each file has to loaded, parsed into useful structures, and then matched to the default (English) text. Yes, the site could cache a unified file, but that file could become massive and cause trouble on its own for some OSes and file systems.
* The site content is already stored in the database so overriding displayed text would have to come from two systems (either you'd have some in file and some in database, or you'd have all the default language in database and the translations in files), which adds complexity an likely processing time as Drupal determines where to pull the data from next.

Now think about what happens with the translations in the database:

Since nodes (and other fielded objects) store all the languages in the same tables, most of the time Drupal doesn't have to do anything extra. All the translations for a given field get loaded with the object and then Drupal picks which to display at render time. When Drupal does need to load a translation specifically, Drupal is able to re-write the queries used so it again has the data on hand at the same time it would have had the default language (that rewrite time should be trivial since it had a write a query in the first place). So almost nothing extra needs to be added to the load time to load the needed translated text.

Finally you have to keep in mind that good page load speed is mostly driven by caching, which Drupal does in the database by default, it does not load even the full node objects whenever it can avoid it.

***Disclaimer****: I don't know that anyone checked a file-based system when the translation system was initially written and I've never seen actual numbers run, so this is mostly speculation.*

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


title: PHP switch and translations

text:
# Question
Title: PHP switch and translations
Given a PHP switch statement, would it be a good (or bad) idea to use `t()` in `case` statements?

```
switch ($button_value) {
  case t('Clear'):
    // …
    break;
  case t('Search'):
    // …
    break;
}

```

# Answer
Drupal 7 uses code similar to the following one. (See `image_style_form_submit()`.)

```
  if ($form_state['values']['op'] == t('Update style')) {
    drupal_set_message(t('Changes to the style have been saved.'));
  }

```

That code is necessary to handle the submission done from two different buttons with the same form submission handler. (See `image_style_form()`; comments starting with *kll* are mine.)

```
  // kll: This is the first button using that submission handler.
  $form['effects']['new']['add'] = array(
    '#type' => 'submit',
    '#value' => t('Add'),
    '#validate' => array('image_style_form_add_validate'),
    '#submit' => array('image_style_form_submit', 'image_style_form_add_submit'),
  );

  // Show the Override or Submit button for this style.
  $form['actions'] = array('#type' => 'actions');
  $form['actions']['override'] = array(
    '#type' => 'submit',
    '#value' => t('Override defaults'),
    '#validate' => array(),
    '#submit' => array('image_style_form_override_submit'),
    '#access' => !$editable,
  );

  // kll: This is the second button using that submission handler.
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Update style'),
    '#access' => $editable,
  );

```

Avoiding to check the value of `$form_state['values']['op']` can be easily accomplished by using different submission handlers for different buttons.

I think this is the only case Drupal 7 uses the value returned from `t()` in a control structure; it can be avoided, and Drupal 8 does avoid that.

Generally speaking, using a string that is shown in the user interface in a control structure should be avoided, since any change to the text presented to the user would require a change in the logic of a different function. Since `t()` is used with strings shown to the users, code like the one you shown should be avoided.
> 1 votes

# Answer
In general, it would be a bad development practice. The whole purpose of `t()` is to provide *human-readable translated text*. As such, it can't be guaranteed as consistent switch logic because the translation context might differ.

In practice (e.g. a input button submit value on a basic form with little-to-no translation contexts), you might get away with it, but you're adding technical debt; if your application grows and other features start to rely on the switch logic, it's only a matter of time before the inconsistent logic will bite you.
> 4 votes

---
Tags: coding-standards
---


# Question
Title: How can I retrieve the value of a configuration object from a template?
I have a module that sets the value of a configuration object. I don't know how to retrieve that value from a template file.

In Drupal 7 I just needed `variable_get()` to get the value. What equivalent code should I use in Drupal 8?

# Answer
> 14 votes
The values saved as configuration items can be accessed using code similar to the following one.

```
$slogan = \Drupal::config('system.site')->get('slogan');

```

Since you are asking for a template file, that code should be split in two parts. My example is for the node.html.twig template file, but you can use the same kind of code for other template files too.

* In the preprocess function of your template file (e.g. `mytheme_preprocess_node(&$variables)`) you get the value of the configuration item

```
$variables['slogan'] = \Drupal::config('system.site')->get('slogan');

```
* In the template file (e.g. node.html.twig), you access that variable

```
{{ slogan }}

```

Be sure not to use a variable (`$variables['slogan']`, in my example) that is already used from the template file, or its preprocess functions.

---
Tags: 8, configuration
---


# Question
Title: Form selection with radios, ajax and taxonomy terms
In my form i get the message: "An illegal choice has been detected. Please contact the site administrator." after i didn't select a radio box in the 2nd form. How can i avoid this? NULL doesn´t work and key($type\_2) works only for the first call. If I changed the selection in the first form I must select a radio box in the 2nd form. If I don't do this, the message comes and I can\`t change the selection of the 1st form ... hope I could it little bit explain.

```
  $default = isset($input) ? $input : NULL;
  $form['step_2']['options']['type'] = array (
    '#title' => t('Types 1'),
    '#type' => 'radios',
    '#options' => $type, //get the array from a Taxonomy
    '#default_value' => $default,
    '#required' => TRUE,
    '#attributes' => array(
      'class' => array('clearfix'),
      'onkeypress' => array(
        'if(event.keyCode==13){this.form.submit();}'
      ),
    ),
    '#ajax' =>  array(
    'callback' => '_type_ajax_callback',
    ),
  );

  $default_2 = isset($input_2) ? $input_2 : key($type_2);
  $form['step_2']['options']['type_2'] = array (
    '#title' => t('Types 2'),
    '#type' => 'radios',
    '#options' => $type_2, //get the array of the Taxonomy which is referenced in the 1st Taxonomy
    '#default_value' => $default_2,
    '#attributes' => array(
      'class' => array('clearfix')
    ),
    '#ajax' => array(
      'event' => 'change',
      'wrapper' => 'calc-wrapper',
      'callback' => '_type_2_ajax_callback',
      'method' => 'replace',
      'keypress' => TRUE,
    ),
  );

  function _type_ajax_callback(&$form, $form_state) {
    return array(
      '#type' => 'ajax',
      '#commands' => array(
        ajax_command_replace("#floor-options", render($form['step_2']['options'])),
      )
    );
  }

```

Maybe i need to recreate the $type\_2 array, but I didn\`k know how i could do this. Need I an extra value recall in the ajax callback?

# Answer
> 0 votes
I found a little solution by clearing the default value after output the form. unset($form\['step\_2'\]\['options'\]\['type\_2'\]\['#default\_value'\]);

But if the user goes back in the multistep form and comes to this point the default value isn\`t set. It will not be recrate like the #options in the form array.

---
Tags: forms, ajax
---


# Question
Title: Views filter: how to compare two fields?
I have two content types "type1" and "type2" and one taxonomy. I have assigned the taxonomy to both of the content types. In type1 its name is "field\_type1\_test" and in type its name is "field\_type2\_test".

Now I want to fetch the title and body from the "type1" Where values of "field\_type1\_test" = "field\_type2\_test".

Is this possible?

If yes then how will I do this in views? Help please.

# Answer
> 1 votes
Not sure **you** are going to use it, but for those who may get here looking for the same:

Under the `Filter Criteria`, Search for `"Globals: Fields Comparison"`. For the record, the fields you want to compare should be among the fields you are loading in the current View.

So, if you want to compare to something you are not willing to show, you should add the fields to the View and check the `Exclude from display`.

Hope it helps!

---
Tags: 7, entities, views
---


# Question
Title: Hide views tab display on user profile to profile owner
I have a use case where I need to create a page for members of two specific roles (Contributor and NAD Contributor) to see their own unpublished content. Using views relationships and filters, I've created a tabbed page display at the path user/%/unpublished that only displays unpublished content belonging to the logged in user. All that works great except for one thing; the tab itself is visible on all user accounts, even though it's only visible to users of the specific roles. What this means is that there is a Unpublished tab (with no content) for other roles that don't need this page, so for instance the two Contributor roles would see an Unpublished tab on users of other roles.

Is there a way within Views to control the display of this tab to only be displayed on the profile pages of the roles specified in the Access settings for the display?

Thanks.

# Answer
> 0 votes
You might have already thought about this, but you could make a Panel Variant that only shows to those roles.

# Answer
> 0 votes
I assume that your context filter is *Content: Author uid*. In that case, you can add a validation criteria, following these steps.

* Under *When the filter value IS available or a default is provided*, select *Specify validation criteria*
* As *Validator*, select *User*
* Select *Restrict user based on role*
* Under *Restrict to the selected roles*, select the roles you need the view visible
* On *Action to take if filter value does not validate*, select *Hide view*

>

This is also applicable when the contextual filter is *Content: User posted or commented*.

---
Tags: 7, views
---


title: How to rewrite VBO results?

text:
# Question
Title: How to rewrite VBO results?
In the 'Rewrite Results' section of the 'Configure Field' popup, there are several options to rewrite the results - but not in the way I need. I want to substitute particular strings in the output.

How can I do that?

# Answer
> 1 votes
For string changes your best bet is altering the view in a custom module. Use hook\_views\_pre\_render to modify the output of the fields prior to the view result being fully outputted.

---
Tags: views
---


# Question
Title: How do I pass JavaScript variables back to PHP?
I'm trying to build a Drupal 8 module with a jQuery plugin. I wanted to pass some of the JavaScript variables to PHP so that I can save the variables into database.

This question asked about the way to do it in Drupal 7. Since `hook_menu()` is gone in Drupal 8, how can I accomplish this task?

# Answer
Where you implemented `hook_menu()`, in Drupal 8 you need:

* A .routing.yml file containing the routing definition

```
example.name:
  path: '/example/{variable}'
  defaults:
    _controller: '\Drupal\example\Controller\ExampleController::content'
  requirements:
    _permission: 'access content'

```
* A controller class for the page callback

```
class ExampleController {
  // ...
  public function content($variable) {
    // Do something with $variable.
  }
}

```

What is important is the file structure, which should be as follows, assuming that *example* is the machine name of the module.

* example
The directory containing the module

+ example.routing.yml
    + src
    The directory containing all the classes

    - Controller (directory)

        * ExampleController.php
            The file containing the controller

Keep in mind that you can change the machine name of the module, the route name (example.name), and the name of the class implementing the controller (ExampleController); the ones I used are only examples.
> 2 votes

---
Tags: 8, javascript, ajax
---


title: How to use Image EXIF Autorotate?

text:
# Question
Title: How to use Image EXIF Autorotate?
I have been trying to use the Image EXIF Autorotate Module. I have installed all the required modules like

* Imagecache Autorotate
* Original image with style

Also changed the image field property

* Apply style to image after upload = Image EXIF Autorotate

Nothing is happening I upload the image and no changes and it just upload the image as it is and if I try to rotate it manually nothing happens.

My requirements are as the image is uploaded the user sees the image and if wants to rotate it by clicking on it to do so.

# Answer
> 1 votes
The Exif Autorotate module

> Automatically rotates any uploaded image file according to the EXIF orientation information.

This EXIF data is embedded into the photo by the camera (and is often lost in compression). It contains the author, aperture settings, shutter speed, camera position and much more.

So if your photo is not created by a camera, or is already in the upright position, or has been compressed or downloaded, nothing will happen.

> My requirements are as the image is uploaded the user sees the image and if wants to rotate it by clicking on it to do so.

EXIF Autorotate does not rotate the photo by clicking on it, it rotates the photo to the position the camera shot it in (landscape or portrait).

---
Tags: 7, media
---


# Question
Title: Why does core uses the lib directory instead of the src one, for its classes?
Drupal 8 now uses the PSR-4 specification for namespaces and auto-loading; module developers need to keep their PHP classes in their module's src directory.
However, if you look in the core directory, Drupal keeps all these in the lib directory.

Why is this so?

# Answer
The following document explains the differences between PSR-4 and PSR-0, and the reason why PSR-4 was suggested.

It also explains that PSR-4 complies with the PSR-0.

Basically, when working with packages (modules) PSR-4 is preferable. But the base package can still use PSR-0 and be readable.
> 1 votes

---
Tags: 8
---


title: Background image in node content

text:
# Question
Title: Background image in node content
Is it possible to create a image file upload and then have that image appear as a background image within the "content" area of a particular page? I then want to put content (text) over the image. It would only be for a particular content type, but there is about 80 pages within this content type and each page/node would have its own background image.

To simplify, I have about 80 recipes. I have high-res images of each. I want the image to be the background and I would then have the specifics of the recipe on top of the background image.

Example:

# Answer
I've used the Dynamic Background module, which has a whole set of advantages for setting up background which vary according to content. At that particular time I used the Context module, which gave me a varied set of options (including content type, path, taxonomy, etc.) and which is very extensible. For your recipes, you could combine with the taxonomy functionality for different types of recipes, or select a particular image for each.

While I don't like using modules for everything, if this is going to be part of your day to day use of the site, I recommend that you choose the simpler solution, so you can try and choose what works better for you.

When you install the Module, you can set up which images you want to use, style the image and the type of behaviour you want for the whole site:

Since you can assign it using CSS, you can set it up for the content area only (#region-content), or whatever indicator you define in Panels. So, you can combine the logic in panels to show a particular background for a content type, or whatever logic you want to assign.
> 1 votes

# Answer
You should create a template file based on the content type.

For example, if you have "Receipe" content type then you should create tpl file based on content type's machine name that is

node--receipes.tpl.php

After creating this file you should clear cache.

In that tpl file you should get all the fields mention content type structure and using css you can apply desired page styling.

I hop it helps... :)
> 0 votes

# Answer
Another option is to add a new CCK image field on `Recipe` content type. With that your content creator can easily manage the image background he/she want without going to other configuration page. This approach requires some coding. You can use `preprocess_node` then pass the variable to your `node template` where you print the background.
> 0 votes

# Answer
Another solution: Create a view and create your own views-view-fields.tpl.php - file. Set up a relation to your picture. Insert a path field with relationship to your picture and place the following code to your tpl.php.:

```
<div class="your_background_wrapper" style="background-image(url: <?php print $fields['your_path_field']->content; ?>);"
  <div class="your_content">
  </div>
</div>

```
> 0 votes

---
Tags: media
---


# Question
Title: How can I show just one content with 5 images
I create search page with views in Drupal 8.

In filter criteria, I choose "Content: images:target\_id" because I want show contents that have images. (I set *operator* to *not empty*.) If a node has 5 images, the search page show that node for 5 times.

How can I fix this problem?

# Answer
> 2 votes
This can be solved by using aggregation

Change the No to Yes.

---
Tags: views, 8, search
---


# Question
Title: How do I add/remove form fields dynamically?
i have form build in standard like:

```
public function getFormId() { }
public function buildForm(array $form, FormStateInterface $form_state) { }
public function validateForm(array &$form, FormStateInterface $form_state) { }
public function submitForm(array &$form, FormStateInterface $form_state) { }

```

in my build form it return $form array with button add and remove.

if i press add, i would like to add new textfield above the add button (or anywhere else)

and next to the new text field i like to have a minus button ( - ) to remove the text field.

how do i achieve this in drupal 8 with ajax? how do i position the newly added textfield? how do i generate the field id (`$form['composition']['DynamicallyAddedAndRemove']`)?

i know how to build ajax callback but im not sure how to add new field and/or remove it dynamically through ajax

this is what i did and it didn't work, any idea why

```
class MyForm extends FormBase {
  /**
   * Class constructor.
   */
  public function __construct($coreService) { }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) { }

  /**
   * {@inheritdoc}
   */
  public function getFormId() { return 'id_form'; }

  /**
   * Overrides Drupal\Core\Entity\EntityFormController::form().
   *
   * Builds the entity add/edit form.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param FormStateInterface $form_state
   *   An associative array containing the current state of the form.
   *
   * @return array
   *   An associative array containing the settings add/edit form.
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

  /*
   * to make it short... $form build here
   * then continue...
   */

    // Initialize the counter if it hasn't been set.
    if (null !== ($form_state->get('fields'))) {
      // Nested this deep to avoid conflicts with other modules
      $form_state->set('fields', array(
        'module' => array(
          'fieldset' => array(
            'items_count' => 0
          )
        )
      ));
    }

    $max = $max = $form_state->get(['fields','module','fieldset','items_count']);

    $form['fields']['module']['fieldset'] = array(
      '#type' => 'details',
      '#title' => t('title here'),
      '#description' => t('description here'),
      '#open' => TRUE,
    );

    // Add elements that don't already exist
    for ($delta = 0; $delta <= $max; $delta++) {
      if (!isset($form['fieldset'][$delta])) {
        $element = array('#type' => 'textfield','#title' => t('tittle 00'),'#required' => FALSE);
        $form['fieldset'][$delta]['t00'] = $element;
        $element = array('#type' => 'textfield','#title' => t('title 01'),'#required' => FALSE);
        $form['fieldset'][$delta]['t01'] = $element;
        $element = array('#type' => 'textfield','#title' => t('title 02'),'#required' => FALSE);
        $form['fieldset'][$delta]['t02'] = $element;
      }
    }

    $form['fieldset']['add'] = array(
      '#type' => 'submit',
      '#name' => 'add',
      '#value' => t('Add field'),
      '#submit' => array(array($this, 'addSubmit')),
      '#ajax' => array(
        'callback' => array($this, 'addfield'),
        'wrapper' => 'foo-replace',
        'effect' => 'fade',
      ),
    );

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

    return $form;
  }

  /**
    * Ajax submit to add new ingredient.
  */
  public function addSubmit(array &$form, FormStateInterface $form_state) {
    $max = $form_state->get(['fields','module','fieldset','items_count']);
    $form_state->set(['fields','module','fieldset','items_count'],$max++);
    $form_state->set('rebuild', TRUE);
  }

  /**
    * Ajax callback to add new ingredient.
  */
  public function addfield(array &$form, FormStateInterface $form_state) {
    return $form['fieldset'];
  }

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

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

}

```

Thank you,

# Answer
> -1 votes
```
public function buildForm(array $form, FormStateInterface $form_state) {
  $form['fields']['modules'] = array(
      '#type' => 'details',
      '#open' => TRUE,
      '#title' => t('sample field'),
      '#description' => t('Explaination about sample field is here, Lorem ipsum dolor sit amet. bla yadda bla yadda. this is a very long description here. Lorem ipsum dolor sit amet. bla yadda bla yadda. this is a very long description here.Lorem ipsum dolor sit amet. bla yadda bla yadda. this is a very long description here.Lorem ipsum dolor sit amet. bla yadda bla yadda. this is a very long description here.Lorem ipsum dolor sit amet. bla yadda bla yadda. this is a very long description here.thank you.'),
      '#prefix' => '<div id="modules-wrapper">',
      '#suffix' => '</div>',
    );

    $max = $form_state->get('fields_count');
    if(is_null($max)) {
      $max = 0;
      $form_state->set('fields_count', $max);
    }

    // Add elements that don't already exist
    for($delta=0; $delta<=$max; $delta++) {
      if (!isset($form['fields']['modules'][$delta])) {
        $element = array(
            '#type' => 'textfield',
            '#title' => t('field Name'),
            '#autocomplete_route_name' => 'route here',
        );
        $form['fields']['modules'][$delta]['iqqq'] = $element;
        $element = array('#type' => 'textfield','#title' => t('aaa'),'#required' => FALSE);
        $form['fields']['modules'][$delta]['iaaa'] = $element;
        $element = array('#type' => 'textfield','#title' => t('sss'),'#required' => FALSE, '#suffix' => '<hr />');
        $form['fields']['modules'][$delta]['isss'] = $element;
      }
    }

    $form['fields']['modules']['add'] = array(
      '#type' => 'submit',
      '#name' => 'addfield',
      '#value' => t('Add more field'),
      '#submit' => array(array($this, 'addfieldsubmit')),
      '#ajax' => array(
        'callback' => array($this, 'addfieldCallback'),
        'wrapper' => 'modules-wrapper',
        'effect' => 'fade',
      ),
    );

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

    return $form;
  }

  /**
    * Ajax submit to add new field.
    */
  public function addfieldsubmit(array &$form, FormStateInterface &$form_state) {
    $max = $form_state->get('fields_count') + 1;
    $form_state->set('fields_count',$max);
    $form_state->setRebuild(TRUE);
  }

  /**
    * Ajax callback to add new field.
    */
  public function addfieldCallback(array &$form, FormStateInterface &$form_state) {
    return $form['fields']['modules'];
  }

```

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


# Question
Title: how to managed form '#type' => 'text_format' toolbar
I have a simple form:

```
$form['module']['name'] = array(
        '#type' => 'text_format',
        '#title' => t('Name'),
        '#description' => $this->t('Some notes'),
        '#required' => FALSE,
        '#default_value' => '',
        '#format' => 'full_html',
        '#allowed_formats' => array('full_html'),
    );

```

and it gives me:

Which is good, but then, i want to manage the toolbar to remove certain buttons (e.g. only allow bold, italic, and strikethrough and remove remaining)

Can this be achieved from my custom module?

# Answer
> 6 votes
You need to `+Add new text format` over at `/admin/config/content/formats`

Then `Configure` your new text format and remove those icons by grabing them and dragging them from the active toolbar to the available buttons section

Lastly, instead of `full_html`, use your custom format for your custom module.

---
Tags: 8, forms, wysiwyg
---


title: How to clone a content type?

text:
# Question
Title: How to clone a content type?
I want to clone a node type and add a few fields in it. I think the simplest will be to duplicate it and start working on it.

It seems there is no official way to clone a content type in Drupal 7. Features may allow it but there is no written procedure as to how it could be done.

I've even tried Bundle Copy module.

What'll be best way to clone any content type in Drupal 7?

# Answer
The easiest way is to use the Bundle copy module, but if you can't get that to work I'd recommend the Configuration Management module.

> The configuration management module enables the ability to keep track of specific configurations on a Drupal site, provides the ability to move these configurations between different environments (local, dev, qa, prod), and also move configurations between completely different sites (migrate configurations) without the use of modules with all configuration being owned by the site.

It's basically features with the stuff you don't need. Its sole purpose is to move configuration from one site to another.
> 12 votes

# Answer
I'm using the Field Tools Module for D7; it does exactly what you need.
> 4 votes

# Answer
Feature module is best option yet.
Here's what you need to do:

* Export the content type that you want to clone as a Feature.
* Re-name the content type (i.e., change the "machine name") in your Drupal site
* Upload and enable your Feature

This page may have your answer for "official way to clone a content type in Drupal 7".
> 3 votes

# Answer
I've created Content Type Clone, available as a sandbox project here:

https://www.drupal.org/sandbox/davidfiaty/2745827

It allows you to clone a content type in one click without having to look at PHP code or perform complex manipulations.

It's still a sandbox project at the moment but it will soon be available as an official Drupal module. Check it out!

Edit 1: The official release of Content Type Clone for Drupal 7 is here! https://www.drupal.org/project/content\_type\_clone Drupal 8 version coming soon.

Edit 2: The official release of Content Type Clone for Drupal 8 is available on the same page.
> 3 votes

---
Tags: 7
---


title: How to copy content type?

text:
# Question
Title: How to copy content type?
How to copy content type in Drupal 7 ?

I can't find a button to duplicate content type.

# Answer
> 14 votes
If you mean export by duplicate use the Features module.

> The features module enables the capture and management of features in Drupal. A feature is a collection of Drupal entities which taken together satisfy a certain use-case.
>
> Features provides a UI and API for taking different site building components from modules with exportables and bundling them together in a single feature module. A feature module is like any other Drupal module except that it declares its components (e.g. views, contexts, CCK fields, etc.) in its .info file so that it can be checked, updated, or reverted programmatically.

# Answer
> 21 votes
Maybe too late you can use the Bundle Copy module:

> Bundle copy is a replacement for the Content copy module which lives in the CCK project for Drupal 6. Has export/import support for: Node types, Taxonomy, User, Field API fields, Field groups

**UPDATE** 7.x-2.x-dev notes

The following features have been added:

* Export/import of Field Collection
* Cloning of Content types
* Export/Import of Commerce Entity bundles

Drupal 8: Bundle Copy is in Drupal 8 Core CMI.

# Answer
> 16 votes
I used the Field tools module, and it worked flawlessly.

All I did was create my second content type, used this module functionality to clone all the fields to the new content type, then uninstalled the module. Bundle copy and Features seem like ridiculous ways to duplicate a content type, this was super simple and exactly what I wanted.

# Answer
> 5 votes
The easiest way is to use Bundle Copy \- the 7.2 version which is in development but worked perfectly for me.

After installing the module, go to your "content types" page and click on the new "clone" tab.

Under "Source Bundle", select the content type you want to clone.

In "New Bundle Name", enter the name of the new content type you want to create. Click on "clone" and you'll now see that new content type in your list.

Field Tools also does the job but it's not as straight forward.

# Answer
> 4 votes
I found the (relatively new) Bundle Inherit module to be a very easy way of doing this. Be sure to enable the "Bundle Inheritance Node" (bundle\_inherit\_node) module in addition to the bundle\_inherit module, then you'll get a new "Inheritance" tab when creating new content types.

(It also gives you a choice between "soft inherit" and "strict inherit"...as far as I can gather, "soft inherit" simply does a one-time copy of the fields whereas "strict inherit" keeps track of the inheritance hierarchy.)

# Answer
> 1 votes
Just for the history, there is one more module that can handle this.

Config in Code (CINC)

# Answer
> 1 votes
Otherwise, Content Type Clone allows you to do it quickly and simply, without having to look at PHP code or perform complex manipulations:

https://www.drupal.org/sandbox/davidfiaty/2745827

It's a sandbox project at the moment, but it will soon be available as an official Drupal module.

Edit: The official release of Content Type Clone for Drupal 7 is here! https://www.drupal.org/project/content\_type\_clone Drupal 8 version coming soon.

---
Tags: 7, nodes
---


# Question
Title: Is this the correct way to make a panels layout
I have a 'working' panels layout that is getting the job done, but I'm unsure if it's the right way to do it.

Basically I copied the twocol\_stacked layout from Panels and fitted it to my needs. The layout I'm looking for is this:

```
------------
|          |
|----------|
|  |       |
|  |       |
|  |-------|
|  |       |
|  |       |
------------

```

What shows up when in the panels lay out looks like this:

```
------------
|          |
|----------|
|  |       |
|  |       |
|----------|
|      |
|      |
--------

```

My css isn't too strong and I don't know if there is a way to make it display correctly in the panels layout window. When I put some long text in the left side, it does push the lower div to the right the way I want, it just feels incomplete/wrong.

The css is mostly copied out of the `twocol_stacked.css` file with a few changes:

```
.panel-2col-stacked {
  /*  overflow: hidden;  */
  margin-top: 0;
  padding-top: 0;
}

.panel-2col-stacked .panel-col-top {
  width: 99.9%;
  clear: both;
}

.panel-2col-stacked .panel-col-top .inside {
  margin-bottom: .5em;
}

.panel-2col-stacked .panel-col-first {
  float: left;
  width: 33%;
}
* html .panel-2col-stacked .panel-col-first {
  width: 32.9%;
}

.panel-2col-stacked .panel-col-first .inside {
  margin: 0 .5em 1em 0;
}

.panel-2col-stacked .panel-col-last,
.panel-2col-stacked .panel-col-bottom{
  float: left;
  width: 66.9%;
}

.panel-2col-stacked .panel-col-last .inside {
  margin: 0 0 1em .5em;
}

.panel-2col-stacked .panel-separator {
  margin: 0 0 1em 0;
}

```

# Answer
You can use Panels to create your own layout over at `/admin/structure/panels/layouts/add-flexible`

This Video Tutorial covers on how to create one.

Basically, you add a column, and for each column you need to add a region. You can choose to use a flexible region or a fixed region, which you can resize by draging the grey bar.
> 2 votes

---
Tags: theming, panels
---


# Question
Title: Why do all auto created urls in my multilingual site cause a Page not found?
I have a multilingual site, using Drupal core 7.43 and the Redirect module, and the Pathauto module (and aliases are auto created without any problems).

Creating content translation I've got such problem: all auto created url aliases don't work.

When I change site language (as visitor) all seems Ok, I see all content has been translated. But if I (as a logged in user which is also an administrator) try to open an article (for example), or any other translated content, I am always getting "***Page Not Found***". Auto created url leads nowhere.

What is wrong?

**Note**: When I am manually adding redirect (eg. from `mysite/content/myarticle_1` to `node/122`), I am getting error "*You are attempting to redirect the page to itself. This will result in an infinite loop.*" When I change article language from native to "All languages" then redirect could be saved and works as it should be.

# Answer
Check your configuration at `Configuration -> Languages -> detection and selection`: the order specified there could be what explains the current behaviour in your site.

You'd have to experiment a bit with what the exact order in your case should be. In my experience, I often get these kind of issues to work by using an order like 'URL, Default, User', and not something like 'Default, URL, User'. It could well be that that is all that's needed here ... So try to experiment a bit with the various combinations in this order to see if it helps.

**Note**: Debugging is the *art of taking away all possible causes of a problem*. So sorry upfront if this answer turns out to not be *the* solution.
> 0 votes

---
Tags: 7, redirection
---


# Question
Title: Save tags in parent and children of vocabulary with shs module
How can I save my tags in parent and children of vocabulary with the shs module?

When I save my tag in children with the shs module, I want to show my content in parent and children path.

# Answer
on taxonomy/term/% view, enter contextual filter

> "Has taxonomy term ID (with depth)"

and change the depth settings to -1 and children view will take parent tag nodes too.
> 1 votes

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


title: Display two vocabularies

text:
# Question
Title: Display two vocabularies
I have a content type LAW with fields Title, law Category( Taxonomy Vocabulary) and Tags( Another taxonomy vocabulary) and last field is Description.

When Adding law content, I select in which category it belongs (lets say *Labor law*). I also add tags (e.g. *Condemnation*, *Judgement*) which are autocompleted as the default tags.

In view, I have displayed a list of all the categories, for example:

* Labor law
* Banking law
* Land law

When *Labor law* is clicked, I want a list of tags (*Condemnation*, *Judgement*) related to labor law; on clicking *Condemnation* or *Judgement* the nodes should be displayed.

# Answer
> 0 votes
I've made something similar using normal taxonomy view for "category list" and made an exposed filter for "tags", and to show just tags related to the exact category i've used the "Views Selective Exposed Filters".

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


# Question
Title: What is the correct URI syntax for using Forena to connect to a Postgres database?
I am trying out Forena Reports and in connecting to a Postgres table I set the the Driver Type to `Postgres Database` and the URI to `postgresql://username:password@127.0.0.1:5432/database`.

The problem is when try to connect to the database username and password are correctly sent as the database log produces this message.

```
 FATAL:  database "database password=password" does not exist

```

I have created a temporary workaround by creating a user with the same name as the target database, by using the URI and omitting `database` at the end, as in

```
postgresql://database:password@127.0.0.1:5432/

```

What is the correct syntax for this URI `postgresql://username:password@127.0.0.1:5432/database` which allows a user without the same name as the database?

# Answer
I think your `uri` is **not** correct, read on for more details, and the correct syntax (near the end) ...

To use Forena for connecting to a database (such as Postgres, Oracle, MS SQL, etc), you need to perform the steps described in the tutorial that comes with Forena, i.e. within the Data Sources Settings). These are the supported methods for defining Data Sources:

* use the ***Forena configuration data*** (located within `admin/config/content/forena/data`), and then use the "add data source" link (=`admin/config/content/forena/data/add`). There you can specify relevant options. After you select "Postgress Database" as the driver there, you'll be able to specify the remaining options within "Connection info", such as the `uri`.
* use a `settings.php` file which allows for including PHP logic. Have a look at the `settings.php` files for each of the samples included in Forena's subfolder `repos`.
* from within a custom module, use a `forena_alter_repos hook` (documented within Available Hooks in Forena's Development Guide).

Specific to Postgres, you can connect to it in one of two ways:

1. Using the Postgres native driver, connect using a `uri` that has a connection string similar to what is described in http://php.net/manual/en/function.pg-connect.php .
2. Using PDO Postgres driver use a syntax that is similar to http://php.net/manual/en/ref.pdo-pgsql.connection.php .

Looking at the (first) `uri` included in your question, I would specify a `uri` like so:

> `pgsql:host=127.0.0.1;port=5432;dbname=database;user=username;password=password`

**Disclosure**: I'm a co-maintainer of Forena.
> 0 votes

# Answer
This worked for me:

```
host='somesite.comOR_IP' dbname='YourDBName' user='DBUsername'

```
> 3 votes

---
Tags: 7, uri, forena, database
---


# Question
Title: How could I delete products and products displays using mysql?
I am using kickstart commerce and feeds import to import my products in a csv.

I need to delete some products and product displays using mysql in phpmyadmin because I had a bad import execution with mistakes, now they are in phpmyadmin, but they are not showing up in my backend admin views, I can't reimport again because it says "no new nodes" when I try to reimport althought I have checked replace items.

Please,, what mysql commands can I use to delete any products and products displays, that fits my condition, for example where title='%mypattern%'.

Thank you.

# Answer
You should not do that. Products are fieldable entities, and if you delete commerce products in database directly, you will have rubbish remaining there. You should use the api call commerce\_product\_delete(). http://www.drupalcontrib.org/api/drupal/contributions!commerce!modules!product!commerce\_product.module/function/commerce\_product\_delete/7

Sample code (please note, that I have not actually tried it, use for reference: Entity queries: https://www.drupal.org/node/1343708):

```
<?php

$pattern = 'mypattern%';

$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'commerce_product')
  ->propertyCondition('title', $pattern, 'LIKE')

$result = $query->execute();

if (isset($result['commerce_product'])) {
  $ids = array_keys($result['commerce_product']);
  commerce_product_delete_multiple($ids);
  $news_items = entity_load('node', $news_items_nids);
}

?>

```
> 2 votes

---
Tags: commerce, database
---


# Question
Title: Title's will not show translated version (multilingual site) in View list
I am working on a multilingual drupal website (webshop with commerce\_kickstart-7.x-2.37, drupal 7.43).

My articles are perfectly translated, even the titles. So when I go to the page of the article and change the language it shows the translated content including title.

I then made a new view. With that view i created a page to have all the titles of the articles in a list. The thing is though that those titles will not translate when i change the site language while it does perfectly change on the article itself!

Any help? Is it because I do not have internationalization views? I don't get why it is translating on the article itself but not on the overview page.

# Answer
I've found it myself.

when using fields, instead of adding content:title as a field, use entity translation:title. This will show the same field as your title but the translated version.
> 2 votes

---
Tags: 7, views, commerce, i18n-l10n
---


# Question
Title: What are the criteria to decide between modules ThemeKey and Switchtheme?
There are (at least) 2 modules that allow for switching between themes, i.e.:

What are the typical criteria, or pros/cons, for a site builder (without any custom coding or custom theming) to decide for either one?

I have the impression that using ThemeKey the administrator (only) determines how the theme is switched, while by using Switchtheme it is rather the user who decides (from a list predefined by the administrator). Am I close?

# Answer
Switchtheme is a user-driven theme switcher *with a couple of automatic options*. It provides a couple of blocks (displayed via a custom Switchtheme permission) where a user can select a theme to choose on a per session (or user account) basis.

Its automatic (admin configured) solutions are:

ThemeKey is a combination of user/admin driven theme switching based on various settings & rules.

Its theme switching solutions provided are:

* A per-alias solution that allows to set a theme for each Drupal alias
* A per-node solution that allows a permissioned user to set a theme for any node they create (as well a default option).
* A per-user solution that allow a user to set a default theme for their configured account.
* A chain of custom rules that evaluates various Drupal system, user, comment, node, taxonomy, and Views properties.
> 5 votes

---
Tags: 7, theme-negotiation
---


# Question
Title: Views contextual filter pages and duplicate content?
I just picked up a site that has its content represented by views pages with contextual filters instead of content pages, meaning that the content is available in two places. For instance, mysite.com/node/282 and also mysite.com/find-a-store/georgia/282-node-title. The pages that are utilized on the site and linked to via the main find-a-store page are the views ones, whereas the node pages seem to just sit there as sources for the view.

Is this a circumstance where there would be SEO penalties for having duplicate content? Will search engines even readily pick up on these views pages at all? Would it be better to change this so that the content is only available on the content page? I think it would be simpler to manage metatags/paths/redirects by using the content pages instead of views, as well.

# Answer
Ended up just scrapping the views pages and using the content pages instead. Couldn't find a satisfactory answer to whether or not the views would actually be indexed.
> 0 votes

# Answer
For removing them from Google search, you could use the Metatag module https://www.drupal.org/project/metatag to mark nodes of that Content Type as noindex.

For internal Drupal search I suggest adding the Custom Search module https://www.drupal.org/project/custom\_search You can use that to block searching of that Content Type.
> 0 votes

---
Tags: nodes, views
---


title: Authcache will cache user menu

text:
# Question
Title: Authcache will cache user menu
I have used Authcache and memcache to cache pages for authenticated users.

However, I have a user specific menu displayed at top right of every page, and the menu sometimes displayed a wrong users' infomation (avartar, username).

I have checked the **Authcache** *Retrieve menu title using Ajax or ESI* option at every menu entry's config page.

I also have tried to generate the menu items in code, but both with no good.

# Answer
If you serve your menus as blocks then you can use Authcache Block sub module. On the block admin page you will find an Authcache personalization setting.
> 0 votes

---
Tags: 7, caching
---


# Question
Title: Setting anonymous user timezone on page load
I'm developing a radio site where show times are displayed. Since it's an Internet radio station, I need to be able to display times in the user's timezone.

I'm able to detect which timezone a user is using (eg. Europe/London), but I don't know how to make Drupal use that timezone.

Is there any way to programmatically override Drupal's default timezone to instead use the timezone I detected?

I've looked through the documentation, but I have not been able to find a way for achieving this.

# Answer
> 2 votes
`drupal_get_user_timezone()` is the main function that retrieves the user's zone (based on a configured user setting, site setting, or PHP's `date_default_timezone_get()` depending on site/user settings).

This function's implementation is based off of retrieving configuration settings and native PHP function. There's no way to override that short of trying to redefine to this function (if you don't mind a solution that is a bit of hack).

An alternative to that would provide some wrapper function in a custom module. For example:

```
function mymodule_get_timezone() {
  // @TODO: At timezone lookup retrieval based on IP/Whatever
}

function mymodule_get_user_timezone() {
  // Or \Drupal::currentUser()->isAnonymous() in D8
  return user_is_anonymous() ? mymodule_get_timezone() : drupal_get_user_timezone();
}

```

Then reference `mymodule_get_user_timezone()` wherever you need to insert your own discovered timezone.

# Answer
> 2 votes
Drupal allows users to set their own timezone, but that is only for authenticated users; there isn't a setting for anonymous users. Even `drupal_get_user_timezone()` doesn't return anything useful for anonymous users, since (for anonymous users) it returns the default timezone set in PHP (i.e. on server side).

The only way to detect the user timezone is from JavaScript, which is exactly what Drupal does to auto detect the timezone used as default in the user profile edit form, when the user has not set their own timezone, yet. See misc/timezone.js.

```
  var dateString = Date();
  // In some client environments, date strings include a time zone
  // abbreviation, between 3 and 5 letters enclosed in parentheses,
  // which can be interpreted by PHP.
  var matches = dateString.match(/\(([A-Z]{3,5})\)/);
  var abbreviation = matches ? matches[1] : 0;

  // For all other client environments, the abbreviation is set to "0"
  // and the current offset from UTC and daylight saving time status are
  // used to guess the time zone.
  var dateNow = new Date();
  var offsetNow = dateNow.getTimezoneOffset() * -60;

  // Use January 1 and July 1 as test dates for determining daylight
  // saving time status by comparing their offsets.
  var dateJan = new Date(dateNow.getFullYear(), 0, 1, 12, 0, 0, 0);
  var dateJul = new Date(dateNow.getFullYear(), 6, 1, 12, 0, 0, 0);
  var offsetJan = dateJan.getTimezoneOffset() * -60;
  var offsetJul = dateJul.getTimezoneOffset() * -60;

  var isDaylightSavingTime;
  // If the offset from UTC is identical on January 1 and July 1,
  // assume daylight saving time is not used in this time zone.
  if (offsetJan == offsetJul) {
    isDaylightSavingTime = '';
  }
  // If the maximum annual offset is equivalent to the current offset,
  // assume daylight saving time is in effect.
  else if (Math.max(offsetJan, offsetJul) == offsetNow) {
    isDaylightSavingTime = 1;
  }
  // Otherwise, assume daylight saving time is not in effect.
  else {
    isDaylightSavingTime = 0;
  }

  // Submit request to the system/timezone callback and set the form field
  // to the response time zone. The client date is passed to the callback
  // for debugging purposes. Submit a synchronous request to avoid database
  // errors associated with concurrent requests during install.
  var path = 'system/timezone/' + abbreviation + '/' + offsetNow + '/' + isDaylightSavingTime;
  var element = this;
  $.ajax({
    async: false,
    url: settings.basePath,
    data: { q: path, date: dateString },
    dataType: 'json',
    success: function (data) {
      if (data) {
        $(element).val(data);
      }
    }
  });

```

You can use a similar approach.

* Using JavaScript, you detect the timezone for the user
* You make an AJAX call to make Drupal (or your module) know the timezone

---
Tags: users, datetime
---


# Question
Title: admin/commerce/products/add page says "You have not created any product types yet" when I have
Somehow, the Drupal Commerce page at admin/commerce/products/add is failing to recognise that I have product types and is giving this misleading error:

> You have not created any product types yet. Go to the product type creation page to add a new product type.

From reading this discussion and a look at the code here it looks like the Commerce module on this page bizarrely gets the list of product types from looking at the menus. There's a heap of "what worked for me was moving X to Y in the menus" but they all seem to be slightly different and match older menu naming conventions. This issue appears related but isn't. I have editted the Commerce menu and would like to keep my editted menu how it is.

How can I make sure that Commerce recognised my product types on this page? What has to be where for this page to recognise product types (or even better, is there a way to make it happen the normal way via entities instead of via menus?)

I've also tried bypassing my broken admin/commerce/products/add page completely with a redirect, but the redirect is ignored.

I've also tried moving my Products \> Create Item auto-generated menu links back under Store in the Management menu, and creating new menu links to those pages under Store in the Management menu, but neither works.

# Answer
> 1 votes
Those admin pages are generally based on the menu, so I think it makes sense that the commerce module is using the menu to build it.

It doesn't have to be like that, though, you can change it up pretty easily:

```
function MYMODULE_menu_alter(&$items) {
  $items['admin/commerce/products/add']['page callback'] = 'MYMODULE_commerce_product_ui_add_page';
}

function MYMODULE_commerce_product_ui_add_page() {
  $types = commerce_product_types();

  if (count($types) == 1) {
    drupal_goto(_MYMODULE_commerce_product_admin_add_path(key($types)));
  }

  return theme('MYMODULE_product_add_list', array('types' => $types));
}

function _MYMODULE_commerce_product_admin_add_path($type) {
  // Method taken from commerce_product_ui_menu()
  return 'admin/commerce/products/add/' . strtr($type, array('_' => '-'));
}

function MYMODULE_theme() {
  return array(
    'MYMODULE_product_add_list' => array(
      'variables' => array('types' => array()),
    ),
  );
}

function theme_MYMODULE_product_add_list($variables) {
  // Build up an HTML list of links based on $variables['types'], similar to theme_product_add_list()
}

```

---
Tags: 7, commerce
---


# Question
Title: Two Errors Lumped Into One - File Field Deleted - Cannot Be Found/Deleted/Recreated
I'm in the process of adding more content types/cleaning up old ones on my site. Except I keep coming across an error that has another part which seems to differ from other questions posted to this site.

I deleted a field because it had become obsolete, named "Site Document Attachment" which was a file field. Now whenever I make any change to the site, this error puts it on hold:

```
PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table
'cocempro_portal.field_data_field_site_document_attachment' doesn't exist:
SELECT field_data_field_site_document_attachment0.entity_type AS entity_type,
field_data_field_site_document_attachment0.entity_id AS entity_id,
field_data_field_site_document_attachment0.revision_id AS revision_id,
field_data_field_site_document_attachment0.bundle AS bundle FROM
{field_data_field_site_document_attachment}
field_data_field_site_document_attachment0 WHERE (field_data_field_site_document_attachment0.field_site_document_attachment_fid
= :db_condition_placeholder_0) AND
(field_data_field_site_document_attachment0.deleted =
:db_condition_placeholder_1) ; Array ( [:db_condition_placeholder_0] => 1552
[:db_condition_placeholder_1] => 0 ) in field_sql_storage_field_storage_query()
(line 652 of /home/cocempro/public_html/portal/modules/field/modules
/field_sql_storage/field_sql_storage.module).

```

And I did double check to make sure there weren't any tables named that in my MySQL database, as that happened to me once before - and the field isn't listed in my field report. And playing the easy way out, I just tried to recreate the field in the exact same way, but that came back stating that the machine name was already in use.

So where to I go from here? I'd appreciate any help anyone might be able to offer in regards to this problem, because I'm not sure where to go at all. Thanks

# Answer
You should, in theory, be able to just remove the references to that field from the `field_config` and `field_config_instance` tables, clear caches, and then be able to recreate the field again as if it never existed.

Please do try that in a development environment first; it's also possible, in theory, that some other non-core module has a reference to that field in some way, which may either be responsible for the problem in the first place, or cause problems when you manually remove the data.
> 1 votes

---
Tags: entities, files, database
---


# Question
Title: Why, while developing a module, do I get an error for not specifying a handler when one exists?
Receiving the error "entity type did not specify a access handler", even though the entity type definitely does specify an access handler, like so:

```
/**
 * @ConfigEntityType(
 *   handlers = {
 *     "access" = "Drupal\give\GiveFormAccessControlHandler",
 *   },
 * )
 */

```

And the file `src/GiveFormAccessControlHandler.php` is in place and ready to handle access.

Why won't Drupal 8 see it?

# Answer
Drupal 8 made the decision to be fast by default and use the APC Classloader if it is available. It is faster, but it doesn't necessarily catch changes as you make them. To not have to restart your web server during development, you can set your local environment to *not* try to use a better-for-production class loader.

For instance, in **local.settings.php** add:

```
$settings['class_loader_auto_detect'] = FALSE;

```

As documented in settings.php:

> If the APC extension is not detected, either because APC is missing or because auto-detection has been disabled, auto-loading falls back to Composer's ClassLoader, which is good for development as it does not break when code is moved in the file system.

In the issue where this change was made, Berdir warned that it would stymie developers. More background information at what to do when developing a Drupal 8 module and a class file just isn't being loaded even though it is definitely there.
> 3 votes

---
Tags: 8
---


title: Any way to filter by week number?

text:
# Question
Title: Any way to filter by week number?
Drupal 7, Views 3

I've got several views configured which display data over many years. The data is filtered by Year using a date field as filter criteria. For each year I have attachment views that I need to filter further by week. Rather than determining the exact dates for the weeks of each year and inputting them manually as filter criteria, I'm wondering if there is any way to add a filter criterion to filter by week number, i.e. week 1 thru week 52. That way the only date that needs to be set is the year for each view, and the rest happens automatically according to week number.

I am aggregating a lot of data by year and week in a table view where each column is an additional view attachment and trying to avoid having to manually enter the filters for week dates per year.

Does anyone have any advice/hints for me on this? Thanks very much.

Here is the code I am currently playing with:

```
function x_week_start($date) {
    $ts = strtotime($date);
    $start = (date('w', $ts) == 0) ? $ts : strtotime('last sunday', $ts);
    return date('Y-m-d', $start);
}

function x_week_end($date) {
    $ts = strtotime($date);
    $start = (date('w', $ts) == 0) ? $ts : strtotime('last sunday', $ts);
    return date('Y-m-d', strtotime('next saturday', $start));
}

$date = '2013-01-14';
$start = x_week_start($date);
$end = x_week_end($date);
$inquiry_date = date('Y-m-d', $data->field_field_inquiry_date[0]['raw']['value']);

if ($inquiry_date <= $start) {return FALSE;}

```

I should add that the `field_inquiry_date field` is a unix timestamp.

# Answer
> 2 votes
Here's a trick: create a new date format by navigating to Admin \> Configuration \> Regional and Language \> Date and Time and clicking on the Formats tab (admin/config/regional/date-time/formats).

Set it to W (that's uppercase W), and it will give you week number, which you can use with any date.

That way you can include the date field directly in views, set the W filter and use the aggregation, filter, etc without any additional coding.

# Answer
> 1 votes
https://www.drupal.org/project/views\_date\_format\_sql might help you in grouping the table data with date formatters of SQL.

---
Tags: 7, views
---


# Question
Title: Allow anonymous user to search custom account field
I have a custom account field called *license number*.

How do I allow anonymous users to search for that license number and, after they select it, view that user's profile?

# Answer
> 1 votes
This can be covered by the Views module in a few steps.

1. Make sure anonymous users have the *Access User Profiles* permission.
2. Create a user view with a page display in the Views UI.
3. Add a exposed filter on your view for your license number field. Set the **Operator** to *Is equal to* if you want a search by full account number only, or set it to *Contains* if you want a partial/full account number search.
4. Adjust the display how you see fit. The display can contain links to the user profile page.
5. Save the View.

From this point you should now have a page from which to search for user profiles with your custom account number field.

---
Tags: users, views
---


# Question
Title: How to display a block to a specific user?
I need to display a block just to a specific user. I don't want to create a role just for a user. that does not make sense!

# Answer
> 1 votes
Below is an answer for a user with `uid` = 2 (change to whatever `uid` fits for your case).

# Part 1: Rules block visibility

You should be able to get this to work using 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 intercept the actual user who's using the site, i.e. if it is **YES** or **NO** (a boolean, right?) the user with `uid = 2`.

# Part 2: Create an appropriate Rules Component

The Rules block visibility module doesn't have a lot of documentation, except in the README.txt that comes with this module. Here is what the crucial part of it is (to get the idea):

> Configuration is done on a per-block basis. To control a block visibility using a rule component, go to the block settings page, scroll down to the "Rules" tab, and select the Rules component that you want to use.
>
> Notice that to be able to be used by this module, a Rules component *must* be constructed in a very specific way. See the next section for more information.

This module comes with 2 sample Rules Components, that should help to understand the **K**eep**I**t**S**uper**S**imple concept behind it.

By looking at these samples, I was able to create another Rules Component which looks like so:

```
{ "rules_block_visibility_hide_block_for_user_2" : {
    "LABEL" : "Hide block for user 2",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false }
    },
    "IF" : [
      { "data_is" : { "data" : [ "site:current-user:uid" ], "value" : "2" } }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}

```

You should be able to import this rule in your own environment.

What this Rules Component does is "only" return a boolean (**1** or **0**), based on the condition if the user's uid is YES or NO equal to `2`.

With that, we're coming close to an actual answer to your question.

# Part 3:

Head over to the "Block" settings for the block you want to hide for the user with `uid = 2`. At the bottom of it's settings, within the typical "Visibility settings", there is now (after you enabled the Rules block visibility module as in Part 1) an extra tab labeled "*Rules*". Using that tab will allow you to select a "Rules Component" that will do what's documented below that selection list field, ie: "***Show this block only if the selected rule returns a positive value. Important: to be listed here, a block visibility rule must have specific parameters and return values.***".

And guess what, in my case I just selected my Rules Component from Part 2

**Note**: it doesn't matter what type of block it is (created by a view, or something else), it works in all cases.

# Answer
> 2 votes
I would implement hook\_block\_view\_alter() and remove the block's content when the uid is not the user you were aiming at. In this example we only show the block content for uid 2.

```
function hook_block_view_alter(&$data, $block) {

   if ($block->module == 'somemMdule' && $block->delta == 'someDelta') {
         global $user;

    if ($user->uid != 2) {
       $data['content'] = array();
    }
  }
}

```

# Answer
> 2 votes
You can also write php code in block visible settings.

```
<?php
global $user;
if($user->name=="admin") {    return TRUE;}
else {   return FALSE; }
?>

```

---
Tags: 7, blocks, users
---


# Question
Title: How can I transfer votes to nodes selected from an entity reference list?
I create a form where users can submit their opinion and votes about nodes that they select from an entity referenced list. How can I assign the votes to the entities that apoear on this list?

eg. "Review" content type are completed by auth users. In "review" form there are 2 fields "class" and "teacher" where the user can select from an list of nodes "class" and "teacher" content types. After the user select the "class" and "teacher" then must vote (voteapi & rate) and complete an opinion (textarea) about the nodes he selects.

# Answer
> 1 votes
Use the Inline Entity form, which allows you to set a view with the list of nodes and modify them directly (you would set the voting in the voted node e.g., the class or teacher, in your example).

The plan is for you to set up the **Review** content type with a Entity Reference field. This will allow you reference a View where you can set up your Class and Teacher Nodes.

You need the following Modules: Five Star and Voting Api (Which you already have) Views, Entity API, Inline Entity Form.

The way I understand your process is as follows:

* You have a set of classes and a teachers
* You intend to make available a set of these classes and teachers to a different content type (this is review), to generate votes for that class and/or teacher
* The number of classes/teachers available for that review to emit a vote from is unspecified (may be all or a subset of them)

To go about this you need to have the following:

* Voting fields in class and teacher content types
* Create a Entity Reference View which displays the list of nodes you need (one for each, selecting their respective content types).
* Add a Entity Reference field in the review content type with the Inline entity form - multiple values widget.
* While setting the field:
    + Check Allow users to add existing nodes, so that they can select the class/teacher from your current list.
    + Select in Entity Selection: *Views: Filter by an entity reference view*
    + Select in View used to select the entities the view you would prefer for that field (teacher or class)

You should be able to add the classes/teachers you want to vote for. Also, you can control the entities shown by the view (so you could add context filters). Be mindful of setting the votes so you can vote while editing.

---
Tags: 7, rating
---


# Question
Title: Navigation block title no longer defaulting to user name in d7
The default behavior for the Navigation block in d6 was to replace the word Navigation with the user name. It appears that this logic was removed from the core user module in d7. My client stills wants the user name to display. Is there a way to duplicate this same behavior in d7 ??

What complicates things a bit is that we are using a mini panel that includes that block but I haven't figured out a way to override the title with the user name. I've tried using the user:name token as the Navigation block title and then overriding the title with %title but it displays the literal value 'user:name' instead of the actual user name.

# Answer
Have you set "user" in the contexts? It sounds like you do not have access to the %user:name token, and that's why it sets the actual text instead of the username.
> 1 votes

# Answer
This is the covered by the use case of the Block Title Link module. It allows you to replace any block title with your arbitrary title/link with token support (e.g. `[current-user:name]`). If you're just looking to rename the block title (without a link), you can leave the link field empty and just rewrite the title display.
> 1 votes

---
Tags: 7, navigation
---


# Question
Title: How to import node view count with Feeds and Statistics module?
After enabling drupal 7.x core Statistics module, on the feeds node processor mapping page, I still cannot find any suitable target to map.

# Answer
This isn't currently a feature of the feeds module. You could write a module that implements `hook_feeds_after_save()` to create the needed database records.
> 0 votes

---
Tags: 7, feeds
---


# Question
Title: Help understand/solve this Warning: Invalid argument supplied for foreach() in views that requires class registry clean to mend
Out of nowhere without any changes to the view or the views data I suddenly started receiving this error:

```
Warning: Invalid argument supplied for foreach() in views_handler_filter->prepare_filter_select_options() (line 1104 of /var/www/site/public_html/profiles/commerce_kickstart/modules/contrib/views/handlers/views_handler_filter.inc).

Warning: Invalid argument supplied for foreach() in _form_options_flatten() (line 2684 of /var/www/site/public_html/includes/form.inc).
An illegal choice has been detected. Please contact the site administrator.

Warning: Invalid argument supplied for foreach() in form_select_options() (line 2836 of /var/www/site/public_html/includes/form.inc).

```

The view has an exposed filter and the view is unusable until cache is cleared, then after some time it "blows up" again.

Prior to this starting happening I created a custom module page which creates a JSON structure with db queries and caches it. Can this be a caching issue or can cache run out?

**Edit:**

I have services nodes, and those services nodes have a taxonomy reference field\_service\_locations. The view that breaks displays the nodes and has an exposed filter for choosing the service location (based on the same field\_service\_locations)

In the log I see another error message happening right before this:

```
Illegal choice 12 in field_service_locations element.

```

This error is from one of the services page, however the term with id 12 is a location term, and exists.

However the select list displays no values and also when editing the views filter, it doesn't have values until cache clear.

**Further down the road**

I have been trying to pinpoint the issue further, what makes it more difficult is that I don't know exactly how to replicate it, as it just happens after a period of time.

I have pinpointed the cache to clear, that resolves the issue is "class registry" or "page and else" - not sure yet what to do with this information.

With the help from Shawn Conn I've been able to further pinpoint the issue that the $options variable received by prepare\_filter\_select\_options() is FALSE instead of an array.

I'm not sure if my custom module that caches data could be the culprit (testing it will take some time as I'll have no other option than to disable the module caching part and wait to see if the issue rises again or not), it's however implemented as follows:

```
function custom_module_json_output_menu()
{
    $items = array();
    $items['services/%/json'] = array(
        'access callback'   => true, // available to all
        'page callback'     => '_services_json_object', // defined below
        'page arguments'    => array(1),
        'delivery callback' => 'drupal_json_output'
    );

    return $items;
}

function _services_json_object($service_type) {

    $cache_id = "services_json_".$service_type;
    $response = cache_get($cache_id, 'cache');
    if (empty($response)) {
        $response = array();

        $service = taxonomy_term_load($service_type);
        if ($service->vocabulary_machine_name == 'product_category') {
            // populate $response...
        }
        cache_set($cache_id, $response, 'cache', CACHE_PERMANENT);
    }

    return $response;
}

```

I also deleted rows from the cache\_bootstrap tableone-bu-one, none seemed to resolve the issue and truncating the table completely didn't resolve either. As pointed out to me, that the common table for both cache clears that seem to resolve the issue is this table I'm in the ditch again. My site does have 2 languages, and I just noticed that while on the english version this seems to hit the fence, the german one is ok.

**EDIT 3:**

Disabling the caching on my custom module does not seem to be the issue, as the error happened again.

Problem still unsolved and I'm out of places to debug in the database. What could possibly cause a views select options exposed filter to suddenly no longer have options..? It's not the cron, and this happens even overnight when there's no activity (all this is in a dev only accessible environment)

**EDIT 4:**

I seem to be able to reproduce this by runing cron a couple of times, not sure what that means.

Yes, it's definately cron, and after running cron I get no errors. Even though clearing class registry through the admin menu "flush cache -\> class registry" works, invoking registry\_update() does not resolve the issue. Neither does registry\_rebuild() which seems to be the function "class registry" clear invokes, which in turn invokes registry\_update() and system\_rebuild\_module\_data(). Or is calling any of those fron drush ev not supposed to work?

As it seems to me, the class registry clear also invokes clear all cashe, as there's no break after the cache. This may be why "drush cc all" also seems to resolve the problem, so I'm afraid I just got further from the cause of this issue.

cache\_clear\_all('\*', 'cache\_views', TRUE) seemed to be the one that solves the issue, and makes running cron no longer cause the issue. However flushing all caches, makes cron cause the issue again.

Again, this error is resolved with cache clear, but only cache clear. This view is my front page view :(

# Answer
> 3 votes
A few key things to know will help debugging here.

The errors mentioned seem to be symptoms of your view's exposed filter form selectbox not being correctly built. As the `views_handler_filter::prepare_filter_select_options()` method name implies, this function is responsible for building your selectbox options. For some reason, the `$options` data supplied to it is empty. The "illegal choice" errors are where the exposed filter form being submitted with a value that's not in the empty selectbox.

As you've identified, there is bad data in your cache. It helps to know that the Admin menu empty cache options you've selected affects a few Drupal cache tables. For **Class registry**, you're touching (`via _registry_update()`) `registry`, `registry_file`, & `cache_bootstrap` (the `lookup_cache` entry) tables. In **Page and else**, you're touching the `cache`, `cache_bootstrap`, `cache_filter`, & `cache_page` tables.

Given that `cache_bootstrap` is the common entry here, you might want to inspect that. If your custom module is affecting this table (doesn't seem likely but there could be some odd bug), that might be relevant. More relevant might be the `cache_bootstrap.lookup_cache` entry that is both touched in both cache flush operations. It contains class name/include file entries. If this is corrupted, perhaps a key include/class isn't being included that's key to making your selectbox options appear.

With this information known, you have to identity the relationship between the bad cache data, what cache entry is causing problems, and how it relates to your rendered select options.

For troubleshooting, a `ddebug_backtrace()` placed in the `prepare_filter_select_options()` will produce a stack trace that might give you indication why no data is being supplied to the method and trace it back to a bad cache lookup.

For recreating, it might be useful to backup your site once the cache data is corrupted. One strategy you might try to employ is to selectively remove cache entries until you find the one corrupted entry that is causing the problem. Since you have a snapshot of the site DB, you can restore it as much as needed to narrow down the possible source of the bad cache data.

Once you've identified the cache entry in question and how it relates to `prepare_filter_select_options()`, hopefully that should shed some light on how/why things are misbehaving.

---
Tags: 7, views, caching
---


# Question
Title: I don't want ajax submit / callback validate form '#required' => TRUE,
I have form with static fields and dynamic fields as follow:

fieldset

1. textfield00 (require = true)
2. textfield01 (require = true)

fieldset

3. textfield02

fieldset

4. add textfield
5. submit button

so, everytime add textfield pressed, it will add new/duplicate textfield02.

with add textfield code as follow:

```
$form['fields']['modules']['add'] = array(
      '#type' => 'submit',
      '#name' => 'addtextfield',
      '#value' => t('Add more TextField'),
      '#submit' => array(array($this, 'addTextfieldSubmit')),
      '#ajax' => array(
        'callback' => array($this, 'addTextFieldCallback'),
        'wrapper' => 'wrapper',
        'effect' => 'fade',
      ),
    );

```

the adding field is working fine, the only problem i have here is: because textfield00 and textfield01 is mandatory, if i pressed add button, it will send me an error message 'mandatory fields' before i can add new textfield.

so how can i 'bypass' the requried validation, everytime i press add textfiled and only validate 'required = true' when i press submit button.

Thank You, AnD

# Answer
**'#limit\_validation\_errors' =\> array();**

```
$form['actions']['previous'] = array(
    '#type' => 'submit',
    '#value' => t('Previous'),
    '#limit_validation_errors' => array(
      // Validate $form_state->getValue('step1').
      array('step1'),
      // Validate $form_state->getValue(array('foo', 'bar')).
      array('foo', 'bar'),
    ),
    '#submit' => array('some_submit_function'), // #submit required.
  );

```
> 0 votes

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


# Question
Title: Different ways of logging in a user without having them to type anything?
I'm on Drupal 8 and currently looking to replicate similar functionality like: https://www.drupal.org/project/urllogin -- They do not have a D8 version yet.

I need to auto login a specific user depending on which URL the user visits. How can this be done on D8? I was thinking of using rules, but there doesnt seem to be an **action** for "login a user" if Path alias equals X.

Another possible scenario I could just do is create a custom module to auto login a user. Which functions would I need to fire in Drupal 8 to do this?

# Answer
You just need to use drupal\_session\_regenerate(), you can see the use of this function here. All you have to do is either play with Uid or if you want to do this for anonymous user then you just create a user xyz and use that ID for session regenerate. You can grab the UID from URL for different users like www.example.com/custom-url-to-login/125 or www.example.com/custom-url-to-login?uid=125

now supposing 125 be the ID of user whom you want to login on visiting the URL.

The code will go something like this:

```
global $user;
$user = user_load(540); // suppose 540 be UID of xyz account
drupal_session_regenerate();

```

This is just a suggestion, if it does not work for you please let me the know the correct solution.

Thanks
> 2 votes

# Answer
You can use Auto Login URL Module

**Use case**

You may get an auto login URL for a user($uid).

```
// Drupal 7.
$auto_login_url = auto_login_url_create($uid, $destination);
print $auto_login_url;

// Drupal 8. As above plus.
$alu_service = \Drupal::service('auto_login_url.create');
auto_login_url = $alu_service->create($uid, $destination);
print $auto_login_url;

```

Or convert all links of a text to auto login for a `user($uid)`.

```
// Drupal 7.
$auto_login_url_text = auto_login_url_convert_text($uid, $text);
print $auto_login_url_text;

// Drupal 8. As above plus.
$alu_service = \Drupal::service('auto_login_url.create');
auto_login_url_text = $alu_service->convert_text($uid, $text);
print $auto_login_url_text;

```

Also there are two tokens:

```
['tokens']['user']['auto-login-url-token']
['tokens']['user']['auto-login-url-account-edit-token']

```
> 1 votes

---
Tags: users, 8, rules, actions
---


# Question
Title: Error when running update.php about field_data_body existing
```
DatabaseSchemaObjectExistsException: Table field_data_body already exists. in DatabaseSchema->createTable() (line 660 of /srv/bindings/e27b77cd6512471f902f88e9e0704451/code/includes/database/schema.inc).

```

Any thoughts on where to track this down? Seems someone decided to delete all the field\_body instances on the site and replace them with field\_page\_body, but I'm not sure why that would cause the above issue during an update.

# Answer
I would recommend you to apply this patch, that can be maybe the solution for you :

https://www.drupal.org/files/issues/1551132-drupal-install-schema-shared-tables-69-D7.patch
> 1 votes

---
Tags: 7, updating
---


# Question
Title: How do I get the raw URL as a field in Views?
In views I need to return the raw url that is provided as the href value to the title field (when as a link) or the Content: link value. I thought originally I could choose Content:link and strip the HTML in a rewrite, but no go.

I need the full URL so that I can pass it as a parameter in a field rewrite. Thoughts on how to get this only?

# Answer
There is number of ways you can do this but the following is fairly easy.

In your view add NID as a field.

Create a 'row style' template that loops through the $fields object.

In your template file, before the loop assign a variable with the NID value from the field.

```
$nid = strip_tags($fields['nid']->content);

```

Then use the node\_load() function to load a node object.

```
$node = node_load($nid);

```

You should be able to access anything you want including the path from this node object.

To see whats in it use Devel if you have this installed or just use the PHP var\_dump() function.

Even better check whether you have a 'path' field the you can add.
> -3 votes

# Answer
As per the comment here http://drupal.org/node/458316#comment-6236984

In views 3.x you can use "Path" field with option "Use absolute link (begins with "http://")" in Rewrite results section.
> 32 votes

# Answer
Yes, we can use the `path` field. This also support multilingual content. Please find attached screenshot to see what it looks like.
> 16 votes

# Answer
Adding to rakesh.flake comment, we have a option to add the absolute URL as well in the settings.
> 2 votes

---
Tags: 7, views, entities
---


# Question
Title: How to prevent closing CTools modal window with ESC during AJAX?
How can I prevent closing CTools modal window with ESC key during AJAX request?

# Answer
> 0 votes
Try this one

```
/**
 * Override Ctools modal content function to prevent closing the modal with
 * the escape key.
 */
Drupal.CTools = Drupal.CTools || {};
Drupal.CTools.Modal = Drupal.CTools.Modal || {};
var modalContent = Drupal.CTools.Modal.modalContent;
Drupal.CTools.Modal.modalContent = function(content, css, animation, speed, modalClass) {
  modalContent(content, css, animation, speed, modalClass);
  $(document).unbind('keydown', modalEventEscapeCloseHandler);
}

```

---
Tags: forms, ajax, chaos-tool-suite
---


# Question
Title: Datepicker not appearing when an url alias is added
I've implemented a datepicker in a textfield on a basic page from Drupal. It works fine and the url shown is "http://....../drupal7/node/28".

If I add an url alias to the url, the datepicker doesn't appear. It only reappears if I remove the url alias.

Anyone know how to show the datepicker with an url alias?

The files used are:

jquery-1.10.2

jquery-ui.js

jquery-ui.css

# Answer
I have date\_popup module under date enabled and any form field with date\_popup type displays date picker for me:

```
$form['my_date'] = array(
      '#type' => 'date_popup',
      '#date_format' => 'Y-m-d',
      '#title' => t( 'My Date' ),
  );

```

It seems to work for me regardless of which url it is used on.
> 0 votes

---
Tags: 7, javascript, uri
---


# Question
Title: Send e-mail when a field has a specific value
I use the Workbench moderation module for Articles workflow. I would like to send an e-mail when Workbench moderation field has the *needs review* value.

I tried using the Rules module, but I don't know how to select this field and compare data. How do I get the value of the Workbench moderation field in a rule?

# Answer
> 0 votes
I don't know when you need to compare the field data,But you can probably do a form alter or modify the Workbench moderation module function.

Then create a component instead of rules and use a parameter if needed for field id or data.In action add send email.

Then you can invoke that component in the function you are using like this:-

rules\_invoke\_component('rules\_save\_review\_field', 'paramval1', 'paramval2', ....);

---
Tags: 8, rules, workflows, workbench
---


# Question
Title: Output all possible items in a list field as a View?
Is it possible to output all of the possible options in a list field type (of a content type) as a view?

# Answer
> 1 votes
My own answer (but still feel free to chip in):

1. Create a View of the Content Type containing the list.
2. In the FIELDS section only have your Content Type Field that contains the list Content: (whatever the name of your list field is called)
3. Click on your Content Type Field under FIELDS for the 'Configure field: Content: Your field' Under Multiple Field Settings, make sure display multiple fields on one row is unchecked
4. add your Content Type Field to the FILTER CRITERIA. Filter should be set to 'is not empty' / not null
5. over to the right hand side of the Views settings, enabled Aggregation
6. back to FILTER CRITERIA and click Aggregation Settings for your content type field and select COUNT DISTINCT.

What this does is produce a unique list of items from all of the content that has this field with those items checked.

What it won't do is show items in from the list field if they have not yet been selected in any content.

It may also have a performance overhead to generate the list like this as it is based on the data from the entire set of content. The positive benefits flipside of this is that perhaps you only want to see items where there is content that has it checked and you may want to extend the list to include number of content using a list item.

Final thought - why did I not just use a taxonomy? this would have been far easier and Views supports this better. Reason: currently (at the time of writing), Views does not support context filtering on taxonomy where *multiple* arguments are provided in the URL. I want to use this list from this View as a menu block to filter data in a View in another block in Panels from multiple fields.

**References / Credits:**

How do I remove duplicates when using the random sort?

# Answer
> 0 votes
The alternative option (the feasibility depends on the other requirements), would be to use a taxonomy vocabulary for holding all possible values.

In the node you can create a reference to a term in this vocabulary and use autofill or a drop down as a widget. In the node edit page you can list select the term you need.

In views you just load all terms of the given vocabulary.

In most cases I guess this will be easier, but you might have certain criteria they require the use of fields.

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


title: Disallow /node/ in robots.txt

text:
# Question
Title: Disallow /node/ in robots.txt
I have given alias to the above pages as

> www.example.com/node/123

(to)

> www.example.com/about

and

> www.example.com/node/145

(to)

> www.example.com/contact

When search with a keyword in google, google crawler takes this page as www.example.com/node/123 and not as www.example.com/about. same in the case of contact page. Please advice me whether i can add Disallow : /node/ to my robots.txt to solve this issue. Will this affect my about and contact page from crawling. Will this affect only nids or the alias too. Thanks in advance.

# Answer
> 1 votes
Having you pages accesible both via `/node/*` and `/somealias` leads to duplicate content and should be avoided as this can cause an SEO penalty. Under normal circumstances you could take a look at the global redirect module

> GlobalRedirect is a simple module which…
>
> Checks the current URL for an alias and does a 301 redirect to it if it is not being used. ...

It saves you from alteting robots and comes with some additional benefits.

Related to your question:

Since they are different paths, blocking one does not affect the other. And as explained above it is advised to prevent crawlers from indexing both. It should be safe to block one of them.

However, for Google indexing your `/node` paths, they might be in use somewhere. So first check your existing links and make sure there is nothing linking to those paths. Then add it to robots. (If it is still in use when you block it, you risk certain parts of your site not getting indexed.)

# Answer
> 0 votes
You can add

`Disallow: /node/*` in robots.txt and please check again

---
Tags: 7
---


# Question
Title: How to run drush with cron (elysia cron)?
**Problem**

I can't get cron (specifically elysia cron) to run with Drush. I've been using this as a guide. What have I missed/done wrong?

**My Crontab**

```
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
COLUMNS=80

*/5 * * * * /usr/bin/drush @main elysia-cron
* * * * * env > /tmp/cronenv.log

```

Checklist:

* I've used *www-data* for my crontab. This is the default nginx server user.
* The path to drush (`/usr/bin/drush`), comes from `which drush`.
* I've used an alias for the site, @main. I've tested this outside of cron and the command `drush @main elysia-cron` runs cron, although only once an hour (see this problem). This cron runs every five minutes so it should work once an hour.

I also tried the format in the docs above:

```
*/5 * * * * /usr/bin/env PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin COLUMNS=80 /usr/bin/drush @main elysia-cron

```

# Answer
> 3 votes
It would probably be easier to use `--root` and `--uri` instead of `@main`. Drush loads aliases on a per-user basis; the user you are testing `drush @main elysia-cron` probably has the `@main` alias defined in an alias file in `~/.drush`. You'd need to either move your aliases to a global location, or perhaps copy your alias file to the www-data user's `.drush` folder.

# Answer
> 0 votes
I copied my aliases drush folder from `~/.drush` to `/var/www` the home of the default server user: `www-data`.

The command in Ubuntu I used was:

```
cp -r ~/.drush /var/www

```

# Answer
> 0 votes
```
drush --root=/var/your website/ elysia-cron

```

# Answer
> 0 votes
Just make bash script /var/www/scripts/elysia\_cron.sh

```
cd /var/www #put your path to the document root which add centext
/usr/bin/drush elysia-cron

```

and start this script on cron

```
*/5 * * * * /var/www/scripts/elysia_cron.sh

```

---
Tags: 7, drush, cron
---