# Question
Title: Create a new node when a field is added to a node
How can a element (say an image) that is entered as a field (when creating a new node), also be created as a separate new node at the same time (either through copying the image or by referencing it)?

# Answer
## Option A

I myself wouldn't do that - I think that generally it's a practice that doesn't worth the time and risks (as would be explained in Option B) but anyway:

In drupal 7 this can be done with the Multi Node Add module. There isn't a version for Drupal 8 yet; If you don't have the knowledge to port it to Drupal 8 you might hire a PHP programmer to do that for you. An alternative would be to copy the desired fields from 1 node to another via this module. This module is going through a porting process at this era.

Guessing that both modules work only on 1 content type at a time, and can't recreate content in another Content type: You could handle that by cloning your nodes inside the same content type (X) with Node Clone or a similar module, and than convert all clones to their other, similar content type (Y) with Node Convert or a similar module.

## Option B - Advice and workaround with Views.

As an SEOer, I would recommend on finding other way to enrich your sites' content; Cloned content is quite a good recipe for lowering both your PQS (Page quality scores) and in some cases - Your PageRanks as well... This becomes more serious with every passing year.

It could be better to create more sophisticated content pieces based on the first node content via the Views module (which is part of the Drupal 8 core); Here is an intro to Views 8. Many tutorials are available in Youtube for that module.
> 1 votes

---
Tags: nodes, entities
---


# Question
Title: Utilizing private methods/vars inside module
I'm creating a custom module which uses a few hooks and then after the form is submitted it will dive into custom PHP interaction that interfaces with an external restful API.

I want some of these variables and functions to be private as they will contain business rules and some variables that I wouldn't want someone to get their hands on (easily).

I'm uncertain of how to do this in Drupal. I understand that I would need to create a PHP class which would then have private/public methods available inside of it. But how do I do this?

Do I build this PHP class in its own file outside of my .module file and then use `files[] = includes/MyClass.class.php` in my .info file to import this external class file in?

Then once it's successfully imported in I could instantiate it with `$something = new MyClass();`?

Is it that simple to do, or is there another/better way?

# Answer
Yes - it's that simple. Remember; Drupal is only PHP.

Although your class should be called `MyClass.php` rather than `MyClass.class.php` to adhere to the Drupal Coding Standards for OO code (note - this isn't explicitly declared, but is hinted at when they describe the Interface file naming conventions).

Just to pad this out a bit; you could also use the X Autoload module to allow for PSR-4 style autoloading instead of adding your class in the `files[]` array. I do this for as much D7 code as possible now (where I'm not using Composer Manager), and would whole heartedly recommend it.

> xautoload is a comprehensive and yet highly efficient PHP class loading suite.
>
> Most importantly, it provides Drupal-8-style PSR-4 (and the old D8 PSR-0-style in "lib") autoloading for Drupal 7. But it is also a great tool for 3rd party autoloading.
> 2 votes

---
Tags: 7
---


title: Clearing Boost cache with drush

text:
# Question
Title: Clearing Boost cache with drush
I am testing the boost module out, it is a great performance enhancement for the site I am working on.

However I would like to be able to get boost to clear it's cache using drush. `Drush cc all` doesn't seem to do this. And looking in the boost module code, there doesn't seem to be a cron command for it. Am I missing something or is this currently not implemented?

# Answer
> 3 votes
Answering my own question. I was missing something.

Boost is a bit more fussy about the URL than the rest of drush when clearing the cache

```
drush --uri=http://my.site.name cc all

```

will work.

# Answer
> 3 votes
If you just want to clear Boost's cache and not any other caches:

`drush --uri=http://example.com boost-cache-clear-all`

See also the notes at the Drush integration patch for Boost.

# Answer
> 0 votes
If you have drush aliases configured, just do this: drush @name\_of\_alias cc all

I'm using Drush 8 and Drupal 7, but this also worked on my earlier versions.

---
Tags: drush, caching
---


# Question
Title: clear boost cached pages as the content is changed
I am using boost with Maximum Cache Lifetime = 1 Day and Maximum Cache Lifetime = 0 Sec

If i do update some content / banners, i have to clear caches at

> /admin/config/development/performance

Is this the only way? There is no way that changed nodes/frontPage cache will be automatically cleared instantly ? and all users will see new content instead of asking them to use Ctrl + f5.

any clues thanks

# Answer
> 1 votes
You can use the Cache Expiration module to expire caches when content is updated.

The expire module provides the events that fire when content is updated and other caching modules hook into those events and clear their caches.

The boost module supports the expire module's events.

Once installed, you can configure the module at admin/config/system/expire.

# Answer
> 0 votes
You can use drush as well. If you have drush aliases configured, just do this: drush @name\_of\_alias cc all

I'm using Drush 8 and Drupal 7, but this also worked on my earlier versions.

# Answer
> 0 votes
If I understand correct, I had a similar issue once: It's a known problem; The fact the Drush's cache isn't separate and being cleared in any general cache-clearing is problematic especially in sites where there are only tens or hundreds of users daily (and not thousands or much more) because than you need to wait everyone to rebuild the cache for you.

The solution I had in the time is pretty lame: If you site doesn't have more than some thousands of users a day - Just don't use Boost. It's a heavy module designed in the time only or mostly for large-scale sites by terms of users, so I stopped using it at the time.

We can hope that in **Drupal 8** the Boost's caching system will be totally or partly separated from the general caching system...

---

If you actually meant to ask what is the fastest way to clear cache than instead navigation to the address you posted (with or without a browser bookmark) you could install Admin\_menu for Drupal 7 or Admin\_toolbar for Drupal 8 and they would not only give you a cool icon to clear cache instantly on every page but a comfortable management menu on top of your browsers fold.

In Drush master you could do "`drush cr`" (this stands for drush cache rebuild).

That's aside of using cache expiration mentioned in other comments.

---
Tags: caching
---


title: White screen of death errors

text:
# Question
Title: White screen of death errors
I have come across an error that I have been having difficulty fixing.
I am suspicious the problem is the "Primary script unknown" error, but I am lost. There is an reoccurring Fatal Error, but it is a core file that has never been modified..

Any help would be greatly appreciated.

See below for an example of the nginx error log.

> 2016/01/09 08:08:17 \[error\] 1082#0: \*315 FastCGI sent in stderr: "Primary script unknown" while reading response header from upstream, client: 188.68.224.62, server: , request: "GET http://dhg.pisz.pl/httptest.php HTTP/1.1", upstream: "fastcgi://unix:/var/run/php5-fpm.sock:", host: "dhg.pisz.pl"

# Answer
The error you've shown is from someone running a hacking script.

The nginx documentation offers many solutions to avoid running bad php scripts in their Pitfalls and Common Mistakes FAQ, but the one I like is the try\_files directive to only run scripts that exist on your server otherwise return a 404 Not Found status code.

```
location ~* \.php$ {
    try_files $uri =404;
    fastcgi_pass backend;
    # [...]
}

```
> 0 votes

---
Tags: 7, wsod
---


# Question
Title: Reflection error on my first module development
I'm using Drupal 8.0.1. Just I'm started to develop a custom module to simply show hello world text in /first path. Here is my code.

**FirstController.php** \[It is in the path sites/all/modules/first\_module/src/Controller\]

```
namespace Drupal\first_module\Controller;

use Drupal\Core\Controller\ControllerBase;

class FirstController extends ControllerBase {
  public function content() {
  return array(
      '#type' => 'markup',
      '#markup' => t('Hello world'),
    );
  }
}

```

**first\_module.routing.yml** \[It is in the path sites/all/modules/first\_module\]

```
first_module.content:
  path: '/first'
  defaults:
    _controller: 'Drupal\first_module\Controller\FirstController::content'
    _title: 'Hello world'
  requirements:
    _permission: 'access content'
    _permission: 'view first'

```

**first\_module.info.yml** \[It is in the path sites/all/modules/first\_module\]

```
name: First Module
description: An experimental module to build our first Drupal 8 module
package: Custom
type: module
version: 1.0
core: 8.x

```

I can able to see my custom module in **http://localhost/admin/modules** also I can able to install the module. But when I got to the path http://localhost/first it shows the error

```
ReflectionException: Class Drupal\\first_module\\Controller\\FirstController does not exist in
/home/aaa/Public/drupal-8.0.1/core/lib/Drupal/Core/Entity/EntityResolverManager.php on line 128, referer: http://d8.localhost/admin/modules

```

Where I would went wrong?? Any help!!!

# Answer
> 0 votes
a) in the route definition the path to the controller should start with backslash b) in the route only one permission will work c) you do not need to define type markup, just use #markup alone

---
Tags: 8
---


# Question
Title: Complicated 'double' contextual and relationships view
I would like some help on how to implement the following view: A block that shows all the '**events**' happening at any '**location**' created by a user.

I have 'event' and 'location' content types. There is a field in the 'event' node which refers to a 'location' node (it's nid).

I am familiar with views, just not sure how to get the 'double filtering' required to show only events that have a location that is created by the user logged in. I cannot create an 'author' relationship to a contextual filter for the location or event to a simple filter, as the view displays events, not locations... Any ideas?

# Answer
Thanks to Argiepiano for the direction to take. Here is what I ended up doing. Quick reminder of the objective: a business owner (owning more than one places) wants to view all **events** created at any of his **locations**. **Locations** and **events** are separate content types and in the '**event**' content type, there is an *entity reference field* to the **location** nodes.

1. Create a view of content type **EVENT**.
2. Create a relationship '`Entity Reference: Referenced Entity`'. Call it 'location node'.
3. Create a relationship '`Content Author`'. Call it 'location author'. Add a relationship to 'location node'.
4. Create a contextual filter '`Content: Author uid`'. Add a relationship to 'location author'.
5. In that filter, in the section 'WHEN THE FILTER VALUE IS NOT IN THE URL', select '`provide default value`' and choose '`User ID from logged in user`'.

I hope it helps someone in the future!
> 0 votes

# Answer
I would create a View of the Content Type **Location** (these are the nodes created by your users, right?).

1. Create a Relationship to **Author**.
2. Create a Filter to `user: current` and select Yes in `Is the logged in user` (NB: this a a regular filter, not a Contextual Filter)
3. Create a Relationship to the **Event** type through its reference field to Location (**NB:** select `Entity Reference: Referencing Entity` . If you select "Require this relationship" the View will limit the **Location** types to only those referenced in an **Event** node
4. Add any field to the View, but be sure to select the relationship you created in 3 above to show field from the Event type

That's it! Nice question!
> 0 votes

---
Tags: views
---


title: Twig Link Macro?

text:
# Question
Title: Twig Link Macro?
I was looking at various Drupal core Twig templates to get an idea of how menus are rendered; I came across this line in menu--toolbar.html.twig.

```
{{ link(item.title, item.url) }}

```

Is `link` a macro? If so, where is it defined?

It doesn't appear to be a Twig feature. I couldn't find it by searching in the Drupal 8 code base.

# Answer
> 8 votes
It's a `Twig_SimpleFunction` extension, rather than a macro. It's registered with Twig in `\Drupal\Core\Template\TwigExtension::getFunctions()`.

Its callback method is `\Drupal\Core\Template\TwigExtension::getLink()`.

---
Tags: theming, 8
---


# Question
Title: Its possible to load "Image Formatter" on a theme?
I'm building a Drupal 8 theme, and I need the functionality of Image URL Formatter. I do not want to have a contrib module as dependency of my theme. So I started digging up into the Image URL Formatter code and I notice that it was very simple module. For this reason, I try to stole that code and added into my theme and I'm not able to see the image formatter =(.

Then I notice that DrupalConsole have generator to generate the same functionality from Image URL Formatter (the generator have like 95% of the same code as IUM), so I decide to added into my theme and for some reason did not run.

The location of my code is at - **Casper/src/Plugin/Field/FieldFormatter/CasperImageFormatter.php** and the source code is the same as what the generator provide, which is...

```
<?php

/**
 * @file
 * Contains \Drupal\casper\Plugin\Field\FieldFormatter\CasperImageFormatter.
 */

namespace Drupal\casper\Plugin\Field\FieldFormatter;

use Drupal\image\Plugin\Field\FieldFormatter\ImageFormatterBase;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Url;
use Drupal\Core\Utility\LinkGeneratorInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Form\FormStateInterface;

/**
 * Plugin implementation of the 'casper_image_formatter' formatter.
 *
 * @FieldFormatter(
 *   id = "casper_image_formatter",
 *   label = @Translation("Casper image formatter"),
 *   field_types = {
 *     "image"
 *   }
 * )
 */
class CasperImageFormatter extends ImageFormatterBase implements ContainerFactoryPluginInterface {
    /**
     * The current user.
     *
     * @var \Drupal\Core\Session\AccountInterface
     */
    protected $currentUser;

    /**
     * The link generator.
     *
     * @var \Drupal\Core\Utility\LinkGeneratorInterface
     */
    protected $linkGenerator;

    /**
     * The image style entity storage.
     *
     * @var \Drupal\Core\Entity\EntityStorageInterface
     */
    protected $imageStyleStorage;

    /**
     * Constructs an ImageFormatter object.
     *
     * @param string $plugin_id
     *   The plugin_id for the formatter.
     * @param mixed $plugin_definition
     *   The plugin implementation definition.
     * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
     *   The definition of the field to which the formatter is associated.
     * @param array $settings
     *   The formatter settings.
     * @param string $label
     *   The formatter label display setting.
     * @param string $view_mode
     *   The view mode.
     * @param array $third_party_settings
     *   Any third party settings settings.
     * @param \Drupal\Core\Session\AccountInterface $current_user
     *   The current user.
     * @param \Drupal\Core\Utility\LinkGeneratorInterface $link_generator
     *   The link generator service.
     * @param \Drupal\Core\Entity\EntityStorageInterface $image_style_storage
     *   The entity storage for the image.
     */
    public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, AccountInterface $current_user, LinkGeneratorInterface $link_generator, EntityStorageInterface $image_style_storage) {
        parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);
        $this->currentUser = $current_user;
        $this->linkGenerator = $link_generator;
        $this->imageStyleStorage = $image_style_storage;
    }

    /**
     * {@inheritdoc}
     */
    public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
        return new static(
            $plugin_id,
            $plugin_definition,
            $configuration['field_definition'],
            $configuration['settings'],
            $configuration['label'],
            $configuration['view_mode'],
            $configuration['third_party_settings'],
            $container->get('current_user'),
            $container->get('link_generator'),
            $container->get('entity.manager')->getStorage('image_style')
        );
    }

    /**
     * {@inheritdoc}
     */
    public static function defaultSettings() {
        return array(
            'image_style' => '',
            'image_link' => '',
        ) + parent::defaultSettings();
    }

    /**
     * {@inheritdoc}
     */
    public function settingsForm(array $form, FormStateInterface $form_state) {
        $image_styles = image_style_options(FALSE);
        $element['image_style'] = array(
            '#title' => t('Image style'),
            '#type' => 'select',
            '#default_value' => $this->getSetting('image_style'),
            '#empty_option' => t('None (original image)'),
            '#options' => $image_styles,
            '#description' => array(
                '#markup' => $this->linkGenerator->generate($this->t('Configure Image Styles'), new Url('entity.image_style.collection')),
                '#access' => $this->currentUser->hasPermission('administer image styles'),
            ),
        );

        return $element;
    }

    /**
     * {@inheritdoc}
     */
    public function settingsSummary() {
        $summary = array();
        $image_styles = image_style_options(FALSE);

        // Unset possible 'No defined styles' option.
        unset($image_styles['']);

        // Styles could be lost because of enabled/disabled modules that defines
        // their styles in code.
        $image_style_setting = $this->getSetting('image_style');
        if (isset($image_styles[$image_style_setting])) {
            $summary[] = t('Image style: @style', array('@style' => $image_styles[$image_style_setting]));
        }
        else {
            $summary[] = t('Original image');
        }

        return $summary;
    }

    /**
     * {@inheritdoc}
     */
    public function viewElements(FieldItemListInterface $items, $langcode) {
        $elements = array();
        $files = $this->getEntitiesToView($items, $langcode);

        // Early opt-out if the field is empty.
        if (empty($files)) {
            return $elements;
        }

        $url = NULL;
        $image_link_setting = $this->getSetting('image_link');
        // Check if the formatter involves a link.
        if ($image_link_setting == 'content') {
            $entity = $items->getEntity();
            if (!$entity->isNew()) {
                $url = $entity->urlInfo();
            }
        }
        elseif ($image_link_setting == 'file') {
            $link_file = TRUE;
        }

        $image_style_setting = $this->getSetting('image_style');

        // Collect cache tags to be added for each item in the field.
        $cache_tags = array();
        if (!empty($image_style_setting)) {
            $image_style = $this->imageStyleStorage->load($image_style_setting);
            $cache_tags = $image_style->getCacheTags();
        }

        foreach ($files as $delta => $file) {
            if (isset($link_file)) {
                $image_uri = $file->getFileUri();
                $url = Url::fromUri(file_create_url($image_uri));
            }

            $cache_tags = Cache::mergeTags($cache_tags, $file->getCacheTags());

            // Extract field item attributes for the theme function, and unset them
            // from the $item so that the field template does not re-render them.
            $item = $file->_referringItem;
            $item_attributes = $item->_attributes;
            unset($item->_attributes);

            $elements[$delta] = array(
                '#theme' => 'image_formatter',
                '#item' => $item,
                '#item_attributes' => $item_attributes,
                '#image_style' => $image_style_setting,
                '#url' => $url,
                '#cache' => array(
                    'tags' => $cache_tags,
                ),
            );
        }

        return $elements;
    }

}

```

I was able to run the same code into a module and it works perfect, but for some reason when I try to run it into the theme it does not work.

My question is...

* Its possible to run this much logic into my theme, if so what I'm doing wrong ?

# Answer
If you look at the docs for plugins, you'll see this:

> Plugins are defined by modules: a module may provide plugins of different types, and different modules may provide their own plugins of a particular type.

While it doesn't explicitly exclude themes, I think you can infer from that phrase that only modules can provide plugins.

An option would be to structure your theme's code to be aware of the existence of a module, and react differently, e.g.

```
function MYTHEME_preprocess_foo(&$vars) {
  if (\Drupal::moduleHandler()->moduleExists('image_url_formatter')) {
    // ...
  }
}

```
> 1 votes

---
Tags: theming, 8
---


# Question
Title: Using hook_form_alter to add a label/placeholder insider a form <input> tag
using Drupal Commerce checkout form there is a default 'address' field (it's dynamic and includes several fields in one that are not easy to separate - such as country, name, address 1 and 2, state, etc.). I turned off the labels for the address field because they are ugly and I'd like to put the labels INSIDE each tag, as you would normally do with html like so:

HTML 5:

```
<input type="text" name="user" placeholder="Username">

```

Where the 'placeholder' property shows what should be entered into the field within the tag, thus removing the need to have a separate label at all.

Anyone know how to do this (include a placeholder property if you will) with hook\_form\_alter?

# Answer
> 3 votes
You can specify placeholder attribute in '#attributes' array like this:

```
function MODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'form_id') {
    $form['item']['#attributes']['placeholder'] = t('Placeholder text');
  }
}

```

---
Tags: forms, commerce
---


# Question
Title: Limited access to 'Edit' Commerce Order & limit line items to only 1 type
With further to my earlier question regarding Services for Products, I have implemented as per the suggestions:

Following are the components:

1. Orders
2. Service Vendors - The individual or the Person who would provide service for an order request
3. Rating and Review - Fivestar rating and Editable text field added as fields for Commerce Order.

I am facing the following problems:

1. In order for user to rate and provide a review on the order I would have to expose the Order as editable for authenticated user which would let the user to edit all other order attributes. The fivestar rating module, allows rating the star without edit privilege but the review - (editable textfield) requires edit privileges on Order entity for the user. I have tried to use Field Permissions to limit edit access only to these 2 fields but with no success!
2. I am providing Voting and Review operations on Order because the Line items can be configured only in "Add to cart" form. Hence, I would have to limit a single order to contain only 1 line item type (which can contain multiple products / services of the same type). How can I achieve this?
3. As against the accepted answer here I am planning to create an order request when user needs it and then later update the price (also quantity in line item) after the service quotation actually takes place. Is there a way to edit the order to accommodate this functionality?

**PS**: I would need the rating module to be applied on Order (or Line item) because unlike regular E-Commerce this does not deal with product, it is service oriented. There is a possibility that different vendors can provide service for each order of same type, hence I will have to associate the rating and review system with either Order or Line Item and then pick up the average rating of a particular vendor who has serviced different orders in the past.

Also, if there are any better ways of achieving the same kindly let me know.

# Answer
While it is possible for you to add those fields to the order, you should really create a new review content type and then use those for your reviews and then use an entity reference to connect the review content to the order. In the future, if you did want to allow line items to have reviews, you could then just add another entity reference field to the line items and you can reuse all of the UX you've built for the main review form for anywhere else.

Furthermore, by using a reference, you're not limiting yourself to a particular type of form. If you ever wanted to differentiate between certain types of services and provide different review criteria, you can much more easily do that with new content types + entity reference.

Brief overview of steps:

1. Create a new review content type with your fields and fivestar info.
2. Create an entity reference field on your Order. I believe you can use Entity connect to have it show a "create link" if no reference exists.
3. If that doesn't work, you can use Views to make it so that a user can only connect the entityreference field to orders that they own.
> 1 votes

---
Tags: 7, commerce
---


# Question
Title: How to delete a path when uninstall a module?
this is for Drupal 8:

in my hook\_install function, i have following code:

```
MenuLinkContent::create([
        'title' => 'Location',
        'link' => ['uri' => 'route:locator.filters'],
        'menu_name' => 'main',
    ])->save();

```

when I have uninstalled my module, how do remove above defined link?

# Answer
You can use `hook_uninstall` and `MenuLinkManager::removeDefinition`

> Removes a single link definition from the menu tree storage. This is used for plugins not found through discovery to remove definitions.
> 0 votes

---
Tags: 8
---


title: Missing edit button on node page

text:
# Question
Title: Missing edit button on node page
Im allowing authenticated users to add field values on existing nodes on my site using the "Field Permissions" module. I\`ve set up the necessary custom permissions in the "manage fields" screen:

However, an authenticated user is never shown the "Edit" button on the node page:

If everything where working, the user should have a "Edit" button to be able to add field values. What\`s wrong?

# Answer
The Field Permissions is so the field shows up, they can see it, when they are editing the node.

The problem here looks to be that they don't have permission to edit the content type node.

Ex:

* Allow to Edit Own Articles
* Allow to Edit All Articles
> 2 votes

---
Tags: entities, users
---


# Question
Title: How to get field structure for a custom content type?
I have created a custom content type (mytest) via the Drupal 8 UI.

The content type contains a list field which has the following key|values:

```
gp|GP
device|Device

```

I have tried the following code to retrieve field, but it not there.

```
$fields = \Drupal::service('entity_field.manager')->getFieldDefinitions('node', 'mytest');

```

Does any one know how to retrieve a List field structure?

# Answer
> 1 votes
I have to say sorry, I made a mistake in my other part of code.

```
$fields = \Drupal::service('entity_field.manager')->getFieldDefinitions('node', 'mytest');

```

is correct, it returns all fields belongs to "mytest"

---
Tags: 8, hooks
---


title: Flags - Recreate the 'poke' function

text:
# Question
Title: Flags - Recreate the 'poke' function
I need to create a flags view that displays a list of users that have "poked" the current user with D7, Views 3 and Flag 3. I've read through this question and drupal.org/node/296971, neither instruction seems to work or at least I am not able to get the settings right.

To define the functionality:

1. Users are presented with a list view of other users
2. Users click the "poke" flag link on a single user
3. Users then browse to /pokes/ and view all other people that have poked them

This is either a difficult setup or I'm missing a couple settings (the latter is extremely likely). Any hints or thoughts?

# Answer
I created a test site with Flag and Views module enabled and so far, I could create a view to display users who have poked *me*.

Create a new Flag to flag users. This don't have to be a global flag. Flag text could be "Poke" and unflag text could be "remove".

> Users are presented with a list view of other users Users click the "poke" flag link on a single user

1. Create a view on users table
2. Add a new relationship: **Flags: User**.
3. Uncheck "Include only flagged content "; Choose the poke flag; By: Current user.
4. You will see a new field "**Flags: Flag link**". Add it.

You will now get a view that shows users and a flag link to flag them. Modify the View as you wish. http://paste2.org/CGZshUFN

> Users then browse to /pokes/ and view all other people that have poked them

This is a really tricky part.

1. Create a new View on users table.
2. Add a new relationship: **Flags: User flag**.
3. Uncheck "Include only flagged content "; Choose the poke flag; By: Any user.
4. Add a new contextual filter: **Flags: Content ID**
5. Under contextual filter settings, choose the just-added relationship and set to user the current logged in user ID.
6. Now we have access to a list of user IDs that has flagged the currently logged in user.
7. Add a new relationship: **Flags: User**
8. Under this relationship's settings, check "require this relationship".
9. Add a new field: **User: name** and choose the relationship created in step #7.
10. Add a new relationship: **Flags: User flag** (yes, you are added one already in step 2 but go ahead).
11. Under this relationship's settings, choose the the user relationship created at step #7. Uncheck "include only flagged content"; By: current user.
12. Add a new field: **Flags: Flag link** and choose the relationship created at step #10. http://paste2.org/tkWg99vp

Above step 12 will add the "flag back" type link that the user can see a list of users who have flagged the current user and a link to flag them back. You will need many Views template tweaks to adjust the wording of the View to suit your need.

Good luck!
> 5 votes

# Answer
It works for me too. But When multiple people flagged the same user, When I go on its profile and see the numbers of users who flagged him, I always see the first one and not the others.

In my code I count the number of users who flagged him with this script :

```
if ($flag) {
 print "The number of people who voted for this proposal:";
 print $flag->get_count($user->uid);
}

```

And I my output is 3 people.

I don't know why I see only 1 user.
> 1 votes

---
Tags: 7, users, flags, views
---


title: Custom page template for content pages

text:
# Question
Title: Custom page template for content pages
Is there any way to make a custom page.html.twig template in Drupal 8?

By default, Drupal generates some suggestions, but I'm looking for something like page--node--content-type.html.twig.

# Answer
> 14 votes
You are looking for hook\_theme\_suggestions\_HOOK\_alter().

HOOK is the name of the template, in your case, page. You should be able to add the following to your theme in the .theme file.

In there, do something like this:

```
function yourtheme_theme_suggestions_page_alter(array &$suggestions, array $variables) {
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $suggestions[] = 'page__node__' . $node->getType();
  }
}

```

# Answer
> 6 votes
This code from Jeff Burnz (https://www.drupal.org/node/2521876#comment-10684366) solved it for me. It also places the suggestion above page--node so the capability to override with page--node--% and page--node--\[id\] remains.

```
<?php
function THEME_NAME_theme_suggestions_page_alter(array &$suggestions, array $variables) {
  // Add content type suggestions.
  if ($node = \Drupal::request()->attributes->get('node')) {
    array_splice($suggestions, 1, 0, 'page__' . $node->getType());
  }
}
?>

```

# Answer
> 3 votes
Your file name is bad, rename page.**htm**.twig to page.**html**.twig

After for clear your cache during page refresh, enable an use settings.local.php file inside your installation, on linux by example, copy and rename the example file to the good location with this command:

> cp /sites/example.settings.local.php /sites/default/settings.local.php

Uncomment this lines inside your settings.php :

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

```

And inside /sites/default/services.yml use this value:

```
debug: true

```

Inside settings.local.php, uncomment this line :

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

```

Because Drupal say

> Do not use this setting until after the site is installed.

Now, your environment is ready, you can create theme and modules, but if you add a template file, you need to clear the cache manually :)

Note: don't use this configuration in production (bad performances for user/server).

# Answer
> 1 votes
it is ok ,according to drupal 8 theme api the template file for `page` is `page.html.twig`, may be you did not clear cache.

# Answer
> -1 votes
It's like:

* `node--[content-type].html.twig` ex: `node--article.html.twig`
* `node--[content-type]--[display-format].html.twig`, ex: `node--article--full.html.twig`

Here the screenshot of template suggestion:

---
Tags: theming
---


# Question
Title: How to load into a normal page instead of the (blog-like) front page?
I have my drupal site, loading the page when I open the site. It is the normal behaviour, but I don't want it.

I have a different HOME page that I want to see when I open my site (instead of the page with all my articles).

I still have the page with articles and I have a link NEWS in my menu that points to it, because I want to keep the articles page.

I tried this:

```
Configuration > Site information > Default front page > (I wrote "home")

```

But the NEWS link didn't point to the articles anymore, because it seems that now the page is my HOME page.

So, it loads the HOME page on opening, like I wanted, but now my articles page is not accessible via the NEWS link in the menu.

How can I see my HOME page as default page when entering the site "without" losing access to the page of articles?

Thanks

# Answer
> 0 votes
it is a bit confusing your question. But I try help you.

First, did you create a view called 'NEWS' (in Structure -\> Views)? OK great, make this view accessible by url '/news'. (if not, make this sentence true).

Check if your 'HOME' view is set to \< front\> (url '/home', same url that you set in Site information page - with '/home') and make it accessible.

Then, edit the 'main content' block (in Structure -\> Block Lay out) to only appear in NEWS page.

This is for drupal 8, but seems to be almost the same for drupal 7 (same modules, Block and Views). PS: Edit your question and add a tag with your drupal version.

---
Tags: 7, redirection
---


# Question
Title: Mobile navigation works on desktop resize but not on mobile devices
I'm using the mobile navigation module for a responsive menu, and it works perfect if I resize the browser window on my desktop, but it won't work on actual mobile devices (tested on iPhone and Galaxy Note 2). I've used the module before and never had any issues, and I'm using the same configuration, as far as I can tell. I can't figure out why it's not working.

This is the site I'm working on, and here's a screenshot of the problem on the Note 2. I recently upgraded my server from PHP 5.2 to 5.3, but I don't think that could be causing this issue (plus I needed to upgrade for a different module).

Other than that I really have no clue, so I'd appreciate your help.

# Answer
There is a jQuery error happening on your webpage.

You need to fix that either by trying var $ = jQuery.noconflit(); OR Update the version of jQuery to 1.7, don't upgrade to version higher than 1.7 since jQuery 'on' function will not work.

Thank, Vineeth
> 1 votes

# Answer
This just happened to me, and I hope that it will save someone the frustration that I have felt:

The responsive menu not appear at screen width \< 480px? I was so frustrated with this until I, with the help of Him, figured out the bug. I tried changing the jquery and messed with the .module file associated with it, but still I couldn't get it to work.... until now: The code for it was this:

```
.responsive-menus.responsified.responsive-toggled.absolute .responsive-menus-simple {
position: absolute;
z-index: 999;
top: auto;
}

```

For some reason beyond me, it works well on screen sizes \> 480px, but as soon as it hits that size, it just doesn't work. Here is to code to get it to work on screen sizes \< 480px:

```
@media only screen and (max-width:480px){
        .responsive-menus.responsified.responsive-toggled.absolute .responsive-menus-simple {
        position: relative;
    }
}

```

Hope that helps someone!
> 0 votes

---
Tags: 7, routes, navigation
---


# Question
Title: How to collect payments for the missed periods with the hard decline status?
Scenario: A user's credit card expires and he misses to pay his recurring monthly fee. Two months later he updates his credit card and because the license never expired the system picks it up and continues to successfully charge his card on file for consequent periods, but unfortunately not for the previous.

And it's not clear how to charge for the missed payments with the "Payment failed (hard decline)" status. Any suggestions?

Edit: I had to delete my own answer:

> It was not obvious for me that I needed to use Commerce Dunning module to re-charge for the missed payments.

after trying the Commerce Dunning module, because unfortunately for hard declines it only sends notifications without attempting to re-charge for the missed period even if a customer updated his credit card. Per description on https://www.drupal.org/project/commerce\_dunning:

> If it was a hard decline that led to the failure, the customer needs to update their credit card, so notifications regarding that are also scheduled.

So unfortunately it is still not clear how to collect payments for the missed period.

# Answer
> 0 votes
If a customer has a hard decline, they'll need to log in and create a new stored payment option. They can create new stored payments via their account dashboard:

If memory serves, it should then be used by default.

---
Tags: commerce
---


# Question
Title: How to get the url from uri, uri given as string
I have a string

```
$directory = "/home/ .../sites/default/files..."

```

I tried to get the absolute url with:

```
$MYURL = Url::fromUri("base://".$directory);

```

That leads to an exception!

Can anybody explain hot to retrieve the url from a string?

# Answer
Thx for your comments,

but I found the answer by investigating the core modules:

```
preg_match('/sites(.*)/',$directory,$matches);
$url_new = $matches[1];
$MYURL = Url::fromUri('base:/sites'.$url_new, array('absolute' => TRUE))->toString();

```

Hope this helps some other guys too!
> 5 votes

# Answer
Based on that string alone you'll never get a url. Do you mean how do you get the url of the current site?

In Drupal you don't need to. As Ivan recommended in his comment, you just need

This is the way to do it if the file was uploaded in Drupal and you have the uri.

`file_create_url($path)` https://api.drupal.org/api/drupal/core!includes!file.inc/function/file\_create\_url/8

If you don't have the URI (for example you need to link to a file in your theme, then use:

```
drupal_get_path('theme', 'your_theme');

```

https://api.drupal.org/api/drupal/core%21includes%21bootstrap.inc/function/drupal\_get\_path/8

Then combine that with a link *relative to the theme* instead of relative to the server root like your current $directory is:

```
$directory = "files/myfile.png";

```

Then jam them together:

```
$my_url = drupal_get_path('theme', 'your_theme')."/".$directory;

```

If you do need the full site URL for some reason, you should be able to use `global $base_url;` (a global variable in Drupal) or check out https://stackoverflow.com/a/14500505/430191
> 4 votes

---
Tags: 8, uri
---


title: Display user name with flags

text:
# Question
Title: Display user name with flags
I've this code who show the number of users who 'flagged me' (I'm using flag module)

```
$flag = flag_get_flag('poke');

if ($flag) {
  print "The number of people who voted for this proposal:";
  print $flag->get_count($user->uid);
}

```

I want to show a list of the user name instead.

Thanks for your help !

# Answer
> 0 votes
I don't know the particular flag api to get the usernames of flagged node. But it can be possible using custom implementation. Here is code

```
function get_usernames_flagged_node($entity_id, $flag_name) { //Supply node_id and flag_name
  $get_all_nodes_of_flagged = flag_get_flag_flagging_data($flag_name);
  $flagged_content_detail = array();
  $username = array();
  foreach($get_all_nodes_of_flagged as $get_all_nodes_of_flags) {
    $flagged_content_detail[] = $get_all_nodes_of_flags;
  }
  foreach($flagged_content_detail as $flag_content) {
    if($entity_id == $flag_content->entity_id) {
     $user=user_load($flag_content->uid);
     $username[]=$user->name;
    }
  }
  return $username;
}

```

It can be also possible using views and flag modules. For your reference see this page

---
Tags: users, flags
---


title: Display user field into html.tpl.php

text:
# Question
Title: Display user field into html.tpl.php
In my `user-profile.tpl.php` file In print fields like this :

```
<?php

    global $user;
    $user_id = arg(1);

    $user_item = user_load_by_name($user->name);

    if($user->uid == $user_id) {
        echo 'I'm connected';
        print render ($user_profile['field_mon_statut']);
    }

 ?>

```

I wrote this exact same code in html.tpl.php but it does not appear..

Thanks for your help !

# Answer
U are setting $user variable inside if condition, while in if u have condition that $user-\>uid, so it will compute as false, and it will not go inside if condition.

You will have to write:

```
global $user;
if($user->uid) {
// Your code

```

// Edited

```
global $user;
$user_id = arg(1);

// $user_item = user_load($user->uid);

if($user->uid == $user_id) {
    echo 'I m connected';
    print render ($user_profile['field_mon_statut']);
}

```
> 0 votes

# Answer
I think the problem is in the line where you use `echo`

```
<?php
    global $user;
    $user_id = arg(1);

    $user_item = user_load_by_name($user->name);

    if($user->uid == $user_id) {
        echo "I'm connected";
        print render ($user_profile['field_mon_statut']);
    }

 ?>

```

Try to use the code above and check.
> 0 votes

---
Tags: entities, theming, users
---


# Question
Title: Adding print friendly link on specific nodes
(I have already posted this question on StackOverflow, but I then discovered this forum, which seems to be a more appropriate place for this question.)

I have also read all the similar questions on StackOverflow, without luck.

In my Drupal 7 site I use the Printer, email and PDF versions module. I want to show the printer link on some specific pages of a specific content type. So I have enabled the link in that content type, which include a boolean field (field\_printable) where the admin should be able to choose to include the link or not. In my template.php file I try to figure out how to work this out. This is what I have got so far in my template.php file:

```
function mytheme_preprocess_node(&$variables) {
    if($variables['type'] == "mycontenttype"){
        // boolean field that returns 1 if checked
        if($node->field_printable['und'][0]['value'] == 1){
                 what to put here ...?
        }
    }
}

```

I should probably use print\_insert\_link(); to insert the link, but I cannot figure out how. Can anyone point me in the right direction? I have spent hours googling on similar questions, but I am stuck right now.

Any help would be very appreciated, thanks in advance.

# Answer
Well If I understood your question properly, you want to show the print link only on specific nodes right? This is straightforward, by default if you enable print links for a content type, then the print links will be displayed on all the nodes of the content type.

For those nodes which you don't want the print links to be displayed, you can disable the print links option in the node-edit page itself.
> 0 votes

---
Tags: theming, hooks
---


title: sharing profile2 fields multisite

text:
# Question
Title: sharing profile2 fields multisite
I have a site with 2 multi site like

```
abc.com
xyz.abc.com
zxy.abc.com

```

All sites have same drupal 7 code base. and I shared all users successfully across all portals.

my setting file for sub-site looks like this

```
$main_database_prefix = 'abc.com.';
$current_database = 'xyz';
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => $current_database,
      'username' => 'xxxx',
      'password' => 'xxxx',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => array(
              'default'   => '',
              'users'     => $main_database_prefix,
              'sessions'  => $main_database_prefix,
              'role'      => $main_database_prefix,
          'role_permission'      => $main_database_prefix,
              'users_roles'   => $main_database_prefix,
              'user_ips'   => $main_database_prefix,
              'user_profile_details' => $main_database_prefix,
              'price' => $main_database_prefix,
              'transaction' => $main_database_prefix,
          'db_roles' => $main_database_prefix,
          'user_modification_history'=>$main_database_prefix,
          'authmap'=> $main_database_prefix,
          'user_industry'=>$main_database_prefix,
          'user_account_request'=>$main_database_prefix,
          'user_account_details'=>$main_database_prefix,
          'country'=>$main_database_prefix,
          'states'=>$main_database_prefix,
          'discount'=>$main_database_prefix,
          'taxname'=>$main_database_prefix,
          'price'=>$main_database_prefix,
          'transaction'=>$main_database_prefix,
          'field_data_field_subscriber_name'=>$main_database_prefix,
          'field_revision_field_subscriber_name'=>$main_database_prefix,
          'profile'=>$main_database_prefix,
          'profile_type'=>$main_database_prefix,

    )
    ),
  ),
);

```

all tables working properly , except

```
'field_data_field_subscriber_name'=>$main_database_prefix,
      'field_revision_field_subscriber_name'=>$main_database_prefix,
      'profile'=>$main_database_prefix,
      'profile_type'=>$main_database_prefix,

```

I can not see these fields on registration page or in backend The only difference is these table are entity reference table.

I googled things a lot for this but no success.

Thanks in advance.

# Answer
> 1 votes
I resolved the issue by adding 2 more tables

```
'field_config_instance'=>$main_database_prefix,
'field_config'=>$main_database_prefix,

```

---
Tags: 7, users, entities
---


# Question
Title: Translation not working for custom user roles
I am using the i18n module. I created 2 custom roles: *venue user* and *customer user*. When I log in as administrator user, the translation is working fine; when we log in either as *venue user* or *customer user*, the translation does not work.

How can I solve this problem?

# Answer
> 0 votes
You need to grant translation related permissions for the two roles you have created. For changing the permissions, go to `/admin/people/permissions`, then set the translation related permissions for the two roles. If you want the two roles to translate content, then you need to grant **Translate content** permission for the roles.

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


title: Views Contextual Filter by current day

text:
# Question
Title: Views Contextual Filter by current day
I am using the Date Repeat Entity module for generating a checklist for users. I am able to use Views to display the list in chronological order for tasks relevant for the current user using a Contextual Filter. Could I also use a Contextual Filter to only show the current nodes that have a date equal to the current date?

I would think this could be done by entering some PHP code as shown here:

# Answer
> 1 votes
> I'm not sure how a regular filter will be able to grab the current day

Add your date field to the filter.

You will then see this screen

Click apply and continue

Click on select a date, and select relative date

Put **today** as your relative date.

---
Tags: 7, views, datetime
---


# Question
Title: checkboxes on submit not showing correct values. Shows 0 always
I am working with a form which contains list of checkboxes based on country. checkboxes are rendered correctly. But on submit, I don't get checkboxes' correct values. It always gets submitted as NOT CHECKED. My code is as below:

```
    foreach($fields as $id=>$title) {
          $form['test'.$code]['fields-'.$code] = array(
              '#type' => 'checkboxes',
              '#options' => drupal_map_assoc(array_keys($fields)),
              '#title' => t('Title'),
              '#attributes' => array('name' => 'field-'.$code.'-'.$id),
          );
        }

    function config_submit($form, &$form_state) {
      var_dump($form_state['values']);
      exit;
    }

```

outputs :

```
array (size=13)
  'fields-dk' =>
    array (size=7)
      'title' => int 0
      'reason' => int 0
      'doc-reference' => int 0
      'description' => int 0
      'upload-claim-file' => int 0
      'product-detail' => int 0
      'barcode-num' => int 0

```

Why is it returning always as 0? What am I missing?

# Answer
While we can't see how your form is built completely, it might be that your custom attributes are affecting the element "name" in the form state.

i.e change

```
'#attributes' => array('name' => 'field-'.$code.'-'.$id),

```

to

```
'#attributes' => array('data-name' => 'field-'.$code.'-'.$id),

```
> 2 votes

# Answer
Please verify the submission data with below:

```
$form_state['values']['checkboxes'];

or

foreach($form_state['values']['checkboxes'] as $key=>$value){
  // your logic
}

```

I have used the below form field for checkbox

```
$form['checkboxes'] = array(
      '#type' => 'tableselect',
      '#header' => $build_table['#header'],
      '#options' => $build_table['#rows'],
      '#empty' => t('No records found.')
    );

```
> 0 votes

---
Tags: 7, forms
---


# Question
Title: adding adwords tracking to a Click instead of a page load using goog_report_conversion
I am using the simple subscription module to subscribe users to a newsletter and wish to track clicks of subscribers. Is there an easy way to call the goog\_report\_conversion() function when someone clicks on the subscribe button? I don't see any configuration for this with the simple subscription module.

# Answer
General advice: don't use "simple" modules for non-simple tasks.

No easy way here, you need to inject your JavaScript code, and attach additional behavior to that button. Worse, you would need to make sure there is **enough time** for function to process. My colleagues use *thank you page* if feasible for that very reason - browser will do it's best to minimize time between button click and page load. On *thank you page* that is not an issue.
> 1 votes

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


# Question
Title: How can I download specific dev version of Drupal module?
What to do when I want specific dev version of Drupal module.

For example:

Geocoder dev version from Jan 07 2016 is broken. Latest working dev version was from Sept 01 2015.

How can I download previous dev version of Drupal module (Geocoder in my case)? Any method is welcome.

# Answer
For the easiest way to do it:

1. Go into the repository
2. Select a version there and click on it
3. There will be hash of commit (example)

So, you know the hash of commit - just clone this module from repository and switch to required hash of commit.

How to clone module via git

How to checkout the specific commit

Example:

```
git clone --branch 7.x-1.x https://git.drupal.org/project/geocoder.git
cd geocoder
git checkout c994066d58bc7518bc9796c60d4d43f98ae477cd

```
> 4 votes

# Answer
I want to add one more way how to download specific dev version of Drupal module:

**“Drush make” method**

Create make file for Drush (for example `myMakeFile.make`) and paste into it following:

```
api = 2
core = 7.x
projects[drupal][version] = 7.30
projects[geocoder][version] = "1.x-dev"
projects[geocoder][download][type] = "git"
projects[geocoder][download][url] = "https://git.drupal.org/project/geocoder.git"
projects[geocoder][download][revision] = "2ffd3fa8b22c11100516bf801bc08ba729cc8a68"

```

Type into shell:

```
cd
mkdir removeMeWhenDone
mv myMakeFile.make removeMeWhenDone
cd removeMeWhenDone
drush make myMakeFile.make -y

```

Desired dev version of the Geocoder module is located in `~/removeMeWhenDone/sites/all/modules`, now.

More details about *Drush make* method + how to get commit hash here.
> 1 votes

---
Tags: 7, drush, version-control
---


title: Is there a way to migrate only nodes?

text:
# Question
Title: Is there a way to migrate only nodes?
I don't want to make a full migration. I want to migrate only and solely Nodes (preferably with their Metatag metadata as well). Not Views, Not Panels, not Contexts, not URL redirects - Only Nodes...

I ask this after encountering some troubles in full D7\>\>D8 upgrade and when using the Drupal Upgrade module (I even opened a thread regarding it here in DA). Therefore, I am looking for ways to make only a partial migration, or to make migration in parts.

Is it possible regarding to nodes?

# Answer
You don't need to do a full migration. You can initialize the Upgrade process by connecting to the old site and it will create migrations. Then you can, instead of executing them automatically, run just some of them with the UI provided by the upgrade\_tools project ( I think?).

However, migrations have dependencies. To be able to run the node migration, by default you have to run a few others, e.g. users, text formats and also the fields.

You can try to change that by editing the created migrations either with drush cedit or export/import. I believe someone is also working on an UI for it.

You can also customize any mapping and how fields are migrated. The default behavior is that every field and configuration is migrated 1:1 but to be honest, I can't imagine that's what most sites will want to do. Instead, I imagine they build a new D8 site and then import the content.

See the migration documentation. There are also plenty of blog posts available already around that topic but it's not a trivial thing to do.

Alternatively, you can try to export/import your content, as mentioned in the Comments, Feeds is not quite ready yet, but you could use a views export and import by writing some custom code.
> 9 votes

# Answer
Migration is a bit heavy weight for this. In drupal 7 there were some modules for only import/export of content. In drupal 8 I couldn't find any that is ready yet. So I improvised with a bit of code:

I did an export in drupal 7 with views to csv with the help of the module:

views\_data\_export

In drupal 8 I've used the php-library:

parsecsv-for-php

And this code:

```
require_once('parsecsv.lib.php');
$csv = new parseCSV();
$csv->auto($filepath);
foreach ($csv->data as $key => $row) {
  $node = entity_create('node', array('type' => 'article', 'title' => $row['title'], 'uid' => $row['uid']));
  $node->langcode->value = 'en';
  $body = $row['body'];
  $body = str_replace('http://host1.com/', 'http://host2.com/', $body);
  $node->body->value = $body;
  $node->body->format = 'full_html';
  ...
  $node->save();
}

```

The advantage is, that you can make your own adjustment, like replacing paths from drupal 7, or set a fixed language. And you can check if all dependencies are met, for example that the uid is already there.
> 5 votes

# Answer
We wanted to skip some content types from migration as Migrate modules in D8 migrate all of them by default. We used hook\_migrate\_prepare\_row to skip the content types in our custom module.

```
function hook_migrate_prepare_row(Row $row, MigrateSourceInterface $source, MigrationInterface $migration) {
  // Ignore content types from being migrated.
  if ($migration->id() == 'd6_node_type') {
    $ignore_content_types = array('content_type1', 'content_type2');
    if (in_array($row->getSource()['type'], $ignore_content_types)) {
      return FALSE;
    }
  }

  // Ignoring content of 4 content types.
  $ignore_content_types_content = array('d6_node__content_type1', 'd6_node__content_type2');
  if (in_array($migration->id(), $ignore_content_types_content)) {
    return FALSE;
  }
}

```

More info. - https://www.drupal.org/node/2641912

You get the list of migration ids using drush migrate-status command and skip them as required.
> 1 votes

---
Tags: nodes, 8, migrations
---


# Question
Title: Content Types with field "clusters". Possible or is there a different solution?
My dilemma is this. At the moment I have a content type called "equipment" that I want to have a taxonomy term that will give a type of equipment, based on the selected type I want a new "cluster" of fields and/or taxonomy terms to pop up.

There is likely a different/better way of organizing the data. Creating a new content type for each type of equipment doesn't seem very elegant, especially if I want to create a view for all of the equipment.

Any leads on where I can find a solution to this? My brain has problems with decorator patterns in SQL as well.

# Answer
Probably the easiest solution is to have a single content type, add all fields that you need in any possible situation, and use Conditional Fields to hide/show fields based on the chosen equipment type taxonomy term.
> 0 votes

---
Tags: taxonomy-terms
---


# Question
Title: Views Jump menu with taxonomy url and custom url
I have problem with jump menu and contextual filters. My idea is this:

I have taxonomys (a,b,c) URL: **example.com/a** (this works fine with contex. filters)

Then: example.com/a/**hello**

This **hello** is my menu-url (I make it my own)

When I select **a** in this jump menu and click menu-link **hello** , this jump-menu **a** need to be activated. Default is in this jump-menu is **-Any-**

# Answer
> 0 votes
Here is examples:

First

And then

---
Tags: views
---


title: How to use the Match Redirect module

text:
# Question
Title: How to use the Match Redirect module
I'm trying to use the Match redirect module and follow the basic description I've tried the following:

```
/my-path-1/my-path-2/*

```

to

```
/my-path-2/*

```

OR

```
/ma-path-2/

```

And it doesn't work. I do have pages like:

```
www.example.com/ma-path-2/page-title

```

that works fine as expected, but when I visit

```
www.example.com/my-path-1/my-path-2/page-title

```

I was expecting to be redirected to:

```
www.example.com/my-path-2/page-title

```

Which did not happen. Why? What am I missing here?

Thanks in advance

# Answer
From reading the module description, I get the impression that the Match redirect module module only replaces wildcards and cannot remove them.

I suggest you try redirect module with pathauto. After you change the path in pathauto, remember to use the BULK UPDATE tab to update the urls. Redirect will automatically do it's thing.
> 1 votes

---
Tags: 7, redirection
---


# Question
Title: How to override "active configuration" when the theme is installing?
I have a theme that imports configuration when is installed. The problem is when the configuration is already there and is active.

> Unable to install MYTHEME, field.field.user.user.user\_picture, field.storage.node.body, field.storage.node.field\_image, field.storage.user.user\_picture, node.type.article, views.view.frontpage already exist in active configuration.

I know these errors are because the configuration is already on the site.

How can I override the configuration with a new configuration that is carried from my theme?

# Answer
You cannot. You can provide only configuration for your module or create new configuration entities. You can "override" the default configuration only by profile, not module or theme.

But you can use hook\_install to programmatically override whatever you want.

When it comes to themes, the only configuration that you should provide is block instances and your theme's settings. Of course if you have some advanced blocks you can also provide block types and field storage and instances for them.
> 3 votes

---
Tags: installation, configuration
---


# Question
Title: How can I display a Google map with Search API Views and Search API DB
I am using Search API with Search API DB, and Facets, with Search Views. I want to display a map to plot the results from the search. Is this possible? I have looked everywhere and can't seem to figure it out.

My nodes currently use geofield for the individual node pages.

# Answer
Have you ever tried these two modules? https://www.drupal.org/project/gmap https://www.drupal.org/project/location

With these two modules, you can create google maps and put your location data into a referenced google map.
> 2 votes

# Answer
You could simply write your own field.tpl file for displaying that field and see how to display google map based on geofield values take a display google maps using Geolocation values.

Your tpl file will be named **views-view-field--{field\_name}.tpl.php** be in the adefault theme folder you could check: **views -\> advanced -\> Theming information** and rescan templates button.

Copy the file **views-view-field.tpl.php** and read its docs for variables available.
> 1 votes

---
Tags: google-maps, search, views
---


title: Views custom style

text:
# Question
Title: Views custom style
I have a field collection displayed in a view. Currently, it renders it this way:

I'd like to render all items in one green box though, not all items in a box seperately. I thought I would be able to do this using "style settings" in the view settings.

However, this doesn't seem to work. I've tried all different options, but the class I provide is NOT added in the elements and so the display doesn't change.

Why doesn't that work? Am I wrong by using style settings to achieve this?

# Answer
Add a class to your view by doing this:
> 1 votes

# Answer
In your View

**Click on your Field Collection Field and scroll down to the setting "Multiple Field Settings".**

Select "Display all values in the same row". That should do the trick.
> 0 votes

# Answer
Could you share a screenshot of your settings? However, in the Format section i would go to settings and group my fields. Then add a class for each row, right after Grouping setting
> 0 votes

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


# Question
Title: Problem updating node module from drupal 6 to drupal 7
I am trying to update my drupal version from 6 to 7. I have a problem, I use the next link http://localhost/drupal6/update.php and when the process said "Updating node module" it never finish.

I use WAMPSERVER in WINDOWS 8.1

# Answer
> 0 votes
The problem seems to be with the Locale module. I would suggest disabling the Locale module in D6, running the D7 update.php, then enabling Locale and running update.php again.

---
Tags: migrations, updating
---


title: Show forms in a modal window

text:
# Question
Title: Show forms in a modal window
I have a form and I am using Drupal 7. I need to show this form in a popup when a user clicks a link. The user should then be able to complete the form whilst in the pop up window. I can use anything like Colorbox or modals or anything. I just wanted to know which is the better option and what options do I have for Drupal.

# Answer
> 10 votes
There's 2 good options I know of currently: iframe (in colorbox for example) and CTools. Which option to use depends of the circumstances. I guess this information I found in the CTools modal.html file brings out the main difference:

> CTools provides a simple modal that can be used as a popup to place forms. It differs from the normal modal frameworks in that it does not do its work via an iframe. This is both an advantage and a disadvantage. The iframe simply renders normal pages in a sub-browser and they can do their thing. That makes it much easier to put arbitrary pages and forms in a modal. However, the iframe is not very good at actually communicating changes to the main page, so you cannot open the modal, have it do some work, and then modify the page.

I have no personal experienced with CTools on this subject so I can't add anything else to that, but I've implemented the iframe method in a couple of projects. In the most recent one I used the Colorbox plugin to show a few forms created with the Webform module in a popup. I'll add some example code here in case there's some interest.

Link to the form:

```
<a class="colorbox_form" href="'.url('node/5').'">'.t('Send message').'</a>

```

Javascript code to open the linked address in a popup:

```
if ($('a.colorbox_form').length > 0) {
  var link = $("a.colorbox_form").attr('href');
  link = link.concat('?colorbox=true');
  // colorbox=true is attached for later use (read below).
  $("a.colorbox_form").attr('href', link);
  $("a.colorbox_form").colorbox({iframe:true, width:500, height:450});
}

```

In the theme template file:

```
function mytheme_preprocess_page(&$variables) {
  // Different template and additional stylsheet for colorbox content.
  if (isset($_GET['colorbox']) && $_GET['colorbox'] == TRUE) {
    $variables['theme_hook_suggestions'] = array('page__iframe'); // page--iframe.tpl.php
    drupal_add_css(path_to_theme() .'/iframe.css');
    $variables['styles'] = drupal_get_css();
  }
}

```

I attached 'colorbox=true' to the links using javascript so that users with javascript turned off would see the form with the normal template. The iframe template only has messages, title and content printed.

This already works, but I ran into a issue with Webforms: 'colorbox=true' wasn't preserved when the form got submitted. My attempt to fix it:

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if (isset($_GET['colorbox']) && $_GET['colorbox'] == TRUE) {
    // The id-s of the forms that are possibly shown within a popup.
    $form_ids = array('webform_client_form_2', 'webform_client_form_4');
    if (in_array($form_id, $form_ids)) {
      $form['#submit'][] = 'mymodule_webform_submit';
    }
  }
}

function mymodule_webform_submit(&$form, &$form_state) {
  //drupal_set_message('<pre>'.var_export($form_state['redirect'], TRUE).'</pre>');
  if (!isset($form_state['redirect'])) {
    $form_state['redirect'] = array($_GET['q'], array('query' => array('colorbox' => 'true')));
  }
  else {
    $form_state['redirect'][1]['query'] = array('colorbox' => 'true');
  }
}

```

# Answer
> 8 votes
Use CTools which can insert a form into a modal when a user clicks a link.

Please check the following tutorial: Insert a form into a pop-up modal with CTools and Drupal 7 which simplifies this process in few steps.

Basically you need to define your `hook_menu()` callback for your modal form:

```
$items['mymodule/%ctools_js'] = array(
  'page callback' => 'mymodule_callback',
  'page arguments' => array(1),
  'access callback' => TRUE,
  'type' => MENU_CALLBACK,
);

```

then create a link generator which returns the HTML code:

```
/**
 * Helper function to make a link.
 */
function _mymodule_make_link($link_text = '') {
  // Set a default value if no text in supplied.
  if (empty($link_text)) {
    $link_text = 'Magical Modal';
  }

  return '<div id="magical-modal-link">' . l($link_text, 'mymodule/nojs', array('attributes' => array('class' => 'ctools-use-modal'))) . '</div>';
}

```

so it can be used in your page callback, e.g.:

```
/**
 * An example page.
 */
function mymodule_page() {
  // Load the modal library and add the modal javascript.
  ctools_include('modal');
  ctools_modal_add_js();
  return _mymodule_make_link('Magical modal');
}

```

When user clicks on the link, it makes request either to `/mymodule/ajax` or `/mymodule/nojs` (in case of `nojs`), so the following callback handles creating a modal:

```
/**
 * Ajax menu callback.
 */
function mymodule_callback($ajax) {
  if ($ajax) {
    ctools_include('ajax');
    ctools_include('modal');

    $form_state = array(
      'ajax' => TRUE,
      'title' => t('MyModule Modal Form'),
    );

    // Use ctools to generate ajax instructions for the browser to create
    // a form in a modal popup.
    $output = ctools_modal_form_wrapper('mymodule_form', $form_state);

    // If the form has been submitted, there may be additional instructions
    // such as dismissing the modal popup.
    if (!empty($form_state['ajax_commands'])) {
      $output = $form_state['ajax_commands'];
    }

    // Return the ajax instructions to the browser via ajax_render().
    print ajax_render($output);
    drupal_exit();
  }
  else {
    return drupal_get_form('mymodule_form');
  }
}

```

Now you just need to create a form and its submit handler as below:

```
/**
 * Drupal form to be put in a modal.
 */
function mymodule_form($form, $form_state) {
  $form = array();

  $form['new_link_text'] = array(
    '#type' => 'textfield',
    '#title' => t('Link text'),
  );

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

  return $form;
}

/**
 * Drupal form submit handler.
 */
function mymodule_form_submit(&$form, &$form_state) {
  // Generate the new link using the submitted text value.
  $link = _mymodule_make_link($form_state['values']['new_link_text']);

  // Tell the browser to close the modal.
  $form_state['ajax_commands'][] = ctools_modal_command_dismiss();

  // Tell the browser to replace the old link with the new one.
  $form_state['ajax_commands'][] = ajax_command_replace('#magical-modal-link', $link);
}

```

To test that, go to: `/mymodule/page` where you should see 'Magical Modal' link which should show you the modal form once clicked.

# Answer
> 6 votes
I would start looking at Modal form, instead of Colorbox. It specifically exists because using Colorbox with forms works really bad.

In modal form, Ctools does all the work in background, which has proper support for form handling that just doesn't belong in Colorbox. That also means that if you need to "modal" an unsupported form then you always know that thanks to Ctools there's a solid API behind it that you can switch to instead.

Bonus points for filing a patch with new form support if you write it. ;)

# Answer
> 2 votes
I find that Simple Dialog is a great way to provide forms in Modals. It has the advantage of using jQuery UI which is in core.

All you need to do is provide a link to the form with some additional information. It provides a simple method based on classes and rel tags, or a theme method for more fine-tuned control. I've done this in two ways:

1. The Menu Attributes module to provide the required rel and class tags.
2. theme\_menu\_link to override menu link render functions.

# Answer
> 2 votes
The module you need is https://drupal.org/project/popup\_forms, but you need to do some programming in order to apply it (i.e. it can't be just configured via admin interface).

---
Tags: 7, forms
---


title: Comment Permissions

text:
# Question
Title: Comment Permissions
I am using advanced forums and I would like my site admins to be able to edit and delete forum comments.

The correct permissions are checked and the site admins can edit and delete comments by going into content-\>comments.

However, I would like to have a button on the comment that allows the admins to directly edit the comment.

Current these buttons exist for the original topic post, but not the corresponding comments.

For example, the admins have these options on a topic post.

However, on a comment the admins only have these options.

# Answer
You can install Quick Edit module which allows content to be edited in-place.
> 1 votes

# Answer
You can create a custom `comment.tpl.php` in your theme directory and insert any link in there for any user. for example create link `<a href='www.example.com/commend/[comment_id]/edit'>edit</a>`

Notice that the comment id is available via `hook_preprocess_comment()`. you can set this ID in a variable and use it in the `comment.tpl.php`
> 0 votes

---
Tags: users, comments
---


title: Alter list of blocks on admin page

text:
# Question
Title: Alter list of blocks on admin page
I'm using Drupal 8.

I need to hide blocks of certain type from blocks UI because I'm managing them from my custom module and I'm not using them as a regular blocks.

Is there any way of altering block list generated on blocks administrative page?

# Answer
@David Thomas's answer might be correct if you want to hide blocks from actual regions.

But, if you want to hide blocks from Block UI listing `/admin/structure/block` than you have to alter `block_admin_display_form` using hook\_form\_alter()

Here is what I did for my case:

```
function MY_MODULE_NAME_form_alter(
  &$form,
  \Drupal\Core\Form\FormStateInterface $form_state,
  $form_id
) {
  if ($form_id == "block_admin_display_form") {
    foreach ($form['blocks'] as $key => $block) {
      if (!empty($block['operations']['#links']['edit']['url'])) {
        $block_plugin_id = $block['operations']['#links']['edit']['url']->getOptions()['entity']->getPluginId();
        if ($block_plugin_id == 'MY_CUSTOM_BLOCK_PLUGIN_ID') {
          unset($form['blocks'][$key]);
        }
      }
    }
  }
}

```

This is the only way I could found by far. If anyone has better solution please share.
> 0 votes

# Answer
You could try using `hook_block_access` to restrict access to block operations.

> Control access to a block instance.
>
> Modules may implement this hook if they want to have a say in whether or not a given user has access to perform a given operation on a block instance.
>
> string $operation: The operation to be performed; for instance, 'view', 'create', 'delete', or 'update'.
> 1 votes

# Answer
Given that you're also asked Check if block is visible, I kind of know what you're trying to do.

This isn't really an answer to your question, but I'm wondering if you're on the wrong track with what you are doing.

I don't fully understand why you are using blocks to do what you want in the first place. But assuming that using block plugins is the right thing, block config entities might not be.\*

Block plugins are very flexible and designed to be re-usable, e.g. in page\_manager/panels, in a completely different way. Block config entity however are not meant to be re-usable like this at all. They have a very specific purpose. To be displayed in a theme region of a specific theme, based on a set of visibility conditions. Trying to (mis-) use them for a different purpose will lead you into corners like this one.

You might want to consider storing block configuration in your own entity type. You could extend from block to get most of its logic but have your own list page to manage them, and then they would be a completely different thing than normal blocks for Drupal and you don't have to worry about them being used/showing up in places you don't expect. For example, even if you hide them in the UI, the block system will still prepare any accessible block and make them available in the configured theme region.

* And since your code example seems to hardcode a specific block plugin, maybe you don't want to use block plugins at all?
> 1 votes

---
Tags: blocks, 8
---


# Question
Title: "Unable to to find SQL Class. Drush cannot find your Database connection details."
Just started with drupal and drush CLI but having problems already!
Here is my error:

```
$ drush si --debug --db-url =mysql://USERNAME:PASSWORD@HOST/DATABASE/drushfun
Starting Drush preflight. [0 sec, 1.29 MB]                                                                                [preflight]
Cache HIT cid: 7.1.0-commandfiles-0-33a837c10472909bafe9ab29823ddb79 [0.01 sec, 1.32 MB]                                                                                [debug]
Bootstrap to phase 0. [0.06 sec, 3.52 MB]                                                                                [bootstrap]
Bootstrap to phase 1. [0.06 sec, 3.52 MB]                                                                                [bootstrap]
Drush bootstrap phase : bootstrap_drupal_root() [0.06 sec, 3.73 MB]                                                                                [bootstrap]
Initialized Drupal 7.41 root directory at /home/USER/Documents//drupal-7.41fun [0.06 sec, 3.73 MB]                                                                           [notice]
Find command files for phase 1 (max=1) [0.07 sec, 2.71 MB]                                                                                [debug]
Cache HIT cid: 7.1.0-commandfiles-1-b9de3821d4a21c5d43292e8f9d7ffd3d [0.07 sec, 2.71 MB]                                                                                [debug]
Found command: site-install (commandfile=site_install) [0.07 sec, 2.71 MB]                                                                                [bootstrap]
Calling hook drush_core_site_install_validate [0.09 sec, 3.75 MB]                                                                                [debug]
Returned from hook drush_core_site_install_validate [0.09 sec, 3.75 MB]                                                                                [debug]
Calling hook drush_core_pre_site_install [0.09 sec, 3.76 MB]                                                                                [debug]
exception 'Drush\Sql\SqlException' with message 'Unable to find a matching SQL Class. Drush cannot find your database connection details.' in                                                     [error]
/home/USER/.composer/vendor/drush/drush/commands/sql/sql.drush.inc:597
Stack trace:
#0 /home/USER/.composer/vendor/drush/drush/commands/sql/sql.drush.inc(582): drush_sql_get_class(Array)
#1 /home/USER/.composer/vendor/drush/drush/commands/core/site_install.drush.inc(107): drush_sql_get_class()
#2 [internal function]: drush_core_pre_site_install('=mysql://root:r...')
#3 /home/USER/.composer/vendor/drush/drush/includes/command.inc(359): call_user_func_array('drush_core_pre_...', Array)
#4 /home/USER/.composer/vendor/drush/drush/includes/command.inc(210): _drush_invoke_hooks(Array, Array)
#5 [internal function]: drush_command('=mysql://root:r...')
#6 /home/USER/.composer/vendor/drush/drush/includes/command.inc(178): call_user_func_array('drush_command', Array)
#7 /home/USER/.composer/vendor/drush/drush/lib/Drush/Boot/BaseBoot.php(62): drush_dispatch(Array)
#8 /home/USER/.composer/vendor/drush/drush/drush.php(70): Drush\Boot\BaseBoot->bootstrap_and_dispatch()
#9 /home/USER/.composer/vendor/drush/drush/drush.php(11): drush_main()
#10 {main} [0.09 sec, 3.78 MB]
Command dispatch complete [0.09 sec, 3.75 MB]                                                                                [notice]
$

```

Here is what i have so far:

```
$ drush status
Drupal version         :  7.41
Site URI               :  http://default
PHP executable         :  /usr/bin/php
PHP configuration      :  /etc/php5/cli/php.ini
PHP OS                 :  Linux
Drush script           :  /home/USER/.composer/vendor/drush/drush/drush.php
Drush version          :  7.1.0
Drush temp directory   :  /tmp
Drush configuration    :
Drush alias files      :
Drupal root            :  /home/USER/Documents/drupal-7.41fun
Site path              :   sites/default

```

Why do i have that error? Am i missing something? Need to be able to work from the CLI.

```
$ php -v
PHP 5.6.17-1+deb.sury.org~precise+1 (cli)
Copyright (c) 1997-2015 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2015 Zend Technologies
with Zend OPcache v7.0.6-dev, Copyright (c) 1999-2015, by Zend Technologies

$ mysql --version
mysql  Ver 14.14 Distrib 5.5.46, for debian-linux-gnu (i686) using readline 6.2

mysql> SELECT VERSION();
+-------------------------+
| VERSION()               |
+-------------------------+
| 5.5.46-0ubuntu0.12.04.2 |
+-------------------------+

```

# Answer
> 2 votes
Drush options are space separated, so this:

```
drush si --debug --db-url =mysql://USERNAME:PASSWORD@HOST/DATABASE/drushfun

```

Just needs to be:

```
drush si --debug --db-url=mysql://USERNAME:PASSWORD@HOST/DATABASE/drushfun

```

(no space between `--db-url` and `=`)

---
Tags: 7, drush
---


# Question
Title: How to override aggregator_block_view() in the aggregator module?
Can anyone tell me how to override aggregator\_block\_view in the aggregator module?

I have a feed I need to alter the html for and at the moment aggregator just turns the output into an unordered list.

I tried altering it in hook\_item\_list() but there was nothing for me to lock onto to identify the list as coming from the aggregator module.

# Answer
> 2 votes
IF you want to alter the block view you can try hook\_block\_view\_alter

Refer to menu block alter example for an example

http://api.drupal.org/api/drupal/modules%21menu%21menu.module/function/menu\_block\_view\_alter/7

---UPDATE---

```
  function hook_aggregator_process($feed) {
      foreach ($feed->items as $item) {
        mymodule_save($item);
      }
    }

```

Check out the docs at http://api.drupal.org/api/drupal/modules%21aggregator%21aggregator.api.php/function/hook\_aggregator\_process/7

Also enable the aggregator settings at admin/config/services/aggregator/settings

----UPDATE-----

Also if you just want to override the item list then you should use `themename_preprocess_aggregator_summary_items(&$variables)` and check for 'summary\_list' this holds the items list. For more details refer to `template_preprocess_aggregator_summary_items` in the `aggregator.pages.inc` file.

# Answer
> 1 votes
UPDATED

My initial answer was off. You may use the following to adjust the html around an individual item in your Feeds Aggregator Block:

```
/**
 * Returns HTML for an individual feed item for display in the block.
 *
 * @param $variables
 *   An associative array containing:
 *   - item: The item to be displayed.
 *   - feed: Not used.
 *
 * @ingroup themeable
 */
function theme_aggregator_block_item($variables) {
  // Display the external link to the item.
  return '<a href="' . check_url($variables['item']->link) . '">' . check_plain($variables['item']->title) . "</a>\n";
}

```

This resides in `aggregator.module`. This still doesn't get at modifying `aggregator_block_view()` which is what puts the 'item' wrapping around each feed item. I guess you could do a `hook_block_view($delta= '[the delta of the block you want to modify]')` and then copy the contents of the `aggregator_block_view` and modify the part where `theme('item_list')` is used and replace it with one of the other default wrappers (see some here http://api.drupal.org/api/drupal/modules%21system%21theme.api.php/group/themeable/7) or create your own?

# Answer
> 0 votes
You don't need to override the block that is automatically provided by Aggregator. Much easier to make your own block using Views.

1. Go to Views -\> Add a New View
2. Show Aggregator Item
3. You can uncheck 'create a page' and check 'create a block' if you only want a block.
4. Give the block a name and Continue & edit
5. Under Fields, add the Aggregator Title and any other fields you want.

If you have multiple feeds, give them categories in the Aggregator settings (admin/config/services/aggregator), and then filter by category ID within the view.

---
Tags: 7, hooks, feeds, blocks
---


title: Authentication by MAC address

text:
# Question
Title: Authentication by MAC address
I want to show a view only to users who use authenticate devices. My plan is to add a custom user field users, populate it with the MAC address, and send the MAC address to the view. If the MAC address is valid, show the view content.

I don't know how to authenticate on the view side.

Is there any, module, custom code, or something else to check if the MAC address is valid?

# Answer
> 1 votes
You will have to override the `access callback` used for your view pages using an `hook_menu_alter` implementation (from a custom module) to use a custom one that will do the MAC address check.

Assuming the MAC address is provided as an HTTP header, this would look like.

```
/**
 * Implements hook_menu_alter().
 */
function MODULE_menu_alter($items) {
  if (!isset($items['protected/view/path']['access arguments'])) {
    $items['protected/view/path']['access arguments'] = array($items['protected/view/path']['access callback']);
  }
  else {
    array_push($items['protected/view/path']['access arguments'], $items['protected/view/path']['access callback']);
  }
  $items['protected/view/path']['access callback'] = 'MODULE_menu_access';
}

/**
 * Return whether or not the request contains an authorized MAC address header.
 */
function MODULE_menu_access() {
  $mac_address = $_SERVER['HTTP_MAC_ADDRESS'];

  // Validate the MAC address.
  if (!MODULE_mac_is_authorized($mac_address)) {
    return false;
  }

  // Return the result of the original access callback
  $args = func_get_args();
  $access_callback = array_pop($args);
  return call_user_func_array($access_callback, $args);
}

```

---
Tags: views
---


# Question
Title: Contact form - Custom fields are not sending content
I've done a custom contact form with 2 more fields, but I can't get values of those 2 custom fields.

I modified contact.module in core to see what are coming from form submit, found my custom fields but they are empty. I just don't know why they are empty.

**Value of contact\_form in contact.module:**

```
$contact_form = {"contact_form":[{"target_id":"feedback"}],"uuid":[{"value":"5470b680-99db-4d5a-8c00-ae043dce67e1"}],"langcode":[{"value":"pt-br"}],"name":[{"value":"Name"}],"mail":[{"value":"some@mail.com"}],"subject":[{"value":"Any"}],"message":[{"value":"Any message"}],"copy":[{"value":0}],"recipient":[],"field_customa":[],"field_customb":[]}
;

```

Any clues to make this contact form work?

# Answer
Drupal 8 will handle custom fields on contact forms 'out-the-box', they will be rendered in the message body by contact module. If custom fields don't appear in message body, someone messed up.

In this particular case, attribute 'name' of 'input' html tags were modified, and $\_POST came with a wrong schema. $\_POST\['field'\] instead of $\_POST\['field'\]\[0\]\['value'\].

Here shows the hint:
`"message":[{"value":"Any message"}]` \- Correct (field\[0\]\['value'\])
`"field_customa":[]` \- Wrong (field\[\])
> 1 votes

---
Tags: 8, emails
---


# Question
Title: Display the taxonomy term name in the page.tpl from a node
I want to show the term name in the header for every node. Whats the best way, espacially if the node has 2 fields with taxonomy terms and the page is in different languages.

This display nothing, but gives me also no errors:

```
<?php if ( !empty($node) && $node->type == 'content-type') {
  print render(field_custom('node', $node, 'field_custom', array('label'=>'hidden', )));
}
?>

```

**EDIT**

preprocess\_node:

```
global $language;
$wrapper = entity_metadata_wrapper('node',$variables['node']);
$variables['term1'] = $variables['term1'] ->language($language->language)->field_term_ref->value()->name;

```

page.tpl.php:

```
<?php print $term1 ?>

```

I don\`t get any term name.

# Answer
This is the 1st Solution, but the terms aren\`t translated with -\> i18n\_taxonomy\_term\_get\_translation($term, $language).

**EDIT**

The translation works with -\> i18n\_taxonomy\_localize\_terms($term). The language($language-\>language) in the $wrapper is not necessarry for the name translation:

```
    function MYTHEME_preprocess_page(&$variables) {
      if(arg(0)=="node" && is_numeric(arg(1))) {
        global $language;
        $wrapper = entity_metadata_wrapper('node',$variables['node']);
        $variables['term'] = '';
        if(isset($wrapper->field_term_ref1)) {
          $term = $wrapper->language($language->language)->field_term_ref1->value();
          $translated_term = i18n_taxonomy_localize_terms($term);
          $variables['term'] = $translated_term->name;
        }
        if(isset($wrapper->field_term_ref2)) {
          $term = $wrapper->field_term_ref2->value();
          $translated_term = i18n_taxonomy_localize_terms($term);
          $variables['term'] = $translated_term->name;
        }
      }
    }

```
> 0 votes

# Answer
I would use an entity metadata wrapper for this:

```
// Load the current active language.
global $language;
// Put the node object in a wrapper.
$wrapper = entity_metadata_wrapper('node', $node);
// Get the term object.
$term = $wrapper->language($language)->field_term_ref_1->value();
// Translate the term.
$translated_term = i18n_taxonomy_term_get_translation($term, $language);
// Pass the term name to page.tpl.
$variables['term1'] = $translated_term->name;

// The same for term 2.

// Now you can print them in your page.tpl.
print $term1;

```

Not sure if the language part works, though.
> 1 votes

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


# Question
Title: Can a student gradebook be created without a custom module?
I'm confused about when I need to build a module. I'm using Drupal 8. If I create a content type of a student, class, grades and so on, can that be done without a custom module? Can it be done solely with content type and views?

# Answer
I think no. You need content type and views as you write. I think that you also need to use taxonomy (for year and class) so you can assign students to years and class. For calculation you need to write some module, maybe you can do also that in view.

Try the Computed field module.

> Computed Field is a very powerful field module that lets you add a custom "computed fields" to your content types. These computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal, including other fields, the current user, database tables, you name it. (Feeling the power yet? :) ) You can also choose whether to store your computed field values in the database with other content fields, or have them "calculated" on the fly during node views. (Although you should note that Views use requires database stored values.) This field is literally the Swiss Army knife of fields. So start cooking up your PHP based values!
> 1 votes

---
Tags: nodes
---