title: Session ID same across browsers

text:
# Question
Title: Session ID same across browsers
I know that it's impossible for the sessions IDs to be the same across multiple browsers, but Drupal is acting really weird with sessions and I've been stuck with this issue for over a week now. Let me explain what the issue is.

I'm building a custom login page (A custom form that connects to an external database for authentication). If the credentials are correct, I'm setting a session variable and redirecting the user to a landing page that only successfully authenticated users can see. I'm setting the session variable to the user's id and checking that to see if the user is logged in or not.

So: 1. If the user tries to access the login page and a session already exists, user is redirected to the logged in page. If it doesn't, log in form is shown. 2. If the user tries to access the logged in page and a session doesn't exist, user is redirected back to the log in page. If session exists, the landing page is shown.

ISSUE #1: Now for some weird reason, after I login, the session ID generated on the landing page (after logging in) seems to be the same across all my browsers (I've tried Firefox, Chrome and even a live remote website testing service). Even if a new session ID is generated on the login page, whenever I'm redirected to the landing page, it has the same old session ID from before when I logged in on another device.

ISSUE #2: Sessions were acting pretty weird earlier too. For example, the session ID generated even on the login page would sometimes be the same across browsers. But this is not as consistent as the issue with the landing page. Also, this session ID is never carried over to the landing page. The session IDs of the login form and the landing page are always different.

ISSUE #3: Earlier, I was also facing the issue where I couldn't read the session variable on the login page to check if the user is already logged in. Even after a successful log in, whenever I came back to the form, it would still display the form. The session variable did not have the value I stored earlier. But if I go the landing page, the session would exist there and not redirect me back to the form.

This is very strange for what should be a straightforward implementation. For my implementation, I've created a controller which handles 2 routes - login and landing page. The login controller embeds the custom form. I've handled redirection in the submitForm handler and in the controllers. Here's my code:

Controller code:

```
namespace Drupal\igshpa_members\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Session\SessionManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\user\PrivateTempStoreFactory;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Session\SessionManager;

class MembersController extends ControllerBase {

  /**
   * Drupal\user\PrivateTempStoreFactory definition.
   *
   * @var Drupal\user\PrivateTempStoreFactory
   */
  protected $userPrivateTempstore;

  /**
   * Drupal\Core\Session\SessionManager definition.
   *
   * @var Drupal\Core\Session\SessionManager
   */
  protected $sessionManager;

  /**
   * Drupal\Core\Session\AccountInterface definition.
   *
   * @var Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;

  // {@inheritdoc}
  public function __construct(
      PrivateTempStoreFactory $user_private_tempstore,
      SessionManager $session_manager,
      AccountInterface $current_user) {
    $this->sessionManager = $session_manager;
    $this->currentUser = $current_user;
    $this->userPrivateTempstore = $user_private_tempstore->get('igshpa_members');
  }

  // {@inheritdoc}
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('user.private_tempstore'),
      $container->get('session_manager'),
      $container->get('current_user')
    );
  }

  public function content() {

    if (!isset($_SESSION['session_started'])) {
      $_SESSION['session_started'] = TRUE;
      $this->sessionManager->start();
    }
    $userId = $this->userPrivateTempstore->get('igshpaId');

    if(!is_null($userId)) {
      $sessId = session_id();
      return array(
        '#theme' => 'members_portal',
        '#test_var' => $this->t($sessId),
      );
    } else {
      return $this->redirect('igshpa_members.igshpa_login');
    }
  }

  public function login() {

    if (!isset($_SESSION['session_started'])) {
      $_SESSION['session_started'] = TRUE;
      $this->sessionManager->start();
    }
    $userId = $this->userPrivateTempstore->get('igshpaId');

    if(!is_null($userId)) {
      return $this->redirect('igshpa_members.members_portal');
    } else {
      $sessId = session_id();
      $form_class = '\Drupal\igshpa_members\Form\IGSHPALogin';
      $form = \Drupal::formBuilder()->getForm($form_class);
      return array(
        '#theme' => 'igshpa_login',
        '#form' => $form,
        '#debug' => $sessId
      );
    }
  }
}

```

Form code:

```
namespace Drupal\igshpa_members\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Database\Database;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\user\PrivateTempStoreFactory;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Session\SessionManager;

/**
 * Implements an example form.
 */
class IGSHPALogin extends FormBase {

  /**
   * Drupal\user\PrivateTempStoreFactory definition.
   *
   * @var Drupal\user\PrivateTempStoreFactory
   */
  protected $userPrivateTempstore;

  /**
   * Drupal\Core\Session\SessionManager definition.
   *
   * @var Drupal\Core\Session\SessionManager
   */
  protected $sessionManager;

  /**
   * Drupal\Core\Session\AccountInterface definition.
   *
   * @var Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;

  // {@inheritdoc}
  public function __construct(
      PrivateTempStoreFactory $user_private_tempstore,
      SessionManager $session_manager,
      AccountInterface $current_user) {
    $this->sessionManager = $session_manager;
    $this->currentUser = $current_user;
    $this->userPrivateTempstore = $user_private_tempstore->get('igshpa_members');
  }

  // {@inheritdoc}
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('user.private_tempstore'),
      $container->get('session_manager'),
      $container->get('current_user')
    );
  }
  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'igshpa_login_form';
  }

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

    $form['username'] = array(
      '#type' => 'textfield',
      '#title' => $this->t('Username'),
      '#required' => true,
    );
    $form['password'] = array(
      '#type' => 'password',
      '#title' => $this->t('Password'),
      '#required' => true,
    );
    $form['actions']['#type'] = 'actions';
    $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => $this->t('Log in'),
      '#button_type' => 'primary',
    );
    $form['actions']['submit']['#attributes']['class'][] = 'btn-all';
    $form['#cache']['max-age'] = 0;
    $form['#cache']['contexts'][] = 'session';
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    // Validate the information
    // Remember to handle required, text length, format etc
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Receive username and password
    // search db for entry
    // If present, set session to user id | session!!!
    // redirect to user profile page | redirect!!!
    $username = $form_state->getValue('username');
    $password = $form_state->getValue('password');

    $con = Database::getConnection('default','igshpa');
    // I've removed the actual query for security purposes:
    $query = $con->query('SELECT ....');

    $result = $query->fetchAll();

    if (sizeof($result) == 1) {
      if (!isset($_SESSION['session_started'])) {
        $_SESSION['session_started'] = TRUE;
        $this->sessionManager->start();
      }
      $userId = $this->userPrivateTempstore->set('igshpaId',$result[0]->person_id);
      $form_state->setRedirect('igshpa_members.members_portal');
      return;
    } else {
      drupal_set_message($this->t('Wrong username or password. Try again.'), 'error');
      return;
    }
  }

}

```

# Answer
> 1 votes
The session id of a request from a browser with no session cookie is always the same, because the session you see in Drupal at this point is not real. Drupal waits until the response is finished to start a session when there is new session data to store. This lazy behavior is to prevent generating sessions that are never used. Usually you don't interfere with that by using the session manager. You simply store and retrieve data in the session and do so as if a session is started (and don't think about it that it is not real). That's the reason why the private tempstore is very difficult to use for anonymous traffic and you normally don't need it. All you need is to store the user id in the session `$session->set('igshpaId', $result[0]->person_id);`. So the form submit could be like this:

```
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Receive username and password
    // search db for entry
    // If present, set session to user id | session!!!
    // redirect to user profile page | redirect!!!
    $username = $form_state->getValue('username');
    $password = $form_state->getValue('password');
    $con = Database::getConnection('default','igshpa');
    // I've removed the actual query for security purposes:
    $query = $con->query('SELECT ....');
    $result = $query->fetchAll();

    if (sizeof($result) == 1) {
      $session = $this->requestStack->getCurrentRequest()->getSession();
      $session->set('igshpaId', $result[0]->person_id);
      $form_state->setRedirect('igshpa_members.members_portal');
      return;
    }
    else {
      drupal_set_message($this->t('Wrong username or password. Try again.'), 'error');
      return;
    }
  }

```

And then in the controller

```
use Symfony\Component\HttpFoundation\Request;

...

  public function content(Request $request) {
    $session = $request->getSession();
    $userId = $session-get('igshpaId');
    ...
  }

```

If you have a route callback like a controller you can get the request directly from the route arguments. So no need to inject any services.

---
Tags: 8, forms, sessions
---


title: Change domain based on location

text:
# Question
Title: Change domain based on location
I want to create one website for multi-countries and each country's website content should be different according to the selection. But the file and database should be single. For example, For Singapore version: example.com/sg/ For Honk kong version: example.com/hk/ The website is redirected based on the user location and can also be switched manually. When a user from Singapore enters the url it first redirects to the example.com/sg/. There should also be an option to switch the domain manually by the user. If user selects Honk Kong manually the website is redirected to example.com/hk/. How is this possible?

# Answer
> 0 votes
U can take client ip and then use some library like Geocoder to create redirection based on country.

---
Tags: 7, multi-sites, uri
---


title: hook_view, hook_theme and Display suite

text:
# Question
Title: hook_view, hook_theme and Display suite
My module adds further content to a specific node bundle, in the "view" phase, in the following way:

* `hook_view` (under the right conditions) adds these "contents" to the node `display` array
* `hook_theme` specifies how to render the possible render\_array related to the added contents

I followed several tutorials about, and in effect the documentation (of the latter) reports:

> The structure of $node-\>content is a renderable array as expected by drupal\_render().

Here is an abstract from my code:

```
/**
 * Implements hook_view().
 * Remember: hook prefix is based on the base of the node type (node-type-specific hook)
 */
function mynode_view($node, $view_mode) {
  $contentWrapper = entity_metadata_wrapper('node', $node);
  $myfield = $contentWrapper->myfield->value();
  if ($view_mode=="full") {
    $node->content["ds_column"] = array(
      '#markup' => theme('ds_column', array(
        'element' => _mymodule_to_render_arrays($myfield, $node->status),
        )),
      '#weight' => 150,
    );
  }
  return $node;
}

```

As you can see this adds the `ds_column` to my node content, telling me it has to be rendered by a theme function. It also passes to the theme function a "render array" (containing the information to be rendered).

```
/**
 * Implements hook_theme().
 */
function mymodule_theme($existing, $type, $theme, $path) {
  return array(
    'ds_column' => array(
      // See http://drupal.org/node/224333#theme_changes
      'variables' => array('element' => NULL),
      'template' => 'theme/ds_column'
    ),
  );
  return $theme;
}

```

This part of my module explain what template file have to be used in order to properly render, in the node (bundle) page, the content I added by the previous hook.

For what I see this is the standard approach. And indeed everything works fine.

The problem description starts here.

The module I described has been installed on an environment using the Display Suite module to define how to show contents for each node type in the node page, but the Display Suite module doesn't allow to see, in the configuration page, the content I added with the code shown above. So now that content doesn't appear in the node page.

I would like just to see the "ds\_column" in the Display Suite configuration page for that specific node, in order to place it properly.

I can't figure how to see it (have I to implement also a DS hook? Have I to modify my code in some way?). I just found the "Display Suite Extra" sub-module, but I wasn't able to solve by it.

# Answer
> 0 votes
For people interested to the solution, you have to use the `hook_field_extra_field()` hook.

There you can declare your own "virtual fields" and they will appear as fields also in the Display Suite.

To link them to the content you create, just be sure to use the same name as a key both in the field name and in what you add as a node-\>content.

To provide you with the solution related to my example:

```
/**
 * Implements hook_field_extra_fields().
 */
function mymodule_field_extra_fields() {
  $extra['node']['my_custom_bundle_type']['display'] = array(
      'ds_column' => array(
        'label' => t('My column'),
        'description' => t('Description is also mandatory'),
        'weight' => 99,
      ),
  );
  return $extra;
}

```

As you can see ther key `ds_column` is the same used in the `mynode_view` (or in any other function implementing a hook able to modify the `content` render array).

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


title: Field Widget Ajax

text:
# Question
Title: Field Widget Ajax
I'm trying to add an ajax callback in a FieldWidget. I definied my element:

```
$element['value']['#ajax'] = [
  'callback' => [$this, 'ajaxRefreshField'],
];

```

Next in my callback, how do I access the form\_state value filled out in the field and the element defined on the form?

```
    public function ajaxRefreshField(array $form, FormStateInterface $form_state, Request $request) {
      // What I want to do is something like this:
      $response = new AjaxResponse();
      $element = $form->get-my-element-in-some-sort-of-way
      $element['add-a-change'] = [...];
      $response->addCommand(new ReplaceCommand('my-selector', $element));

      return $response;
    }

```

# Answer
Grab the triggering element from the `$form_state` in your AJAX callback method:

```
$triggeringElement = $form_state->getTriggeringElement();
$value = $triggeringElement['#value'];

```
> 1 votes

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


# Question
Title: Enable/open comments on all posts of a content type
When I created a content type, I chose to keep the Comments hidden. Now I have many posts of that content-type and I want to open the comments, which I did by editing the content type, but it did not open comments of any posts of that content-type.

How do I open comments on all the posts of a content type at once?

How do I remove that little help box under comments text area?

# Answer
> 4 votes
You'll have to edit your existing content and open the comments manually. If you have a lot of content you can probably do it directly in the database.

To remove the "help box" you can change the text format to "plain text" for the "comment body" field. If you want to keep the HTML option you can use a `hook_form_alter()` function to remove the text.

Better Formats Module might also do the trick.

# Answer
> 5 votes
Or directly into the database with :

```
UPDATE `node`
SET comment = 2
WHERE comment = 1

```

and

```
UPDATE `node_revision`
SET comment = 2
WHERE comment = 1

```

Where : Whether comments are allowed on this node: 0 = no, 1 = closed (read only), 2 = open (read/write).

# Answer
> 4 votes
To enable comments you should use Views Bulk Operations. It allows you to define operations to be executed against any view result.

You have to write a custom Rules action, but it will definitely be worth your time.

# Answer
> 1 votes
In Drupal 7, you can run following code using Devel Module

```
$num_updated = db_update('node_revision')
  ->fields(array(
    'comment' => 2,
  ))
  ->condition('comment',1)
  ->execute();

echo "node revision table updated count: ".$num_updated ."," ;

$num_updated = db_update('node')
  ->fields(array(
    'comment' => 2,

  ))
  ->condition('comment',1)
  ->execute();

echo "node table updated count: ".$num_updated ;

```

# Answer
> 1 votes
For Drupal 7, you need to enable comments in both node and node\_revision tables. Use this query `UPDATE node as n LEFT JOIN node_revision as nr ON nr.nid=n.nid AND nr.vid=n.vid
SET n.comment = 2, nr.comment = 2 WHERE n.type = 'article'.`

# Answer
> 1 votes
Adding node\_type condition as following:

```
db_update("node")
->fields(array(
  'comment' => 2,
  ))
->condition("type", "node_type", "=")
->execute();

```

I can run the above with `drush scr filename.php`

Alternatively I could update with SQL query:

```
UPDATE node as n LEFT JOIN node_revision as nr ON nr.nid=n.nid AND nr.vid=n.vid
SET n.comment = 2, nr.comment = 2 WHERE n.type = 'notes';

```

# Answer
> 0 votes
Very easy to update comment for drupal node

simply run two query

1. in node table

```
UPDATE 'node' SET 'comment' = '2' WHERE TYPE = ''

```
2. ```
UPDATE node_revision  SET `comment` = '2' WHERE  nid in(select nid from node where type='rss_feed')

```

should be update in both table revision and node.

# Answer
> 0 votes
Just Run this Query in devel/php environment to enable comments for all existing content.

```

$num_updated = db_update('node')
->fields(array(
  'comment' => 2,
))
  ->condition('type', 'CONTENT_TYPE', '=')
  ->execute();

```

```

$subquery = db_select('node');
$subquery->addField('node', 'nid');
$subquery->condition('node.type', 'CONTENT_TYPE', '=');
$num_updated1 = db_update('node_revision')
  ->fields(array('comment' => '2',))
  ->condition ('node_revision.nid', $subquery, 'IN')
  ->execute();

```

---
Tags: comments
---


title: Custom module is not working

text:
# Question
Title: Custom module is not working
I created custom module to display `Hello world` text in custom page. I did not install **drush** and **composer** in my windows machine as I don't have admin access. I have pasted my files below:

**example.module**

```
<?php

function example_menu()
{
  // The paths given here need to match the ones in example.routing.yml exactly.
  $items['/mypage/page'] = array(
    'title' => 'First page',
    'description' => 'This is a example page.',
    // The name of the route from example.routing.yml
    'route' => 'example.my_page',
  );
  return $items;
}

```

**example.routing**

```
example.my_page:
  path: '/mypage/page'
  defaults:
    _controller: '\Drupal\example\Controller\ExampleController::mypage'
    _title: 'Hello world'
  requirements:
    _permission: 'access content'

```

**src/Controller/ExampleController.php**

```
<?php

namespace Drupal\example\Controller;

//use Drupal\Core\Controller\ControllerBase;

class ExampleController
{
    public function myPage()
    {
        $element = array('#markup' => 'Hello world!');
        return $element;
    }
}

```

And I have **example.info** file as well and the module is enabled. When I run the controller, it says `page not found`. Can anyone tell me that Am I missed anything in the code?

# Answer
> -2 votes
`hook_menu` doesn't exist anymore in D8. Instead use a **example.links.menu.yml** file.

```
example.my_page:
  title: 'First page'
  description: 'yout description'
  route_name: example.my_page

```

---
Tags: routes
---


title: Add Publishing options to custom entity

text:
# Question
Title: Add Publishing options to custom entity
How do you add publishing options to a custom entity or it's bundles? Currently when I create a new Entity entry I only have a save option. I would like to add published and unpublished states.

# Answer
In 8.3 there is now an interface for this:

> Content entities that need a published/unpublished flag base field are now able to declare a "published" entity key in their entity type annotation. Such entities should implement the new \Drupal\Core\Entity\EntityPublishedInterface and use the \Drupal\Core\Entity\EntityPublishedTrait trait. The interface can be implemented directly, by the entity class, or by the entity specialised interface.
>
> ```
> use Drupal\Core\Entity\EntityPublishedInterface;
> use Drupal\Core\Entity\EntityPublishedTrait;
> use ...
>
> /**
>  * @ContentEntityType(
>  *   id = "custom_entity",
>  *   ...
>  *   entity_keys = {
>  *     "id" = "id",
>  *     "published" = "status",
>  *     "label" = "label",
>  *   },
>  *   ...
>  * )
>  */
> class CustomEntity extends ContentEntityBase implements CustomEntityInterface, EntityPublishedInterface {
>   use EntityPublishedTrait;
>    ...
> }
>
> ```
>
> Entities defined in this way can benefit of the new provided methods to set the published status ON/OFF and are able to inspect the status of the published flag field:
>
> ```
> $storage = \Drupal::entityTypeManager()->getStorage('custom_entity');
> $entity = $storage->load(123);
>
> // Reverse the published status.
> if ($entity->isPublished()) {
>   $entity->setUnpublished();
> }
> else {
>   $entity->setPublished();
> }
>
> $entity->save()
>
> ```

Source: https://www.drupal.org/node/2830201

If you are developing for 8.4 you can use the base class

> **EditorialContentEntityBase - a new base entity class for revisionable and publishable entity types**
>
> Drupal 8.4.0 increases its usage of the revisioning and publishing features from Entity API by converting some if its most widely used content entity types: Taxonomy terms, Menu links, Comments, etc.
>
> In order to reduce code duplication and boilerplate, a new content entity base class is now available for entity types that want to support those features by default: EditorialContentEntityBase.
>
> If you are defining a content entity type in a contributed module or in your project's custom code, it is recommended to extend the \Drupal\Core\Entity\EditorialContentEntityBase base class in order to get out-of-the-box support for Entity API's revisioning and publishing features, which will allow your entity type to be used with Drupal's editorial workflow provided by the Content Moderation module.

Source: https://www.drupal.org/node/2870643
> 3 votes

---
Tags: entities
---


# Question
Title: How to create new markers into a Google map with click?
I want to add a marker on click event and add it into exact location where user clicked on map.

Can't use any of the official examples which eventually return nothing.

My current module specific js code is as follows (just trying to build it step by step):

```
(function ($) {
  Drupal.behaviors.gmapPage = {
    attach: function(context, settings) {

      // Get map object / instance
      var map = Drupal.gmap.getMap($('.gmap-gmap').attr('id'));

      // Is this available in some other way?
      console.log(map); // Prints Drupal.gmap.map, but map != Drupal.gmap.map

      google.maps.event.addListener(map, 'click', function (e) {
        console.log(e.latLng);
      });

    }
  };
})(jQuery);

```

Everything else is fine but cannot create any functionality for the map. Such an easy development task which seems so unbelievably challenging...

And this is purely for the front-end /ui - this question isn't about how to save location, load them into map etc. back-end related.

UPDATE:

I've added following script just for testing purposes:

```
(function ($) {
    Drupal.behaviors.gmapPage = {
        attach: function(context, settings) {

          // Get map object / instance
          var map = Drupal.gmap.getMap(settings.gmap.auto2map.id);
          // Following works although e is undefined
          // if 'ready' is changed to 'click' nothing happens
          map.bind('ready', function (e){
                console.log(e, 'map is ready');
          });

       }
    };
})(jQuery);

```

# Answer
Well, after a one days work I figured it out. Perhaps this could have been explained by Google maps module developer in 5 minutes and/or with a clear documentation.

Following script solved it:

```
(function ($) {
Drupal.behaviors.gmapPage = {
    attach: function(context, settings) {
         // Get "some" map object: Drupal.gmap.getMap(settings.gmap.[id/key provided by module you use].id)
         var map = Drupal.gmap.getMap(settings.gmap.auto2map.id);
         // Bind it with ready function; did not work without it
         map.bind('ready', function(){
            // Now you can have the real map instance
            gMapInit = Drupal.gmap.getMap(settings.gmap.auto2map.id).map;
            // And no - it doesn't work if you change it in the beginning
            // e.g. var map = Drupal.gmap.getMap(settings.gmap.auto2map.id).map;
         });
      }
    };
})(jQuery);

```

I've got to admit that this is rather pointless work to do since everything could be documented. Especially this kind of starting point developer documentation should be available.
> 1 votes

# Answer
This is working example at my side please check here Demo

```
function initCentraDistrictmap()
{
var mapOptions = {
zoom: 12,
center: new google.maps.LatLng(1.3050618171691895, 103.8240737915039),
mapTypeId: 'roadmap'
 };
    map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);

google.maps.event.addListener(map, "click", function (event) {

var myLatLng = new google.maps.LatLng(event.latLng.lat(),event.latLng.lng());
var image = 'data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%2246%22%20height%3D%2244%22%3E%0A%3Ccircle%20cx%3D%2223%22%20cy%3D%2222%22%20r%3D%2220%22%20stroke%3D%22%23000%22%20stroke-width%3D%222%22%20fill%3D%22%23ff3019%22/%3E%0A%3Ctext%20transform%3D%22translate%2823%2025%29%22%20fill%3D%22%23fff%22%20style%3D%22font-family%3A%20Arial%2C%20sans-serif%3Bfont-weight%3Abold%3Btext-align%3Acenter%3B%22%20font-size%3D%2212%22%20text-anchor%3D%22middle%22%3ETesting%3C/text%3E%0A%3C/svg%3E';
var marker = new google.maps.Marker({
      position: myLatLng,
      map: map,
      icon: image// baseURL + 'assets/drawsvg.svg'
  });
});
}
 $(document).ready(function(){
  initCentraDistrictmap();
 })

```
> 1 votes

---
Tags: javascript, google-maps
---


# Question
Title: How to export custom user fields configuration?
I'm developing a module and it needs some custom fields on the users table.

If I export the whole config yml zip, the field.field.xxx and field.storage.xxx files for my custom fields are there, but since "users" isn't a custom content type of my module, those fields are not added to the users table during module installation.

How do I add those fields to the users table during module installation?

# Answer
Modules can add in the config/optional directory any configuration file for fields or entities. For example, the *Forum module* uses the config/optional directory to define a new content type and its fields, but it could have as well defined fields for a content type defined from another module. Keep in mind that in this case, the module need to define an explicit dependency from the other in the configuration file for the field.

For an example of using the config/install directory for defining new bundles and its fields, see the config/install directory used from the *Standard* profile.
> 0 votes

---
Tags: users
---


# Question
Title: How to add captcha to "Printer, e-mail and PDF versions" email form
I am using the Printer, e-mail and PDF versions module to enable user to share pages on my d6 website. Now I have recently noticed that some robots make thousands of requests on this form a nd I need a captcha to prevent it. How can I do that?

Thanks

# Answer
I just added my send form ID to the CAPTCHA form list, and it worked fine.
> 0 votes

# Answer
The correct ID for that is **print\_mail\_form**. The HTML has:

```
 id="print-mail-form"

```

but you must change - to _ to get the internal ID.
> 0 votes

---
Tags: 6, captcha
---


# Question
Title: EntityFieldQuery with fieldCondition returns nothing
I have created a custom entity, called 'point'.

I'm able to get all of the entities in the db, with this:

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'point')
    ->entityCondition('bundle', 'point');
$result = $query->execute();

```

But when I add a fieldCondition, to make sure I only get the one single entity I want, I'll get an empty array back.

It looks like this:

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'point')
    ->entityCondition('bundle', 'point')
    ->fieldCondition('field_point_unique_number', 'value', $unique_number, '=');
$result = $query->execute();

```

Where $unique\_number is a textstring. And it's not a typo in the textstring. In the db the field 'field\_point\_unique\_number' is a varchar, but only contains numbers.

Why does the fieldCondition return nothing?

# Answer
I hadn't checked it for trailing spaces. So using trim() on $unique\_number did the trick. Thanks for leading me the right way Clive!
> -1 votes

---
Tags: entities
---


# Question
Title: How to render taxonomy in page template?
I'm trying to show all taxonomy terms in a custom template (`page--project.tpl.php`) that overrides `page.tpl.php`, but I can't pull it off.

I'd like to use the default rendering that I get when I see with `render($page['content'])`:

>

It seems like I should be able to use `render($node->field_project_tags)`, but I get a bunch of drupal errors on the rendered template page:

```
Warning: Invalid argument supplied for foreach() in element_children() (line 6590 of /Users/username/sites/d7/includes/common.inc).
Warning: Illegal string offset '#children' in drupal_render() (line 6047 of /Users/username/sites/d7/includes/common.inc).
Warning: Illegal string offset '#children' in drupal_render() (line 6057 of /Users/username/sites/d7/includes/common.inc).
...

```

What's the cleanest, simplest way to render these taxonomy terms (as links) in a page template?

# Answer
You can display taxonomy terms in sidebar in multiple methods.

1. Create a view block with required taxonomy terms and assign that block to any region in required pages.
2. Create a normal block, load and display taxonomy terms using following code and assign that block to any region in required pages.

```
$vocabulary = taxonomy_vocabulary_machine_name_load('vocobulary_name');
if ($terms = taxonomy_get_tree($vocabulary->vid)) {
  foreach ($terms as $term) {
    $term_name = $term->name;
    // Do required actions.
  }
}

```
3. Use the above code in your page template to display taxonomy terms.

Hope this will helps you.
> 0 votes

# Answer
Use following code to display manually taxonomy terms:

```
$vocabulary = taxonomy_vocabulary_machine_name_load('vocobulary_name');
if ($terms = taxonomy_get_tree($vocabulary->vid)) {
  $tags ='';
  foreach ($terms as $term) {
      $taxonomy_path = taxonomy_term_uri($term);
      $tags .= l($term->name, $taxonomy_path['path']);
  }
}

```
> 1 votes

# Answer
Jeetendra Kumar gave the correct answer but You should never ever ever do it in a template, especially in Drupal7 since there is a serious performance hit.

As googletorp mentioned the right way would be to create a custom block that will display Your taxonomies. You should never do such within a template!

Create a custom block with hook\_block\_info and hook\_block\_view, and paste the Kumar's code there.

Than You can place that block where it fits Your needs via block management or programmatically.
> 0 votes

---
Tags: 7, theming, taxonomy-terms
---


# Question
Title: Generate reports of similar web forms results
In Drupal 7, I want to generate a report of similar webforms (same fields but created 2 webforms to handle multilingual translations) results. All the fields in my both webforms are same. I tried to use Views to fetch the results of both webforms, which is not working.

Any idea on how to achieve this?

I did this to get the filename of teh fid saved in webform\_submitted\_data table.

Added SQL:

```
SELECT wsd.nid, wsd.sid, fm.filename,
       MAX(CASE WHEN wsd.cid = 2 THEN wsd.data END) fn,
       MAX(CASE WHEN wsd.cid = 3 THEN wsd.data END) ln,
       MAX(CASE WHEN wsd.cid = 4 THEN wsd.data END) email,
       MAX(CASE WHEN wsd.cid = 5 THEN wsd.data END) ph,
       MAX(CASE WHEN wsd.cid = 6 THEN wsd.data END) tr,
       MAX(CASE WHEN wsd.cid = 7 THEN wsd.data END) upr,
       MAX(CASE WHEN wsd.cid = 9 THEN wsd.data END) coc
  FROM webform_submitted_data wsd LEFT JOIN file_managed fm ON wsd.data = fm.fid WHERE nid IN(66,67) GROUP BY wsd.sid;

```

# Answer
If Views can't do what you're trying to do, you might want to consider the Forena module (disclosure: I'm a co-maintainer) as a possible alternative.

As an example, create a custom "data block" (which is just an SQL statement) that fits your needs, to retrieve the webform data that you're interested in. Here is a (basic) example:

```
SELECT s.nid AS node, s.sid AS submission, d.cid AS component, d.data AS fieldvalue
FROM {webform_submissions} s JOIN {webform_submitted_data} d ON s.sid=d.sid
WHERE d.cid=3 AND s.nid=5
ORDER BY s.sid ASC

```

Then create a Forena "report" that uses this data block (maybe you want to enable something like the "CSV" option, within "document types"). Here is the (basic) layout of such report to illustrate the idea:

```
<body>
<div id="webform_submissions_data_block" class="FrxTable" frx:block="drupal_cust/webform_submissions_data">
    <table>
      <thead>
        <tr>
          <th>node</th>
          <th>submission</th>
          <th>component</th>
          <th>fieldvalue</th>
        </tr>
      </thead>
      <tbody>
        <tr id="webform_submissions_data" frx:foreach="*">
          <td>{node}</td>
          <td>{submission}</td>
          <td>{component}</td>
          <td>{fieldvalue}</td></tr>
      </tbody>
    </table>
  </div>
</body>

```

After you saved the report specifications and then browse the generated report, you could have a "CSV"-hyperlink (upper right of the report). Just use that link and ... voilà, there is your CSV file (in this case with 4 columns, since that is what in my (basic) report I asked for).

If this makes sense, head of to the Community documentation of Forena to get you going (which includes pointers to video tutorials). Or use the documentation that comes with Forena.

Of course, building the appropriate SQL statement to perfectly fit your needs is going to be crucial. But apart from that, it's just basic usage of Forena.

**Update**

To "*create a temporary table*" (as in your comment below this answer, and also per your updated question), you may want to have a look at what's suggested (by David Metzler) in this feature request. Though I personally have no experience with using Forena to create such temporary tables.

Reminder: Forena is to *query* data (as in your first version of your question), not to update, delete, etc such data.
> 3 votes

---
Tags: 7, views, webforms, log-messages
---


# Question
Title: Disable the checkbox and select list using element_children
Hi I am trying to disable all the form elements of the form. I am using this code to disable the form .

```
foreach (element_children($form) as $key) {
  $form[$key]['#disabled'] = TRUE;
    $form['#attributes'] = array('disabled' => TRUE);
    }
    drupal_set_message("Website is currently in read only mode. During this it is not possible to change site content", "warning");
}

```

It is working for textbox, radios and submit button but not for the select list and checkbox. What shall I do?

# Answer
In a word: recurse.

```
function _disable_self_and_descendants(&$el) {
  $el['#disabled'] = TRUE;

  foreach (element_children($el) as $key) {
    _disable_self_and_descendants($el[$key]);
  }
}

_disable_self_and_descendants($form);

```
> 0 votes

---
Tags: 7
---


# Question
Title: Handle database connection exception via custom handler
I want to catch the database connection exceptions with a custom handler. I have already built an handler which is overriding the default logger factory, but now I want to use that custom handler to log database exceptions, without hacking the core.

I can see the connection driver uses the following code in `open()`.

```
try {
  $pdo = new \PDO($dsn, $connection_options['username'], $connection_options['password'], $connection_options['pdo']);
}
catch (\PDOException $e) {
  if ($e->getCode() == static::DATABASE_NOT_FOUND) {
    throw new DatabaseNotFoundException($e->getMessage(), $e->getCode(), $e);
  }
  if ($e->getCode() == static::ACCESS_DENIED) {
    throw new DatabaseAccessDeniedException($e->getMessage(), $e->getCode(), $e);
  }
  throw $e;
}

```

I am not sure how I can catch the exception and log it using the handler. How can I achieve this?

# Answer
> 8 votes
To handle the logging for a specific exception implement an exception subscriber with a priority higher than 50, so that it runs before `Drupal\Core\EventSubscriber\ExceptionLoggingSubscriber`:

*src/EventSubscriber/ExampleExceptionSubscriber*

```
namespace Drupal\mymodule\EventSubscriber;

use Drupal\Core\Database\DatabaseAccessDeniedException;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\KernelEvents;

/**
 * Example for catching a DatabaseAccessDeniedException
 */
class ExampleExceptionSubscriber implements EventSubscriberInterface {

  /**
   * @var \Drupal\Core\Logger\LoggerChannelFactoryInterface
   */
  protected $logger;

  public function __construct(LoggerChannelFactoryInterface $logger) {
    $this->logger = $logger;
  }

  public function onException(GetResponseForExceptionEvent $event) {
    $exception = $event->getException();
    if ($exception instanceof DatabaseAccessDeniedException) {
      $this->logger->get('php')->error('Custom logging message');
      $response = new Response('Custom error message', 500);
      $event->setResponse($response);
    }
  }

  public static function getSubscribedEvents() {
    $events[KernelEvents::EXCEPTION][] = ['onException', 60];
    return $events;
  }
}

```

*mymodule.services.yml*

```
services:
  mymodule.exception.subscriber:
    class: Drupal\mymodule\EventSubscriber\ExampleExceptionSubscriber
    arguments: ['@logger.factory']
    tags:
      - { name: event_subscriber }

```

If you don't set a response this subscriber only logs the error and the response is set by a subscriber with a lower priority. In this case you get two log entries, one from your subscriber and one from `ExceptionLoggingSubscriber`, because the dispatcher runs the event subscribers until one returns a response. Logging does not stop this.

Another option would be to extend ExceptionLoggingSubscriber, put the custom code in ExceptionLoggingSubscriber::onException and call the parent method to run standard logging when your custom code doesn't apply. Instead of putting the service in mymodule.services.yml you need to swap the existing service in the container then, see https://www.drupal.org/docs/8/api/services-and-dependency-injection/altering-existing-services-providing-dynamic-services

You find more infos about exception handling here How do handle exceptions?

---
Tags: 8
---


# Question
Title: Using custom .tpl.php for fieldable panel pane view mode
I'm having a difficult time getting a view mode on an FPP to use my custom .tpl.php file.

Here is `hook_preprocess`:

```
function mymod_preprocess(&$variables, $hook) {
  $element = $variables['elements'];
  if ($element['#entity_type'] == 'fieldable_panels_pane') {
    $entity_type = $element['#entity_type'];
    $bundle = $element['#bundle'];
    $view_mode = $element['#view_mode'];
    $variables['theme_hook_suggestions'][] = "{$entity_type}__{$bundle}__{$view_mode}";
    $variables['theme_hook_suggestions'][] = "fieldable-panels-pane-banner-banner-full-bleed";
    kpr($variables);
  }
}

```

The relevant output of the `kpr()` (the `theme_hook_suggestions` part of it:

```
array(3) {
    [0]=> string(29) "fieldable_panels_pane__banner"
    [1]=> string(48) "fieldable_panels_pane__banner__banner_full_bleed"
    [2]=> string(46) "fieldable-panels-pane-banner-banner-full-bleed" }

```

I hard-coded that last one thinking that it might just be a mishap in the naming conventions. I've tried every combination of dashes and underscores that I can think of; `theme_devel` isn't suggesting any of the ones in `theme_hook_suggestions`, the only ones it recommends are: `panels-pane--fieldable-panels-pane--fpid-4.tpl.php < panels-pane--fieldable-panels-pane.tpl.php`

I have the templates in `/sites/all/modules/custom/mymod/templates` with the module file in `/sites/all/modules/custom/mymod/mymod.module`.

Thanks for any direction!

# Answer
Two dashes for tpls. Your file should be named `fieldable-panels-pane--banner--banner-full-bleed.tpl.php`
> 0 votes

# Answer
I think that your if statement is true for rendering any fields that are a part of the FPP, but not the FPP entity itself. Also, when I try your code, the 'elements' key doesn't seem to be defined when looking for suggestions for the FPP's display mode.

Also, you shouldn't need any handling in hook preprocess. Turn on $conf\['theme\_debug'\] and look at your template suggestions, and create a template file with one of those in your theme. If it's not working, try one of the other name suggestions, you may just need something more specific. For me, this worked for a FPP bundle with the machine name "custom\_markup\_fpp"

ds-1col--fieldable-panels-pane-custom-markup-fpp.tpl.php

Picked from the suggestions:

```
<!-- FILE NAME SUGGESTIONS:
   * ds-1col--fieldable-panels-pane-custom-markup-fpp-full.tpl.php
   x ds-1col--fieldable-panels-pane-custom-markup-fpp.tpl.php
   * ds-1col--fieldable-panels-pane-full.tpl.php
   * ds-1col--fieldable-panels-pane.tpl.php
   * ds-1col.tpl.php
   * fieldable-panels-pane--custom-markup-fpp.tpl.php
   * fieldable-panels-pane.tpl.php
-->

```
> 0 votes

---
Tags: 7, panels
---


title: Debug EntityFieldQuery?

text:
# Question
Title: Debug EntityFieldQuery?
I have a module which is misbehaving. An EFQ is returing unexpected results, but I can't see *why* just by looking at the code. Is there a dpq() equivalent for EFQs? Other ways of debugging them?

# Answer
It's a wee bit of a hack, but you could add a tag to any `EntityFieldQuery` you're interested in printing the query for, then implement `hook_query_alter()` to intercept it when it's a standard `SelectQuery`, then cast it to string for debugging:

```
function MYMODULE_query_alter($query) {
  if ($query->hasTag('efq_debug')) {
    dpm((string)$query);
  }
}

$q = new EntityFieldQuery;
$q->entityCondition('entity_type', 'node')
  ->addTag('efq_debug')
  ->execute();

```

It's a bit of a hack but does the trick. The output for the above is:

```
SELECT node.nid AS entity_id, node.vid AS revision_id, node.type AS bundle, :entity_type
AS entity_type
FROM {node} node

```

Presumably this will also only work when using MySQL as the field storage system.
> 38 votes

# Answer
Rather than rolling your own hook\_query\_alter() you can let Devel module do the heavy lifting for you by adding the `debug` tag:

```
$q = new EntityFieldQuery;
$q->entityCondition('entity_type', 'node');
  ->addTag('debug')
  ->execute();

```

This will print the query to screen, just like `dpq()` would.
> 15 votes

# Answer
Adding to the @Clive answer, which generally prints the query with the placeholder not along with the value. To print the value with the query use the following code under the hook\_query\_alter.

```
function hook_query_alter($query) {
  if ($query->hasTag('debug')) {
    $sql = (string)$query;
    $connection = Database::getConnection();
    foreach ((array) $query->arguments() as $key => $val) {
      $quoted[$key] = $connection->quote($val);
    }
    $sql = strtr($sql, $quoted);
    dpm($sql);
  }
}

$q = new EntityFieldQuery;
$q->entityCondition('entity_type', 'node');
  ->addTag('debug');
  ->execute();

```

It is not good practice to install a module for the few lines of code. That is why I opted for the aforementioned solution.
> 4 votes

# Answer
If you download the dev version of Nice DPQ (or anything =\> 1.1), you can simply do:

```
$user_query = new EntityFieldQuery();
$user_query->entityCondition('entity_type','user');
$user_query->addTag('nicedpq');
$user_result = $user_query->execute();

```

and you will get the query dpm'ed nicely :). The important part in the code above is **addTag('nicedpq')** \- that triggers the `dpm()`.
> 2 votes

# Answer
You can try to debug it via XDebug. Once installed, do `xdebug_start_trace()` before the code, and `xdebug_stop_trace()` after that, then you'll have clear trace log what was executed and where.

Also you can enable query logger in MySQL configuration.

The other method is to use strace/truss/dtruss like debuggers.

Example using dtruss:

* all queries

```
sudo dtruss -t read -n mysqld

```
* specific queries

```
sudo dtruss -t read -n mysqld 2>&1 | grep SPECIFIC_TEXT

```

Note that `dtruss` is just a script which uses DTrace, so you may consider a direct implementation of PHP DTrace static probes or DTracing MySQL by writing your own script.

Read more: Advanced debugging of Drupal core using the command line (strace & tcpdump)
> 1 votes

# Answer
Add this function to your module. Then, add the tag `debug` to any EFQ. Requires Devel module to be enabled in order to print the query.

```
/**
 * Implements hook_query_TAG_alter().
 *
 * Add the tag 'debug' to any EFQ and this will print the query to the messages.
 *
 * @param \QueryAlterableInterface $query
 */
function MYMODULE_query_debug_alter(QueryAlterableInterface $query) {
  if (function_exists('dpq') && !$query->hasTag('debug-semaphore')) {
    $query->addTag('debug-semaphore');
    dpq($query);
  }
}

```
> 0 votes

---
Tags: 7, entities, debugging
---


title: Routing and path aliases

text:
# Question
Title: Routing and path aliases
I have created a module with its routing.yml file.

```
mymodule.dossier:
  path: '/dossiers/{node}/dossier'
  defaults:
    _entity_view: 'node.dossier_dossier'
  requirements:
    _permission: 'access content'

```

I have created a custom view mode (node.dossier\_dossier) and the corresponding Twig template. If I go to dossiers/1/dossier, it works, and it displays the node with the dossier\_dossier view mode and appropriate template.

node/1 has /dossiers/my-custom-path as its path alias, which is automatically set from the Pathauto module. If I try to access /dossiers/my-custom-path/dossier, it returns a *Page not found* error.

How can I make this route work for my nodes for both (default and path aliases) URLs?

**Edit**: I should maybe mention why I need that:

* /dossiers/my-custom-path should display the node using the default view mode
* /dossiers/my-custom-path/dossier should display the node using the dossier\_dossier view mode
* /dossiers/my-custom-path/abstract should display the node using yet another view mode (I'd create another route for that one presumably)

# Answer
> 2 votes
The subpathauto module (depends on pathauto) might help you here: https://www.drupal.org/project/subpathauto

I have a pathauto alias on my site for `/node/{id}` (let's call it `/node-slug`). By installing and enabling the subpathauto module, I was able to create a custom route `/node/{id}/locations` which is now accessible via `/node-slug/locations`

# Answer
> 1 votes
Pathauto can't do this, it can only generate aliases to the default view mode.

You can write your own Pathauto module, which generates for each view mode a separate aliases. For a single purpose module there is not much work to do, you only need to generate the aliases and use

```
\Drupal::service('path.alias_storage')->save($source, $alias);

```

to save them.

The problem is, you get a very large url\_alias table.

Or use `route_callbacks:` in \*.routing.yml, then define in this callback for each view mode a different route, which calls a Controller, which then in case you have a hit on the route will look up the middle part of the alias and return a redirect to the node in the requested view mode. This is without the static alias table, but may take longer for each request.

---
Tags: 8, path-aliases
---


# Question
Title: Add js depend jQuery in a specific content type
I need to add js file with jQuery syntax on a specific content type.

I tried on twig template but I get `jQuery or $ not a function`,

If I have js native syntax only, it is working great but not with jQuery syntax.

I think that this is not the right way to add a js depend jQuery file to a specific page.

I an wondering, What is the right way to do it?

Thanks a lot.

# Answer
Checkout https://www.drupal.org/docs/8/creating-custom-modules/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-module especially section **Attaching a library in a twig template**

See also lib/Drupal/Core/Render/theme.api.php where the library is like $build\['#attached'\]\['library'\]\[\] = 'core/jquery';

```
{{ attach_library('core/jquery') }}

```
> 0 votes

---
Tags: nodes, javascript
---


title: Where does a theme hook come from?

text:
# Question
Title: Where does a theme hook come from?
I know I could use something like hook\_theme\_suggestions\_HOOK\_alter() to add a suggestion, which would allow me to get a template rendered, but I wish someone would explain where the original ones come from in the first place.

For example, in the Twig debugging html, I'm seeing this:

```
<!-- THEME HOOK: 'page' -->

```

...but I don't know where that 'page' hook came from. I can't exactly grep for 'page' in core. Could anyone give me an explanation the order in which these things happen, and how they're connected:

* Something creates a list of possible templates to use (How?)
* Drupal grabs/renders the files specified from this list, from the theme or parent theme
* Something adds new suggestions to existing template names, allowing for specificity
* You can add your own template names to elements, which causes it to look for those files

Even a good direction to look in core would be appreciated.

# Answer
> 3 votes
The hook `page` comes from a hook\_theme implementation in `system.module`:

```
/**
 * Implements hook_theme().
 */
function system_theme() {
  return array_merge(drupal_common_theme(), [
    ...

```

which calls the function `drupal_common_theme()` in `theme.inc`:

```
function drupal_common_theme() {
  return [
    // From theme.inc.
    'html' => [
      'render element' => 'html',
    ],
    'page' => [
      'render element' => 'page',
    ],
    ...

```

The hook name is the top key of the array in hook\_theme. See the documentation in D8 Theme API. The theme suggestions are built in core the same way as in custom code.

---
Tags: theming, 8
---


# Question
Title: Drush set block setting only working for one value
If I disable the powered by block, and use drush to enable it, the block shows back up again. I use:

```
root@vagrant-ubuntu-trusty-64:/var/www/drupal# drush config-get
block.block.bootstrap_powered status
'block.block.bootstrap_powered:status': false

root@vagrant-ubuntu-trusty-64:/var/www/drupal# drush config-set
block.block.bootstrap_powered status true
Do you want to update status key in block.block.bootstrap_powered config? (y/n): y
root@vagrant-ubuntu-trusty-64:/var/www/drupal# drush config-get
block.block.bootstrap_powered status
'block.block.bootstrap_powered:status': true

root@vagrant-ubuntu-trusty-64:/var/www/drupal#

```

However, disabling doesn't work and the block continues to show:

```
root@vagrant-ubuntu-trusty-64:/var/www/drupal# drush config-set
block.block.bootstrap_powered status false
Do you want to update status key in block.block.bootstrap_powered config? (y/n): y
root@vagrant-ubuntu-trusty-64:/var/www/drupal# drush config-get
block.block.bootstrap_powered status
'block.block.bootstrap_powered:status': true

root@vagrant-ubuntu-trusty-64:/var/www/drupal#

```

Thoughts on what I'm doing wrong here? Using Drupal 8.

# Answer
> 0 votes
Ended up having to use:

```
drush config-set block.block.bootstrap_powered status --value=''

```

---
Tags: drush
---


# Question
Title: Which preprocess hook do I use to fire some HTML altering PHP?
I have some PHP that ultimately says 'If this class is present in the HTML, add this string to the $additional\_classes array'. Eg, something similar to:

```
$leftcol_empty = empty($content['leftcol']);
$additional_classes = !$leftcol_empty ? 'medium-8 medium-pull-4' : '';

```

Currently, I've put this at the top of my .tpl file and it works fine. However, I've been told I should move it to the 'theme preprocess function'.

I looked through my theme's template.php file and tried adding it to `my_theme_preprocess_page`, `my_theme_theme` and `my_theme_process_html` but it stopped working.

I've tried Googling for theme preprocesses but haven't found anything that works.

Would anyone know what preprocesses function I can use here?

# Answer
> 1 votes
you can use `theme_preprocess_html(&$variables)` OR `my_module_preprocess_html(&$variables)`

in `$variables` you will see `$variables['classes_array']`

```
if(in_array('class_name', $variables['classes_array'])) {

  //Do your changes

}

```

Hope this will help.

---
Tags: 7, theming
---


# Question
Title: How to add class to individual radio item inside "radios"?
I need to style my radios as tabs. So I created a form element like this:

```
$form['important_categories'] = array (
  '#type' => 'radios',
  '#label' => NULL,
  '#attributes' => array (
    'class' => array (
      'radioTabs',
    ),
  ),
);

foreach ($important_categories as $id_important_category => $important_category_name) {
  $form['important_categories']['#options'][$id_important_category] = $important_category_name;
  if(!isset($form['important_categories']['#default_value'])) {
    $form['important_categories']['#default_value'] = $id_important_category;
  }
}

```

This properly sets options, and sets first element as default. However, it add classes in two places. Here I wanted it:

```
<div id="edit-important-categories" class="form-radios radioTabs">

```

Here I didn't:

```
<input id="edit-important-categories-22" class="radioTabs form-radio" type="radio" value="22" name="important_categories">

```

On individual radio, I need `radioTab` *(singular, not plural)*, and on default one also `radioTabDefault`.

Is there any built-in method to get this? Or do I need to alter my theme, like I did for labels? If so, what function I should modify?

# Answer
No there's nothing built-in for this (take a look at `form_process_radios()`, nothing in there that would let you specify individual classes).

No need to hack core though like in the solution you linked to. Simply implement `hook_element_info_alter()`, and *replace* the process function with your own, which will be based on the original `form_process_radios()`, but that can handle individual classes for options.

```
function MYMODULE_element_info_alter(&$info) {
  // You might want more advanced logic here, to replace instead of override altogether,
  // in case other modules have already altered the core info.
  $info['radios']['#process'] = array('MYMODULE_process_radios');
}

function MYMODULE_process_radios($element) {
  // ...
  return $element;
}

```
> 8 votes

# Answer
This is solution for Drupal 8.

Read the Forms API documentation on the '#after\_build' form element property.

In Form Controller file - Radio button use '#after\_build':

```
$form['myoptions'] = [
  '#type' => 'radios',
  '#title' => t('My Options'),
  '#after_build' => array('custom_process_radios'),
//  ..
];

```

In your .module file code - defining the custom function.

```
/**
 * Processing Radios Element using #after_build property.
 * Adding the class attribute for individual radio button.
 * @element  array
 * @form_state  array
 * @return array
 */
function custom_process_radios($element, $form_state) {
  $options = array_keys($element['#options']);
  foreach($options as $values) {
    $element[$values]['#attributes']['class'][] = 'myclass';
  }
  return $element;
}

```

Read purpose of all the properties for Form Element
> 5 votes

---
Tags: theming, forms
---


title: How access term name by object?

text:
# Question
Title: How access term name by object?
I want to load parent term name by tid .I am using this

```
$term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadParents($tid);
kint($term);

```

This return a object which is my parent term but I am not able to access term name by this object. Please check attached screenshot of kint($term).

# Answer
You should get the name with the getName method. In your case :

```
$term[1]->getName();
$term->getName();

```

If not, you can load the term and after get the name:

```
$term = Term::load($term[1]->id());
$term->getName();

```
> 1 votes

# Answer
```
$term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadParents($tid);
$term_name = $term[key($term)]->getName();

```

jBlobsmith answer is not correct because he is using static term id ($term\[1\]) if parent's term id is 3 than it will not work.You have to change this key manualy in variable ($term\[3\]).
> 1 votes

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


# Question
Title: Twig/Drupal 8 custom cache context not working in node preprocess?
I have a twig template that must be rendered differently on smaller displays (mobile devices) or a larger displays. For example, my breakcrumb is moved to the footer for mobile devices.

In order to check the device type, **i use Mobile Detect module** and **i have created a new cache\_context** named "mobile\_detect". I want to use this cache\_context in my "node--page.html.twig".

Currently the cache context seems to work only when i'm logged in as "super user" but **when i'm not logged in, the node is cached once and the cache context is not used**.

Do you have any ideas why this doesn't work ?

Thanks a lot and Sorry for my bad English :(

My preprocess :

```
function theme_preprocess_node(&$variables)
{
    //mobile detect variable
    $mobileDetector = \Drupal::service('krs.mobile_detect');
    $variables['isMobile'] = $mobileDetector->isMobile();

    //cache context
    $variables['#cache']['contexts'][] = 'mobile_detect';

}

```

My twig :

```
{% if isMobile %}
  {# content for mobile device #}
{% endif %}

```

My cache\_context service :

file located in my module modules/custom/customCacheContext/src/Cache

```
<?php

namespace Drupal\customCacheContext\Cache;

use Drupal\Core\Cache\Context;
use Drupal\Core\Cache\Context\CacheContextInterface;
use Drupal\Core\Cache\CacheableMetadata;

/**
 * Defines the MobiledetectCacheContext service, for mobile or desktop caching.
 *
 * Cache context ID: 'mobile_detect'.
 */
class MobiledetectCacheContext implements CacheContextInterface  {

    /**
     * Constructor
     */
    public function __construct(MobileDetect $mobileDetector)
    {
        $this->mobileDetector = $mobileDetector;
    }

    /**
     * {@inheritdoc}
     */
    public static function getLabel() {
        return t('Mobile Detect');
    }

    /**
     * {@inheritdoc}
     */
    public function getContext($parameters = NULL) {

        if($this->mobileDetector->isMobile()) {
            return 'mobile';
        }

        return 'desktop';

    }

    /**
     * {@inheritdoc}
     */
    public function getCacheableMetadata($parameters = NULL) {

        return new CacheableMetadata();

    }

}

```

My cache\_context service.yml:

```
services:
  cache_context.mobile_detect:
    class: Drupal\customCacheContext\Cache\MobiledetectCacheContext
    arguments: ['@krs.mobile_detect']
    tags:
      - { name: cache.context }

```

# Answer
I finally found the solution. My scripts work pretty well, i just forgot one little thing about the cache modules Drupal enable by default in core.

**I needed to disable "internal page cache"** module and **only keep "dynamic page cache" enabled**. In fact "internal page cache" works for anonymous users only and caches the whole page in order to get better performance. It is therefore not possible to create dynamic parts and "max-age" or "cache context" doesn't work. So if you disable the module, drupal uses by default "dynamic page cache" and "max-age" or "cache context" will work then.

I hope this helps you.

More infos here : http://wimleers.com/article/drupal-8-dynamic-page-cache
> 2 votes

---
Tags: theming, caching
---


# Question
Title: How to get reference field value in term object?
I have term object with referance field .How to get values for referance ids.Please check attached srceenshot of my term object.

I tried this but it return nothing

```
 $ids = array_column($term_object->field_aktivitaetsbild->getValue(), 'target_id');
kint($ids);

```

# Answer
> 2 votes
You can get the IDs like this:

```
$target_ids = [];

foreach ($term_object->field_aktivitaetsbild as $item) {
  if ($item->entity) {
    $target_ids[] = $item->entity->id();
  }
}

```

Source: Programmatically get all names of an entity reference field.

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


# Question
Title: hook_theme default arguments not recognised in template
When using hook\_theme I create an array of variables with default values:

```
/**
 * Implementation of hook_theme
 */
function my_module_theme() {

  return array(

    'my_theme' => array(
      'arguments' => array(
        'var1' => 'default value',
      ),
      'template' => 'my-theme',
    ),

  );
}

```

And the template file my-theme.tpl.php:

```
<div><?php print $var1; ?></div>

```

But inside the corresponding template the $var1 variable is only recognised if I explicitly send it with the theme() implementation:

```
print theme('my_theme', array('var1' => 'New var'); // No errors

print theme('my_theme'); // Notice: Undefined variable: var1 in include()

```

My understanding of the default arguments are just that - they should be the default if they are not explicitly defined. What am I missing?

# Answer
You have to do like

/\** * Implementation of hook\_theme \*/ function my\_module\_theme() {

return array(

```
'my_theme' => array(
  'variables' => array(
    'var1' => 'default value',
  ),
  'template' => 'my-theme',
),

```

); }

Instead of arguments use variables.

Hope this will help.
> 1 votes

# Answer
If you want your variable to take default value then you first need to define that variable in your\_theme\_preprocess\_HOOK() function then only your variable will be available in template file without any php notice.
> 0 votes

---
Tags: 7, hooks
---


# Question
Title: Block is displayed on page even though no region is selected, how is this possible?
I am fairly new to drupal, while doing some maintenance I came across a situation that I don't understand

A block, which is defined inside a view has no region selected, yet it appears on pages determined by the "Only the listed pages" option below

It appears in a specific region, an `<aside>` named as "region-sidebar-second"

I'm unable to find anywhere in admin, or in the code to determine that is the region where this block should appear.

What could I be missing?

# Answer
This happened to me once, turns out it was added through the context module. So check if your site has it.

Else, could have been added through the Panels module or the Display Suite module. So check if you have any of these modules also.

If you have non of the above modules are installed then maybe it was added via a template file. So check your template files in your theme's template folder.

Last but not least, perhaps through a preprocess function? check your `template.php` file if on D7 or `themename.theme` file if you're on D8.

Good luck detective.
> 1 votes

---
Tags: blocks, theming
---


title: Two pagers for a single view

text:
# Question
Title: Two pagers for a single view
I have a view with fields. In fields I have added two `rendered node` fields with two different view modes `teaser` and `teaser1`.

I want to add two pagers to this view. One for the first rendered node with view mode `teaser` and one is for the 2nd rendered node with view mode `teaser1`.

I have grouped the 2nd rendered node by a date field in template file.

The first rendered node is simple a list and the pager will add new content.

The 2nd rendered node is grouped by a date field. Content is displaying under each group date. The pager for this view mode will be different.

It will add new group dates along with their content not just only content.

I have looked up for contrib module but didnt find one. I think I have do this custom. But can someone guide me from Where I should start and can give me an idea.

# Answer
If i understand correctly this is not possible out of the box with your current setup and views only. Could you split the view into 2 seperate views instead? Use the second one as attachment for the first. So you could define the pager for each view. You could also look into Views Field View Module. With node specific pagers created with the Entity Pager Module it could possibly work even with your current setup.
> 0 votes

---
Tags: 7, views, paging
---


# Question
Title: Add script on head section without module
I have a google add script Which I want to integrate on the head section. How can I add the script to the head section on drupal 7 without any module and info file? Script is below:

```
 (function () {

        var _onload = function(){

            if (document.readyState && !/loaded|complete/.test(document.readyState)){setTimeout(_onload, 10);return}

            if (!window.__adroll_loaded){__adroll_loaded=true;setTimeout(_onload, 50);return}

            var scr = document.createElement("script");

        };
});

```

# Answer
You can alter html.tpl.php and add your script in head.

Just alter html.tpl.php file from theme folder. If its not present copy it from drupal/modules/system folder.

Also you can use Js Injector module: https://www.drupal.org/project/js\_injector

Hope this will help.

Thanks,
> 0 votes

# Answer
Add it your theme instead.

html.tpl.php would be the correct template to use.
> 1 votes

# Answer
Add html.tpl.php (if not in theme folder) file in theme template folder and add this script to the file.
> 0 votes

# Answer
I would place this script in external js file and insert it with "drupal\_add\_js" function in template file.

```
drupal_add_js(drupal_get_path('theme', 'MYTHEME') .'/file.js', array('type' => 'external','scope' => 'header','group' => JS_THEME,'every_page' => TRUE,'weight' => -1,));

```
> -1 votes

---
Tags: 7
---


# Question
Title: Text field inside <p> tags falls below it
I've created a custom twig template in which I'm placing a text field inside a

tag like so:

```
<p>{{ content.field_sample_text }}</p>

```

It renders the content of that field just fine but when I inspect it, it seems to create a new div below the

tag and places its contents in that div like so:

```
<p></p>
<div>
  Content of the field
</div>
<p></p>

```

There's an extra p tag at the end as well which is also confusing. How can I ensure that my text field renders inside the original p tag as intended so that I can style it properly?

# Answer
If you are using Stable like theme you can see that the field is wrapped around a `div` tag. You can rewrite `field.html.twig` with your theme suggestions and edit the markup.
> 1 votes

---
Tags: theming, entities
---


# Question
Title: How to prevent users uploading images from their system?
I have some image fields on my site.

My requirement is that the user should not be able to upload an image. Instead there will be a directory where I will place some images. And the user can only select an image from those images through image field.

Is it possible?

# Answer
> 1 votes
There are three major projects for handling media libraries in Drupal 7:

The most basic solution is **IMCE**. It is simply a file browser for files on your server. I.e. image files are just files on your server and Drupal isn't really aware of them and their meta-data.

The **Media** module uses in its ver. 2.0 **File Entity** module to manage media files, making it well aligned with the Drupal framework. It is a tried and tested solution for those who want something more sophisticated than **IMCE**.

**Scald** is a relatively new entry for media management. It comes with a very powerful media library sub-module and integrates seamlessly with the CKeditor WYSYWYG editor through drag and drop. It has a bit steeper learning curve than the two others, but is IMHO well worth the effort.

Whether users are allowed to upload files (as opposed to pulling them from a library) are for all three projects handled by permissions settings.

# Answer
> 0 votes
You need to require these two modules IMCE and IMCE filefield. Through this you can browse from exisiting directory and set images.

# Answer
> 0 votes
Also have a look at FileField Sources. With this module you can control which sources are allowed per field.

# Answer
> 0 votes
There is a module that solves such cases specifically. (Offer a few images for avatar selection, to the user.)

It also offers to disable 'upload' of user pictures.

https://www.drupal.org/project/avatar\_selection

---
Tags: 7, media
---


# Question
Title: Views Custom Join change the 'on' condition
We are using Drupal commerce and have a report in views using commerce\_line\_item as the base. We need to be able to split the quantities up into multiple rows. So if a line item has a qty of 5 there should be 5 rows. I am trying to implement this:

https://stackoverflow.com/questions/22291814/mysql-return-result-by-quantity-per-row

I am adding a join in hook\_views\_query\_alter but there does not appear to be a way of changing the join condition from = to \<=.

LEFT JOIN {line\_items\_tally} line\_items\_tally ON commerce\_line\_item.quantity = line\_items\_tally.n

needs to be

LEFT JOIN {line\_items\_tally} line\_items\_tally ON commerce\_line\_item.quantity \<= line\_items\_tally.n

Is there any way of doing that?

# Answer
> 0 votes
I ended up using hook\_query\_alter rather than hook\_views\_query\_alter

```
/**
 * Implements hook_query_alter().
 */
function custom_query_alter(QueryAlterableInterface $query) {
  if ($query->hasTag('line_itmes_qty')) {
    $query->join('line_items_tally', 't', 't.n <= commerce_line_item.quantity');
  }
}

```

---
Tags: views, database
---


title: Paypal recurring payments

text:
# Question
Title: Paypal recurring payments
I'm currently using Drupal Commerce and the Commerce PayPal (https://www.drupal.org/project/commerce\_paypal) module in order to allow my users to purchase items. That said, some of the items require that my customer be charged every month. Is there a way to store credit card data in order to run recurring payments (Commerce Recurring doesn't seem to be compatible with Commerce Paypal)? If I'm not mistaken, the documentation states that PayPal doesn't include the option to run recurring payments? Is there another module I can integrate in order to allow this?

# Answer
We never implemented PayPal's direct recurring API, though there should be a patch in the queue to try out if you wanted. The thing to check will be real-time notifications of recurring charge failures and whether or not there's a user interface allowing the customer to cancel. Since it's PayPal, there very well may be from within PayPal itself.

PayPal does offer the ability to create Billing Agreements that you can charge against at later times, but while we included the ability to *create* Billing Agreements via Express Checkout, it was never fully integrated into the Commerce License Billing suite that we would normally recommend for recurring payment management.

In short, with PayPal your options are limited. If you are able to make use of Commerce Braintree instead, which is a PayPal company, I'd advise doing so, as that module offers a direct integration with Commerce Card on File (and therefore the license billing module).
> 3 votes

# Answer
You don't want to store credit card data on your site, unless you plan to be PCI Compliant which I don't think you'd want to do.

You're better off finding a vendor-based solution. I'm pretty sure that Stripe offers this, and it integrates nicely with Drupal with Commerce Stripe module
> 1 votes

---
Tags: 7, commerce
---


# Question
Title: How do I include a custom class file in a module?
In Drupal 7 module development, I could include a custom inc, api, or php class file using the file\[\]= directive in the module.info file or the drupal\_load\_included() function.

With D8 using PSR, what is the proper way to package up a "plain ole PHP object" and reference it in `DefaultController.php`? Think something like: `$a = new POPO();`.

Is just giving the PHP file containing the class a `namespace` sufficient? How does the controller (or module in general) know to reference or scan for that class?

# Answer
You don't use `file[] = ...` anymore. Instead, classes are autoloaded. For example, I have a module with the following file structure:

* views\_hybrid/
    + views\_hybrid.info.yml
    + views\_hybrid.module
    + src/
        - Plugin/
            * Field/
                + FieldFormatter/
                    - HybridFormatter.php

`HybridFormatter.php` defines a class called HybridFormatter.

In my .module file, if I start typing in my IDE (NetBeans in this case) `HybridFormatter` it autocompletes to `\Drupal\views_hybrid\Plugin\Field\FieldFormatter\HybridFormatter::` because it is autoloaded. Since I don't want that whole path littering my module, at the top I have placed the line,

```
use Drupal\views_hybrid\Plugin\Field\FieldFormatter\HybridFormatter;

```

along with `use` directives for other classes I am including for use with my module.

The namespace is defined in HybridFormatter.php like so:

```
namespace Drupal\views_hybrid\Plugin\Field\FieldFormatter;

class HybridFormatter extends FormatterBase { ... }

```
> 15 votes

# Answer
I'd like to add that for including a custom class that doesn't fit into the D8 "plugin, controller, form, etc." defaults, you can still do so as noted PSR-4 overview here

For my use case, I dropped a "CustomClass.php" in /modules/custom/my\_module/src/ At the beginning of the file I included the namespace declaration

```
namespace Drupal\my_module;

```

and in the file I wanted to use it in (in this particular case my\_theme.theme) I added

```
use Drupal\my_module\CustomClass;

```
> 16 votes

---
Tags: 8
---


title: How to convert text into long text?

text:
# Question
Title: How to convert text into long text?
I have a text field on my site which is becoming a problem. Users tend to input more text than I had expected. I need to convert this text field into a long text field. This is problematic because there is already content. I'm looking for a way to do the conversion as painlessly as possible. Here is my current plan:

* Create the new long text field
* Use a module (probably feeds) to duplicate the data (export, then re-import)
* Delete the old text field.

Is this a good idea or is there a better faster one out there?

# Answer
Though the question is pretty old, I would like to add my suggestion to it. I don't think changing the field type directly in the database is a good idea.

1. Create a new field (long text) with the necessary settings, and add it to the content type.
2. Then you can use the following script to copy all the old field values (text field) to new field (long text).

> ```
> <?php
> // Assign value from old_field to new_field
> $nodes = node_load_multiple(array(), array("type" => "your_type"));
> foreach ($nodes as $node) {
>   $node->field_new = $node->field_old;
>   field_attach_update('node', $node);
> }
>
> ```

3. Finally delete the old field and use the new field for further use.
> 1 votes

# Answer
Once a field is created from admin then it can not be edited later. Because field data is saved in Binary form and can not be edited.

e.g if we have field 'field1' then it will have table 'field\_data\_field\_field1' and 'field\_revision\_field\_field1' in the database. Now change its datatype directly in the database.

1. Export these tables as a sql file and delete the old field in the manage field section of content type using admin.
2. Create the new field with the same name as it was before and choose the appropriate datatype
3. Now delete the newly created table 'field\_data\_field\_field1' and 'field\_revision\_field\_field1' and import the file that were exported earlier.
4. Other way you can create a new field and copy the data from old tables to new table and change settings later.
> 0 votes

# Answer
That worked for me really well:

```
drush scr update_field_description_100.php

```

**update\_field\_description.php**

```
$field_name = "field_description_100";

$rows = db_query("SELECT id,data FROM {field_config} WHERE field_name = '{$field_name}' ")->fetchAll(PDO::FETCH_OBJ);

foreach ($rows as $row ){
 $row->data=unserialize($row->data);
 unset($row->data['settings']['max_length']);
 $row->type="text_long";
 drupal_write_record("field_config", $row, "id");
}

// Update field_config_instance
$rows = db_query("SELECT id,data FROM {field_config_instance} WHERE field_name = '{$field_name}'")->fetchAll(PDO::FETCH_OBJ);

foreach ($rows as $row ){
 $row->data=unserialize($row->data);
 $row->data['widget']['type']='text_textarea';
 unset($row->data['widget']['settings']['size']);
 $row->data['widget']['settings']['rows']=3;
 drupal_write_record("field_config_instance", $row, "id");
}

// Update the field table
db_change_field("field_data_{$field_name}", "{$field_name}_value", "{$field_name}_value", array(
 "type" => "varchar",
 "length" => "20000",
));
db_change_field("field_revision_{$field_name}", "{$field_name}_value", "{$field_name}_value", array(
 "type" => "varchar",
 "length" => "20000",
));

// Clear caches.
field_cache_clear(TRUE);

```

Manage fields:

Content editor:

Taken from:

http://thedombroshow.com/drupal-7-converting-a-text-field-to-a-long-text-aka-textarea-field/
> 0 votes

---
Tags: 7, entities, feeds
---


title: Change a long text field to text

text:
# Question
Title: Change a long text field to text
I'm trying to convert a long-text field into a text-field. The only thing I found so far is the "field\_config" table in the database. But any change there is only leading to errors. Do I have to change it somewhere else?

# Answer
Once a field is created from admin then it *can not be edited later*. Because field data is saved in **Binary form** and can not be edited.

e.g if we have field '**test**' then it will have table 'field\_data\_field\_**test**' and 'field\_revision\_field\_**test**' in the database. Now change its **datatype directly** in the database.

1. Export these tables as a sql file and delete the old field in the manage field section of content type using admin.
2. Create the new field with the same name as it was before and choose the appropriate datatype
3. Now delete the newly created table 'field\_data\_field\_test' and 'field\_revision\_field\_test' and import the file that were exported earlier.

Other way you can create a new field and copy the data from old tables to new table and change settings later.

Hope it will help you!
> 0 votes

# Answer
Thanks to Geoff. As my long-text never was bigger than the textfield size (255) I could use this solution with ease. I did it the following:
Created a new field "textfield"
Did a database action:

```
INSERT INTO newtable (newfields)
SELECT oldfields FROM oldtable

```

and then deleted the old field.
> 0 votes

# Answer
I posted a php script that converts from text field to long\_text field. You could easily reverse it:

How to convert text into long text?
> 0 votes

---
Tags: 7, entities
---


# Question
Title: How can I resolve these errors when updating the module?
I want to update Drupal Commerce to 8.x-2.0-beta7 from a clean, Composer-based installation of 8.x-2.0-beta6, following the documentation on http://docs.drupalcommerce.org/v2/getting-started/update.html.

I noticed that `composer update drupal/commerce --with-dependencies` did not update drupal/core. This surprises me. Isn't drupal/core a dependency? Anyway, says it's white-listed so I then ran `composer update drupal/core`.

Now I am hitting a problem with updates.

> drupal update:debug
>
> Fatal error: Cannot use Drupal\Console\Core\Bootstrap\DrupalConsoleCore as DrupalConsoleCore because the name is already in use in/pathto/commerce8/vendor/drupal/console/src/Bootstrap/Drupal.php on line 11

> drupal update:execute
>
> Fatal error: Cannot use Drupal\Console\Core\Bootstrap\DrupalConsoleCore as DrupalConsoleCore because the name is already in use in /pathto/commerce8/vendor/drupal/console/src/Bootstrap/Drupal.php on line 11

I have since run update.php, but the Composer errors persist.

I am learning about Composer, and I don't know yet anything about Drupal Console.

What am I doing wrong?

# Answer
It sounds like Drupal Console someone was installed improperly, based on the duplicate class name error.

Can you try removing the `/pathto/commerce8/vendor` directory. Then run `composer install` once more. That'll fixup all third party dependencies, hopefully resolve this.
> 1 votes

---
Tags: commerce, console
---


title: How to add currency (TMT) to Commerce?

text:
# Question
Title: How to add currency (TMT) to Commerce?
Turkmenistan Manat is missing from Drupal Commerce list - how to add it to 7.x?

# Answer
Per the `commerce.api.php` file, there is a document hook which allows you to add currencies.

```
function hook_commerce_currency_info() {
  return array (
    'CHF' => array(
      'code' => 'CHF',
      'numeric_code' => '756',
      'symbol' => 'Fr.',
      'name' => t('Swiss Franc'),
      'symbol_placement' => 'before',
      'code_placement' => 'before',
      'minor_unit' => t('Rappen'),
      'major_unit' => t('Franc'),
      'rounding_step' => '0.05',
    ),
  );
}

```

http://cgit.drupalcode.org/commerce/tree/commerce.api.php
> 0 votes

---
Tags: commerce
---


# Question
Title: Multiple Values does not work when field widget is "Autocomplete term widget (tagging)"
In Drupal 7, multiple values does not show for fields which are "Autocomplete term widget (tagging)"

Please look at the attached screenshot.

I'm trying to make 3 separate tags, and want it to appear as the following:

Payment accepted: **Interac**, **cash**, **Watcard**

But I'm not able to do so using commas. It works as plain text but I need it to be linked separate tags. Is there an easy solution to this? I'm new to drupal and don't really know much about coding.

Thanks for your help!

# Answer
> 0 votes
Change the field widget to "Check boxes/ Radio buttons"

For letting user select multiple values, go to Administration » Structure » Taxonomy » Your-Term » Manage fields, set Number of Values in Field Settings to "Unlimited"

---
Tags: entities, taxonomy-terms
---


# Question
Title: How do you remove N/A from radio button groups?
I have added a radio button to my content type and I have found that N/A was automatically put in as a selection. How do I get rid of this?

# Answer
> 3 votes
If you make a list field mandatory, the N/A option automatically goes away

Also, if you allow multiple values, the radio dot elements automatically becomes checkboxes.

# Answer
> 0 votes
I strive to reduce complexity in the systems I build. Following is a CSS only solution. Replace the example field machine names with yours.

```
#edit-field-history-of-prematurity-und > div:nth-child(1),
#edit-field-diagnosed-und > option:nth-child(1),
#edit-field-history-of-hypoxia-und > div:nth-child(1),
#edit-field-ekg-und > div:nth-child(1) {
    display: none;
}

```

---
Tags: 7, entities
---


title: Panels block title translation

text:
# Question
Title: Panels block title translation
I use blocks in a panel with Drupal 8. With view generated blocks there are no problems: The block titles are translated accordingly to the view settings. With custom blocks, it appears to be problematic to get the block title translated. I hoped that these titles would be translatable via the user interface translation but they are not; plus, in the panel settings, I can set the block title, but I cannot translate it.

How can I translate block titles (and maybe block content) of custom blocks in a panel, with Drupal 8?

# Answer
You can override the block.html.twig template and handle the translation of the title directly on the template:

```
    {{ label|t }}

```

You may need to confirm the title structure (if is #markup or plain text/string)
> -1 votes

# Answer
Page variants are translatable using config translation at /admin/config/regional/config-translation
> -1 votes

---
Tags: blocks, i18n-l10n, panels
---


title: Modifying Webform checkbox markup

text:
# Question
Title: Modifying Webform checkbox markup
I've already managed to modify checkbox markup for a bit but there's still something that I can't access. Current markup is as follows and here you can see the duplicate text of which last one should be removed:

```
<div class="form-item form-item-submitted-payment-methods-1 form-type-checkbox checkbox">
<!-- This LABEL seems to be unreachable; cannot remove/modify it -->
<label class="control-label" for="edit-submitted-payment-methods-1">
    <!-- This DIV can be modified via [hook_theme]_checkbox(&$variables) -->
    <div class="checkbox">
        <label>
            <input type="checkbox" id="edit-submitted-payment-methods-1" name="submitted[payment_methods][1]" value="1" class="form-checkbox checkbox require-one-edit-submitted-payment-methods">
            <span class="checkbox-material"><span class="check"></span></span>
            In cash (to a member or representative)
        </label>
    </div>
    In cash (to a member or representative) <!-- Duplicate and should be removed: how to? -->
</label>

```

# Answer
Well, solution was to remove "fake" label and wrapper div which was moved upper to wrap "control-label". All done in THEME\_NAME\_checkbox(&$variables){}.

```
    <div class="form-item form-item-submitted-payment-methods-1 form-type-checkbox checkbox">
<label class="control-label" for="edit-submitted-payment-methods-1">
    <div class="checkbox"> <!-- Remove this and add it as suffix/prefix for the element -->
        <label> <!-- Remove this also -->
            <input type="checkbox" id="edit-submitted-payment-methods-1" name="submitted[payment_methods][1]" value="1" class="form-checkbox checkbox require-one-edit-submitted-payment-methods">
            <span class="checkbox-material"><span class="check"></span></span>
            In cash (to a member or representative)
        </label>
    </div>
    In cash (to a member or representative) <!-- Duplicate and should be removed: how to? -->
</label>

```
> 0 votes

---
Tags: theming, webforms
---


title: Are all custom entities Content types?

text:
# Question
Title: Are all custom entities Content types?
I'm getting mixed up in my terminology. If I created an Entity named "Students," via .yml that has its own table. Is that a Content type but a Custom Content Type?

# Answer
You define an entity type in a class. Either a content or a config entity. Content entities can have bundles. These are defined in config entities (you need a separate class for this). Like all config entities bundles can be exported and imported in yaml files.

An example for a content entity type is **Node**. The node bundle is called **Content Type**. Internally Drupal uses `node_type` as machine name, which makes it clear that this is only used for nodes.
> 0 votes

---
Tags: entities
---


# Question
Title: Exposed date select list in descending order
Using Drupal 7 Views with exposed filter on date, the select list is working fine. Problem is that the list is always in ascending order, for example 2000:2014, but we want it the other way round, like 2014:2000 so that the recent years are closer at hand.

I don't mind if the solution (changing date list to descending order) is affecting every select list of the whole site. Preferably if don't need to change code.

# Answer
> 0 votes
You can do this via hook\_form\_alter().

```
function myModule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_exposed_form' && $form['#id'] == 'FORM-UNIQUE-ID') {
    $form['field_MY_FIELD_value']['value']['#process'][] = date_select_desc_element_process;
  }
}

```

---
Tags: views
---


title: looping over images in an image field

text:
# Question
Title: looping over images in an image field
I have an image field which lets the user input as many images as they want. (set allow number of values to unlimited in field settings) I'm creating a twig template where i want to loop over these images and apply specific style if it's the first image or set a different style if its any other image.

I know I can use `{{ file_url(node.field_home_hero.entity.fileuri) }}` to get the url of the image in an image field. I'm trying to get this for every image in my field now though which is proving to be a challenge.

I'm curently iterating over the field in twig as so:

```
{% for image in content.field_field_name %}
  {% if loop.first %}
    <div class="class1">
      <img src="{ file_url(node.image.entity.fileuri) }" >
    <div>
  {% else %}
    <div class="class2">
      <img src="{ file_url(node.image.entity.fileuri) }">
  {% endif %}
{% endfor %}

```

But doing the above does not load up the images for me. I know for sure I'm messing up with the access somewhere but not able to figure out what i'm doing wrong. If someone could point me to the right direction that would be great!

# Answer
If you want to access the file uri in the node you have to iterate over the field in the node:

```
{% for image in node.field_image %}
  {% if loop.first %}
    <div class="class1">
      <img src="{{ file_url(image.entity.fileuri) }}" />
    </div>
  {% else %}
    <div class="class2">
      <img src="{{ file_url(image.entity.fileuri) }}" />
    </div>
  {% endif %}
{% endfor %}

```
> 2 votes

---
Tags: theming, 8, nodes, entities, media
---


# Question
Title: The wrong site title is coming up for home page
For some reason, the title of our website in browser windows and tabs is coming up as something else. We aren't even sure where this title came from, as it has nothing to do with our site.

I checked the page source to see what was showing up in the `<title>` tags, and sure enough, it's the same, incorrect title.

I tried changing the name of the site and the site's slogan, hoping that would help. I've cleared the caches. It's been going on for about 8 months, before we made some upgrades to core and modules.

Other page titles seem to be working correctly. There are no nodes with this title. We are using Drupal Commons. Drupal version 7.50.

# Answer
Normally the `<title>` element is set in `template_preprocess_html`

```
  // Construct page title.
  if (drupal_get_title()) {
    $head_title = array(
      'title' => strip_tags(drupal_get_title()),
      'name' => check_plain(variable_get('site_name', 'Drupal')),
    );
  }
  else {
    $head_title = array('name' => check_plain(variable_get('site_name', 'Drupal')));
    if (variable_get('site_slogan', '')) {
      $head_title['slogan'] = filter_xss_admin(variable_get('site_slogan', ''));
    }
  }
  $variables['head_title_array'] = $head_title;
  $variables['head_title'] = implode(' | ', $head_title);

```

That is then output in your theme `html.tpl.php`

You may have some code or configuration overriding the default title there in a module or theme.

I'd suggest searching through the codebase for the title text, or perhaps in a db dump file.

After that, you can either update it, or add some code for your own HTML `<title>` logic.
> 0 votes

---
Tags: 7
---


title: Full HTML Block Security

text:
# Question
Title: Full HTML Block Security
I'm currently considering using a free theme for my a Website, they use bootstraps Carousel to render a slideshow/banner, and their advice on how to make that slideshow work is to embed HTML in a block an set it to Full HTML. Tutorial here

My question is if there are security risks attached to having a Full HTML block?

Or does Drupal (more specifically 8) inherently protects blocks with code/snippets in?

If so, to which extent should one utilize it, instead of e.g. building a custom block?

# Answer
In general, you should probably only give Full HTML access to only your most trusted users (which may only be the site administrator).

Now the example you linked to was intended to be used in a block. Block administration is also something that will likely only be done by your site administrators. Every site needs an administration plan, so it's fair to ask, can the people entrusted with block creation also be entrusted with the use of Full HTML? If so, no need to create a custom block.

Alternatively, the example code is fairly benign, so you could add a Text Format that allowed for the use of those tags & attributes (admin -\> configuration -\> content authoring -\> text formats and editors). I often create a Text Format called Advanced HTML that allows for most tags but I don't include any of the potentially problematic tags like script, object, style, etc.

To produce that carousel, looks like you would minimally need the following:

`<div id class role data-*><ol class><li class data-*><img src alt><h3><p>`
> 0 votes

---
Tags: theming, 8, blocks
---


# Question
Title: How to prevent ad blockers from restricting sections of my website (non google ads)
I have a block towards the header, that is full width, and has some basic HTML with Full HTML Text format.

It is getting blocked by my user's ad blocker software. so far it is reported to be blocked with AdBlock and Adguard. I have tested and verified with AdBlock

My content isn't "spamy" at all. In fact it is a coupon code so they are missing out :)

Here's the content

```
<h2 style="text-align: center; font-weight: 300;">50% OFF entire store. Use code <strong>AWESOMESALE50</strong></h2>

```

The CSS class for the block is **banner-advert**

Could it be the inline CSS?

# Answer
Thanks to No Sssweat's simple suggestion, it is fixed (as far as I can tell).

I changed my CSS class for the block from "`banner-advert`" to "`sitewide-promo`".

I'm assuming either `banner` or `advert` caused an issue, so I replaced both.
> 2 votes

---
Tags: theming, blocks
---


# Question
Title: Disable email updates alert on expired domain
As per question, my domain already expired for over months now and im not planning on using it anymore but i keep getting the modules updates email alert coming from the domain. How can i disable it since i can no longer access the domain to change the setting. I find its kinda weird how the domain still able to send the email.

Thanks.

# Answer
> 0 votes
If you still have access to the FTP folders where you uploaded Drupal just remove the folder where you previously installed Drupal. If you can't access it anymore, there's not much you can do. You can setup a filter in your mailbox though.

---
Tags: emails, updating, notifications
---


# Question
Title: Why the content of a block created in an external module does not appear?
I am creating a module for wich i need to create a block with php code. I\`m making it as follow:

```
function my_modulo_block_info() {
   $blocks = array();
   $blocks['start'] = array(
      'title' => 'Start',
      'info' => t('The start block'),
      'status' => TRUE,
      'region' => 'content',
   );
   return $blocks;
}

function my_modulo_block_view($delta='') {
   $block = array();
   switch($delta) {
      case 'start' :
         $block['content'] = '<?php echo "Hello world"; ?>';
         break;
   }
   return $block;
}

```

But i see only the block name on the page, it dont print Hello world. Any body know why?

# Answer
> 2 votes
call a php function to built block-content, in hook\_view code should be:

```
//construct your output as a function
$block['content'] = myfunctionname(); // this function is called 3 lines below
....
return $block;
//then call your output content function
function myfunctionname() {
$output = 'whatever you want(arrays, functions, html, more php, ....)'
 };
 return $output;

```

that will return $output as your content.

---
Tags: blocks
---