# Question
Title: How to install a third party library for Printable module using composer (D8)?
I installed the "Printable" module but it doesn't work. When I try to configure the PDF for the Printable module it says:

"You are seeing no PDF generating tool because you have not installed any third party library using composer".

# Answer
> 1 votes
This depends on how you have installed your Drupal site. There is a long description on how to use composer on Drupal.org handbook section.

The short version is this:

* If you have installed Drupal 8 as you did with Drupal 7 using composer\_manager module (which is depricated now)
* If you have installed Drupal 8 using composer, you can require Drupal modules using composer, which automatically will download dependcies (assuming module developers has done their job by adding this information in their module's composer.json file)

---
Tags: 8, installation
---


# Question
Title: When a module has a composer dependency, should it be automatically installed when the module is installed?
Trying to resolve a debate - if a drupal site that is configured correctly installs a module with a composer dependency, should I expect the composer dependency to be installed automatically during the install?

The other person thinks that modules with composer dependencies have to be installed through command line to work, I think that if things were configured correctly it should happen on its own.

Does someone know how it should work?

# Answer
> 3 votes
If you install the module with composer, yes, dependencies will be fetched. If you download the tar and put it in the site, it will not.

---
Tags: 8, composer
---


# Question
Title: Commerce Kickstart 2 Collection - Displaying too much information
I'm having an issue, for some reason, the collection page is displaying the product detail, included with the add to cart. Where would I adjust this setting? I was comparing with another product variation, and can't seem to fix this issue.

# Answer
> 0 votes
I was able to finally fix this. I fixed this issue by going into Content Types, and just adjusted the Manage Display setting under Product List.

---
Tags: commerce
---


title: Password reset causes a 404 error

text:
# Question
Title: Password reset causes a 404 error
When users try to reset their passwords clicking on *Reset your password*, they are fine until they click on the *Log in* button that shows a message similar to the following one.

> This is a one-time login for foobar and will expire on Tue, 20/09/2016 - 15:25. Click on this button to log in to the site and change your password. This login can be used only once.

When users click on the log in button, they get a 404 error, for a page whose URL is similar to http://example.com/user/reset/123/1474293937/ukVdmEMWoYablzZHPYJzMa30-p\_skkDv06d564V1KHQ/admin.

Users are logged in and they edit their account to change password. I don't like that users get a 404 error page, which could confuse them.

Why do users see a 404 error?

# Answer
> 1 votes
Something is intercepting the submission to the user password reset form.

The form should post to the `user.reset.login` route (**/user/reset/{uid}/{timestamp}/{hash}/login**), handled by `UserController::resetPass()`, then redirect to **/user/{uid}/edit?pass-reset-token={TOKEN}**.

This could be a number of different things which you'll have to troubleshoot (e.g. Rules performing some redirect logic on login, an altered form submit handler, Apache redirect, a module performing some redirect logic on a subscribed event, etc.).

Given that the destination URL is essentially appending "/admin" to password reset form URL that should probably clue you in on what is causing the problem.

---
Tags: 8, authentication-authorization
---


title: Render Content Labels and Values

text:
# Question
Title: Render Content Labels and Values
In my node--content\_type.html.twig template file, I can output both the label AND value of a field by using:

```
{{ content.field_title }}

```

I can also render just the label of a field with:

```
{{ content.field_title['#title'] }}

```

So far, so good.

However, how can I output only the VALUE of a field using the content array? I've tried:

```
{{ content.field_title['#value'] }}

```

And:

```
{{ content.field_title.value }}

```

To no avail.

Thank you for any help.

# Answer
To get the field value **without the label**:

`{{ content.field_name[0] }}`

> ### BONUS
>
> If your field allows for multiple values, just increase the 0 to get the other values.
>
> `{{ content.field_name[1] }}` `{{ content.field_name[2] }}` ... and so on.
> 5 votes

# Answer
I've created this module that lets you print the field label and field value individually: https://www.drupal.org/sandbox/sutharsan/2763183

`<strong>{{ content.field_name|field_label }}</strong>: {{ content.field_name|field_value }}`

Let me know if it is useful to you I will promote it to a full project.
> 2 votes

# Answer
You could use `{{ dump(your_field) }}` which debug show all value in field. Remember you need setting Debugging Twig template
> 0 votes

---
Tags: theming, entities, 8
---


title: Template Files - PHP or HTML

text:
# Question
Title: Template Files - PHP or HTML
I notice most (if not all) templates are written in HTML with PHP snippets where required.

I've been writing a few PHP heavy templates, and instead of writing HTML and encasing almost every line in tags, I have opted for writing PHP, using the print function to render HTML.

Is there any reason I should be writing in mostly HTML instead?

I imagine there's more overhead using PHP to render the HTML, but is there enough to worry about?

Second to that, is there any reason templates encase every line in tags instead of just the opening and closing tags are required?

e.g.

```
<?php if($a == $b) {?>
   <?php print 'a equals b';?>
<?php } else {?>
   <?php print 'a does not equal b';?>
<?php } endif;?>

```

vs

```
<?php if($a == $b) {
   print 'a equals b';
 } else {
   print 'a does not equal b';
 } endif;?>

```

# Answer
Overhead, if there is any, is of little concern. This is pretty much a stylistic concern. As such, the important part is a *consensus among developers* so there is clear readability expectations.

drupal.org has documentation when it comes to template coding standards. In this case, little-as-possible PHP tags usage is preferred (the concern here is readable HTML rendering, not code execution) with use of PHP's alternative control structure:

```
<?php if ($a == $b):?>
   a equals b
<?php else: ?>
   a does not equal b
<?php endif; ?>

```

See the documentation for further style guidelines with templates.
> 1 votes

---
Tags: theming
---


# Question
Title: How do I create an uncacheable field plugin base?
I created a custom field plugin base for show an additional data column in a view.

In my FieldPluginBase Class, I define the value of my additional data column for each row of my view (one row equal one node). The datas depends some node parameter.

My problem is users can often changes nodes parameters, but when the user access to my view after change a parameter of a node, the additional column show old data.

I notice when I clear website cache, the view show the new value.

This is the code of my class, can you tell me what must I do for the view shows all the time the newest value of the node in my field plugin base ?

```
class MyFieldPluginBaseCustom extends FieldPluginBase {

    ...
    public function render(ResultRow $values) {
        //do some work with the current node (the current row view)
        if(node_parameter_test_isOK() == true)
            return "string A";
        }
        else{
            return "string B";
        }
    }

    // 0 : the view shows a list of node
    // the view ;
    // (nodeid - mycustom Field Plugind)
    // node1 - "string B"
    // node2 - "string A"
    // node3 - "string B"
    ...
    // nodeN - "string B"

    // 1 : a user change the parameter of the node3

    // (2) : then, when the user access to the view page, the view must show
    // node1 - "string B"
    // node2 - "string A"
    // node3 - "string A"
    ...
    // nodeN - "string B"

    // 2 : However, the view hasn't been updated and show again (unless I clear caches via drush cr by example)
    // node1 - "string B"
    // node2 - "string A"
    // node3 - "string B" // row not updated
    ...
    // nodeN - "string B"
    ...
}

```

# Answer
> 1 votes
May be you can try :

```
use Drupal\Core\Cache\CacheableDependencyInterface;
use Drupal\views\Plugin\views\field\UncacheableFieldHandlerTrait;

class MyFieldPluginBaseCustom extends FieldPluginBase implements CacheableDependencyInterface  {

    ...
    public function render(ResultRow $values) {
        //do some work with the current node (the current row view)
        if(node_parameter_test_isOK() == true)
            return "string A";
        }
        else{
            return "string B";
        }
    }
  public function getCacheMaxAge() {
    return 0;
  }
  public function getCacheContexts() {
    return [];
  }
  public function getCacheTags() {
    return [];
      }
}

```

---
Tags: views, 8, entities, caching
---


# Question
Title: Views image fields render slow causing overlaping results
I have a view displaying some content fields including images being used as the background. I also have 2 attachments with the same fields.

When i visit the page for the first time, or when i do a hard refresh of my browser (hold shift and refresh) the main content and the two top attachments squish together. if i then refresh all looks ok.

Im using bootstrap theme as my base theme. If I disable my CSS file, the error still occurs.

I was thinking it had something to do with the image resizing and loading later than the text content.

Please let me know if you need more information.

http://dev-tangrm-test.pantheonsite.io/

# Answer
> 0 votes
This is not a views or a Drupal issue...

Things to do are:

1. Make sure the image size in terms of KiloBytes is not huge. If you have fairly large sizes this will affect your site speed in general, especially on mobile devices.
2. Make sure you are using an appropriate Image Style. Meaning the size of the image you are rendering, in terms of pixels is not bigger than the container you are rendering in it.
3. In any case to remove this overlapping effect set a static height to the container the image is rendering into. In this way the text is not going to overlap even if the images are still rendering.

Hope this helps.

---
Tags: views, theming
---


# Question
Title: How to wildcard cache clear in Drupal 8?
In Drupal 7, we used to be able to do this:

```
cache_clear_all('state:', 'cache', TRUE)

```

which would delete any cache bin entires that *started* with the string `state:` (matching cache IDs such as `state:info` and `state:nebraska`).

The change record at https://www.drupal.org/node/1272696 even notes this use case in the Drupal 7 example, but does not actually provide an example of how to replicate it in D8.

It seems that we're supposed to use cache tags, which seems like a more more expensive conversion considering the simple use case. I don't see any matching methods that would apply in CacheBackendInterface. Note, this is not about deleting all items in a cache bin, which is clearly covered by deleteAll().

# Answer
> 9 votes
Not sure why the existing answer was deleted, it was (almost) correct.

Wildcard cache clears was removed. It was extremely complicated to support in backends like redis and memcache, which have no wildcard support.

Cache tags is the replacement and it is not that complicated to use. You just pass along a list of strings as the 4th argument (a bit annoying that you have to set the default timestamp argument, a separate method would be nice):

```
\Drupal::cache('default')->set('state:info', $your_data, Cache::PERMANENT,
['state']);

```

and then call:

```
\Drupal\Core\Cache\Cache::invalidateTags(array('state'));

```

---
Tags: 8, caching
---


# Question
Title: Different image width on a node and on block
I noticed that there are differences in the way inline images are displayed when added to 'Body' of the 'Basic Page' and 'Body' of a 'Basic block'. In the first case the image is internally scaled down to match the width of the container (added attribute 'width=909' \[screenshot 1\]) whilst in the second case the image spills out over the element \[screenshot 2\]

I looked at image styles and field display options but couldn't figure out what is causing this behaviour. I'd like to preserve the scaling of the 'Basic Page' for the blocks. Has anyone else come across this issue? I'm running Drupal 8.1.9.

EDIT 1: @Smalution I checked the region width, too. Both 'region-content' and my custom region are 940px wide (descendants of 'col-sm-12')

# Answer
> 0 votes
You can always make the image fit the container with CSS.

For example:

```
.block .content img {
  max-width: 100%;
  height: auto;
}

```

If you're using Bootstrap, you can achieve the same effect by adding the class `img-responsive` to the image.

---
Tags: 8, media
---


# Question
Title: How to view "your own comments" without the permission view comments?
In Drupal there is a permission "view comments" and "add comments". I would like to activate "add comments" and disactivate "view comments". How to allow to view your own comments for users? It's a little bit strange to publish comments and they disappear into nowhere.

# Answer
> 3 votes
I think this kind of logic is better handled in a custom module instead of the theme layer. Something like this might work for you:

```
/**
 * Implements hook_permission().
 */
function mymodule_permission() {
  return array(
    'view own comments only' => array(
      'title' => t('View only own comments'),
      'description' => t('The user will not see comments made by other users.'),
      'warning' => t('Sometimes this might not work...'),
    ),
  );

}

/**
 * Implementation of hook_query_TAG_alter()
 */
function mymodule_query_comment_filter_alter(QueryAlterableInterface $query) {
  if (user_access('view own comments only') && !user_access('administer comments')) {
    $query->condition('c.uid', $GLOBALS['user']->uid);
  }
}

```

This defines a view own comments only permission. If this is set and the user does not have the administer comments permission, comments made by other users will be hidden on the node page.

There are a few problems with this solution (and you'll probably have the same problems if you are trying to do this in a template file):

* comment count will not be modified
* Recent comments block will not be modified

# Answer
> 2 votes
I would leave the 'view comments' permission on, and put some code in my comment.tpl.php file to test for ownership of the comment.

The default theme file looks like this:

```
/** 60 lines of useful information about available parameters */

<div class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>
  <?php print $picture ?>

  <?php if ($new): ?>
    <span class="new"><?php print $new ?></span>
  <?php endif; ?>

  <?php print render($title_prefix); ?>
  <h3<?php print $title_attributes; ?>><?php print $title ?></h3>
  <?php print render($title_suffix); ?>

  <div class="submitted">
    <?php print $permalink; ?>
    <?php print $submitted; ?>
  </div>

  <div class="content"<?php print $content_attributes; ?>>
    <?php
      // We hide the comments and links now so that we can render them later.
      hide($content['links']);
      print render($content);
    ?>
    <?php if ($signature): ?>
    <div class="user-signature clearfix">
      <?php print $signature ?>
    </div>
    <?php endif; ?>
  </div>

  <?php print render($content['links']) ?>
</div>

```

Put a copy of the file into your theme's templates directory (and reference it in your theme settings if required). Then alter the file so that the entire section is wrapped in an **if** statement.

I don't know exactly where the uids of the author and user are stored, you can use the devel module to find that out, simply put `<?php dpm($author); ?>` in the template file somewhere once you've install devel and you'll see the structure of the $author variable. I have a **hunch** it might be `$author->uid` and `$user->uid`, in which case you can do this:

```
/** 60 lines of useful information about available parameters */

<?php
 global $user;
 if(author->uid == $user->uid):
?>

// everything from line 61 to 92 in here

<?php endif; ?>

```

# Answer
> 0 votes
```
  Here I am using content type name (Custom Comments).
  comment.tpl.php file copy code and past it here
  comment--node-custom_comments.tpl.php

   <?php
     global $user;
     if($comment->uid == $user->uid):
   ?>

   // everything from comment.tpl.php code  copy and past here

  <?php endif; ?>

```

---
Tags: comments
---


# Question
Title: Is there a drush command to set permissions to true on ALL modules for administrator?
I'm getting tired of having to go in the backend and click on some new module's permissions so that I can use them...

Is there a drush command to enable permissions to true on ALL modules in on shot?

This happens on some modules and also when creating content types or using beans or new panels.

# Answer
> 0 votes
You need to look this Permissions API

```
$ drush help perm-grant
Grant permissions to a role.

Examples:
drush perm-grant --roles="Admin"          Grant all permissions provided by the Node module to the Admin role.
--modules="node"
drush perm-grant --all-modules            Grant all permissions to Admin role.
--roles-="Admin"
drush perm-grant --roles="Editor,Copy     Grant "administer nodes" to Editor and Copy Editor roles.
Editor" --permissions="administer nodes"
drush perm-grant --all-roles              Grant "administer nodes" permission to all roles.
--permissions="administer nodes"

Options:
--all-roles                               Grant the permissions to all defined roles.
--roles                                   Comma-separated list of roles to grant permissions to.
--permissions                             Comma-separated list of permissions to grant to a role or roles.
--modules                                 Comma-separated list of modules providing permissions to grant.
--all-modules                             Grant all defined permissions to a role or roles.

$ drush help perm-revoke
Revoke permissions from a role.

Examples:
drush perm-revoke --roles="Admin"         Revoke all permissions provided by the Node module from the Admin role.
--modules="node"
drush perm-revoke --all-modules           Revoke all permissions from the Admin role.
--roles-="Admin"
drush perm-revoke --roles="Editor,Copy    Revoke "administer nodes" from the Editor and Copy Editor roles.
Editor" --permissions="administer nodes"
drush perm-revoke --all-roles             Revoke "administer nodes" permission from all roles.
--permissions="administer nodes"
drush perm-revoke --reset                 Revoke all permissions from all roles.  Requires confirmation, use with
                                           caution.

Options:
--all-roles                               Revoke the permissions from all defined roles.
--roles                                   Comma-separated list of roles to revoke permissions from.
--permissions                             Comma-separated list of permissions to revoke from a role or roles.
--modules                                 Comma-separated list of modules providing permissions to revoke.
--all-modules                             Revoke all defined permissions from a role or roles.
--reset                                   Revoke all defined permissions from all roles.  Requires confirmation,
                                           use with caution.

```

---
Tags: users
---


title: Obtaining all values from a built form

text:
# Question
Title: Obtaining all values from a built form
I'm building a form and setting values via

```
$form = \Drupal::formBuilder()->getForm('My\Module', ['key1' => 'x']);

```

where I set the passed `key1` as the default values for the associated fields : in `My\Module\buildForm`, you would find

```
public function buildForm(array $form, FormStateInterface $form_state, $presets = array()) {

    $form['key1'] = [
      '#type' => 'textfield',
      '#default_value' => isset($presets['key1']) ? $presets['key1'] : $query->get('key1')
    ];

    return $form;
}

```

This takes place in a controller not directly related to the form and I'd like to retrieve all values set, either as defaults or as parameters of the page, something like `['key1' => 'x']` if no parameter is passed to the page or `['key1' => 'v1']` if the page is called with `?key1=v1`

How can I get all the values on my form array (besides filtering on the field names)?

# Answer
Probably you put the preset values in the default values of form elements. They are at this point only in `$form`.

The values in `$form_state` are filled after the form is submitted, as a result of a GET/POST request.

But then your code, that calls the formBuilder, has no longer control. This will be handled by the submit method you have defined for the form.
> 1 votes

---
Tags: forms, 8
---


# Question
Title: How to display the term description on top of view
In Drupal 6 the TVI module had an option: "Display term description" "When enabled, the term description is displayed before the rendered view on term page."

Unfortunately I can't find this option to display the term description on top of views page of taxonomy term in the Drupal 7 version of TVI.

Is there any other way to display the term discription on top of the view (the view displays all content/nodes of the specific term). Thank you.

# Answer
> 1 votes
Here is a coding solution, I still find the suggestion from Kevin to be 'cleaner'/'easier'.
Still, for what it's worth:

```
function YOURMODULE_preprocess_views_view(&$vars) {
  if( $vars['name'] == 'taxonomy_term' && $vars['display_id'] == 'page' ){
    $term = menu_get_object('taxonomy_term', 2);
    $term_description = array(
      '#markup' => check_markup($term->description, $term->format, '', TRUE),
      '#prefix' => '<div class="taxonomy-term-description">',
      '#suffix' => '</div>',
    );
    $vars['header'] = drupal_render($term_description) . $vars['header'];
  }
}

```

You should modify the condition(s) to match your view and display. The rest of the code is copied from the `taxonomy_term_build_content()` function of the core taxonomy module.

You should also note that the description is prepended to whatever content is already present in the `header` variable.

Good luck!

# Answer
> 2 votes
I haven't used Drupal 6 since 2010, so I can't speak to what used to be.

There are a few options here, given the differences in Views for 7/8 vs 6.

1. You can attach a field in the view header for the term description.
2. You can create a separate block display, and put that block on any term path.

I usually opt for #2, so I can put the term description and term name in a hero region, and keep the main view output uncluttered. Although you can use TVI in various ways, I stick to creating taxonomy/term/% as the page paths so feeding arguments so it is simple. So for the block, create a contextual filter and feed it the taxonomy term ID from URL.

You could also have the view render the term as a view mode as well, instead of fields. It's pretty flexible.

edit: The reason it shows without using TVI or Views is because the page callback for a term path hardcodes and prepends it: https://api.drupal.org/api/drupal/modules!taxonomy!taxonomy.pages.inc/function/taxonomy\_term\_page/7.x .

That is one of a handful of reasons modules like TVI were created in the first place, so you can arrange your own display(s). Since TVI is injecting a View, it does not hardcode anything into the output:

```
/**
 * Replace taxonomy page callback.
 *
 * If more or less than one term is given then pass the request off
 * to the original taxonomy module page callback.
 *
 * @param int|object $tid
 *   The term tid or the term object.
 * @param null|int $depth
 *   The shown depth.
 *
 * @return array
 *   The build array.
 */
function tvi_render_view($tid, $depth = NULL) {
  if (is_object($tid)) {
    $tid = $tid->tid;
  }

  list($view, $display, $term, $settings) = tvi_get_view_info($tid);
  // Load metatags if needed.
  if (module_exists('metatag')) {
    metatag_entity_view($term, 'taxonomy_term', 'full', NULL);
  }
  if (is_object($view) && $display) {
    $output = t('There was no content found matching this term.');

    if (isset($settings->pass_arguments) && $settings->pass_arguments == 1) {
      // Pass all arguments to views. Exclude /taxonomy/term.
      $args = array_slice(arg(), 2);
    }
    else {
      $args = array($tid);
      if (NULL !== $depth) {
        $args[] = $depth;
      }
    }

    if ($view->display[$display]->display_plugin == 'block') {
      // If it's a block display, views returns a block array which won't work
      // as a page callback so we need to explicitly set the page title
      // and just return the $block['content'].
      $block = $view->execute_display($display, $args);
      drupal_set_title($block['subject']);
      $output = $block['content'];
    }
    else {
      global $language;
      module_invoke_all('entity_view', $term, 'taxonomy_term', 'full', $language->language);
      $output = $view->execute_display($display, $args);
    }

    return $output;
  }

  // Taxonomy is last resort - used if no standard views are found.
  module_load_include('inc', 'taxonomy', 'taxonomy.pages');
  return taxonomy_term_page($term);
}

```

This is easily solvable in a few minutes with either solution above.

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


# Question
Title: Configuration management export blocks from Dev to Staging
I created and placed some blocks in my local Drupal 8 Dev site. I exported the full configuration. After I import the configuration into my Staging site I get this error:

> This block is broken or missing. You may be missing content or you might need to enable the original module

What do I have to do? And what are best practices for exporting blocks from Dev to Staging and keep Configuration management synced and without errors?

# Answer
Another approach for synchronizing content that is added as part of development to test and live environments is to use the Default Content module to export the content. It is built for the content to be exported to an installation profile's 'content' folder, and then the module, if enabled, automatically brings the content in when the site is installed. It is also possible to import the content one item at a time, such as in an update hook, with the below code in your example.install or example.profile:

```
<?php
/**
* Import a piece of content exported by default content module.
*/
function example_import_default_content($path_to_content_json) {
  list($entity_type_id, $filename) = explode('/', $path_to_content_json);
  $p = drupal_get_path('profile', 'guts');
  $encoded_content = file_get_contents($p . '/content/' . $path_to_content_json);
  $serializer = \Drupal::service('serializer');
  $content = $serializer->decode($encoded_content, 'hal_json');
  global $base_url;
  $url = $base_url . base_path();
  $content['_links']['type']['href'] = str_replace('http://drupal.org/', $url, $content['_links']['type']['href']);
  $contents = $serializer->encode($content, 'hal_json');
  $class = 'Drupal\\' . $entity_type_id . '\Entity\\' . str_replace(' ', '', ucwords(str_replace('_', ' ', $entity_type_id)));
  $entity = $serializer->deserialize($contents, $class, 'hal_json', array('request_method' => 'POST'));
  $entity->enforceIsNew(TRUE);
  $entity->save();
}

```

Export a custom block with an ID of 8:

```
drush dcer block_content 8

```

(If you don't set your profile path in Drush settings you'll have to specify it above.)

And use the resultant export in your example.install file like this:

```
<?php
/**
* Add the footer block content.
*
* Implements hook_update_N().
*/
function example_update_8001() {
  example_import_default_content('block_content/136efd63-021e-42ea-8202-8b97305cc07f.json');
}

```

See easily add default content with update hooks for more.
> 1 votes

# Answer
Content blocks are content. Unfortunately, there is currently no mechanism in Drupal core to deploy them.

You'd need something like https://www.drupal.org/project/deploy for that, but that's a pretty big project with a lot of dependencies.
> 0 votes

---
Tags: 8, blocks, configuration
---


# Question
Title: How to change the default term path "taxonomy/term/[tid]"
Am using drupal 7 for my project.

Here am facing for custom url change.

My website url is www.example.com/plans/1. Above url need to change as www.example.com/plan-name.

Pls suggest to me to fix the issue.

# Answer
Please go Configuration-\>search and metadata -\> url aliases -\> pattern.

Check over to the Taxonomy Term Path. If you have created the *plan* as Taxonomy.

Go to the Pattern for the Taxonomy *plan* and then create the URL path of the plan

If you want to display the Id in URL,give plan/\[term:tid\] or taxonomy name give it as plan/\[term:name\].
> 0 votes

---
Tags: views, taxonomy-terms, path-aliases
---


# Question
Title: Views - Clicked element + corresponding content
I have a content type which contains the following fields

* title
* text body
* image

An I need to achieve something like below

The 4-image grid is a view which covers 50% of the page. The green coloured box represents the clicked image. I need the text-area right next to the view to contain the the text corresponding to the image which is clicked.

Is it possible to achieve this using views alone?

# Answer
**Step 1:** Create the View, the block and the required fields (order matters).

Block's instructions (page can be different):

* Format:

+ Grid
    + Number of columns: `2`
* Fields:

+ Nid: Exclude from display
    + Title:

    - Link this field to the original piece of content: `Unchecked`
        - REWRITE RESULTS `->` Rewrite the output of field `->` Output this field as a link `->` Link path: `ajax-link/nojs/[nid]`
        - Link class: `use-ajax`
    + Image:

    - Link image to: `Nothing`
        - REWRITE RESULTS `->` ... Same as "Title"
        - Link class: `use-ajax`

So, the title's or image's `url` should have this structure: `hook-menu-registered-path/nojs/argument`

**Step 2:** Create a custom module and implement the following code.

```
/**
 * Implements hook_menu.
 */
function custom_module_menu() {
  // A menu callback is required when using ajax outside of the Form API.
  $items['ajax-link'] = array(
    'page callback' => '_custom_module_response',
    'access callback' => 'user_access',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 *  Callback function.
 *
 * @param int $nid
 *   Either a valid node id or 0 (zero) if not available.
 *
 *  @param string $type
 *   Either 'ajax' or 'nojs. Type is simply the normal URL argument to this URL.
 *
 *  @return string|array
 *    If $type == 'ajax', returns an array of AJAX Commands,
 *   otherwise, just returns the content, which will end up being a page.
 */
function _custom_module_response($type, $nid = 0) {
  $output = _custom_module_node_load($nid);
  if ($type == 'ajax') {
    $commands = array();
    // Selector: A jQuery selector string, either a .class or #id.
    $commands[] = ajax_command_replace('.selector', '<div class="selector">' . $output . '</div>');
    $page = array('#type' => 'ajax', '#commands' => $commands);
    ajax_deliver($page);
  }
  else {
    $output = isset($output) ? '<div class="no-content">' . $output . '</div>' : t('Node does not exist!');
    return $output;
  }
}

/**
 *  Node loader function.
 *
 *  @return string
 *   The themed node in its define view mode.
 */
function _custom_module_node_load($nid = 0) {
  $node = node_load($nid);
  if ($node) {
    $pre_rendered_node = node_view($node, $view_mode = 'full');
    return theme('node', $pre_rendered_node);
  }
}

```

**Step 3:** Load the necessary library. I chose the `template.php` file to do it.

```
/**
 * Implements template_preprocess_views_view.
 */
function custom_theme_preprocess_views_view(&$vars) {
  $view = $vars['view'];
  if ($view->name == 'my_view_name') {
    // drupal_add_library is invoked automatically when a form element has the
    // '#ajax' property, but since we are not rendering a form here, we have to
    // do it ourselves.
    drupal_add_library('system', 'drupal.ajax');
    $output = '<div class="selector">' . $vars['rows'];
    $output .= '</div>';
    $vars['rows'] = $output;
  }
}

```

Now, should only the body field must be displayed (or a certain set of fields) I suggest the definition of a view mode per case, then define that view mode to the `node_view` function.

---

**Note:**

Ajax framework's "magic" class: `use-ajax`

> By adding the 'use-ajax' class to a link, the link will be loaded via an Ajax call. When using this method, the href of the link can contain '/nojs/' as part of the path. When the Ajax framework makes the request, it will convert this to '/ajax/'. The server is then able to easily tell if this request was made through an actual Ajax request or in a degraded state, and respond appropriately.

**Ref.:** Drupal examples modules, How to use Drupal 7's built-in Ajax Framework
> 1 votes

---
Tags: 7, views
---


title: Should I customize/replace any file?

text:
# Question
Title: Should I customize/replace any file?
When downloading Drupal, I get .htaccess files which contain Apache directives, including security-related configuration directives.

1. Can Drupal 8 work, out of the box, with Nginx?
2. Where are the Nginx files equivalent to the Apache configuration files? If there isn't any file for Nginx, how can I know how to create them?

# Answer
Nginx doesn't support .htaccess files without an extension. You could install that extension, but most don't.

Drupal doesn't include sample rewrite config for Nginx, so there are a few extra steps when setting up the vhost, but nothing major. You'll also need to make sure FPM is set up and configured correctly, but that goes without saying when using PHP with nginx.

There's a pretty sensible looking sample config on the Nginx site itself:

```
server {
    server_name example.com;
    root /var/www/drupal8; ## <-- Your only path reference.

    location = /favicon.ico {
        log_not_found off;
        access_log off;
    }

    location = /robots.txt {
        allow all;
        log_not_found off;
        access_log off;
    }

    # Very rarely should these ever be accessed outside of your lan
    location ~* \.(txt|log)$ {
        allow 192.168.0.0/16;
        deny all;
    }

    location ~ \..*/.*\.php$ {
        return 403;
    }

    location ~ ^/sites/.*/private/ {
        return 403;
    }

    # Allow "Well-Known URIs" as per RFC 5785
    location ~* ^/.well-known/ {
        allow all;
    }

    # Block access to "hidden" files and directories whose names begin with a
    # period. This includes directories used by version control systems such
    # as Subversion or Git to store control files.
    location ~ (^|/)\. {
        return 403;
    }

    location / {
        # try_files $uri @rewrite; # For Drupal <= 6
        try_files $uri /index.php?$query_string; # For Drupal >= 7
    }

    location @rewrite {
        rewrite ^/(.*)$ /index.php?q=$1;
    }

    # Don't allow direct access to PHP files in the vendor directory.
    location ~ /vendor/.*\.php$ {
        deny all;
        return 404;
    }

    # In Drupal 8, we must also match new paths where the '.php' appears in
    # the middle, such as update.php/selection. The rule we use is strict,
    # and only allows this pattern with the update.php front controller.
    # This allows legacy path aliases in the form of
    # blog/index.php/legacy-path to continue to route to Drupal nodes. If
    # you do not have any paths like that, then you might prefer to use a
    # laxer rule, such as:
    #   location ~ \.php(/|$) {
    # The laxer rule will continue to work if Drupal uses this new URL
    # pattern with front controllers other than update.php in a future
    # release.
    location ~ '\.php$|^/update.php' {
        fastcgi_split_path_info ^(.+?\.php)(|/.*)$;
        # Security note: If you're running a version of PHP older than the
        # latest 5.3, you should have "cgi.fix_pathinfo = 0;" in php.ini.
        # See http://serverfault.com/q/627903/94922 for details.
        include fastcgi_params;
        # Block httpoxy attacks. See https://httpoxy.org/.
        fastcgi_param HTTP_PROXY "";
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
        fastcgi_intercept_errors on;
        # PHP 5 socket location.
        #fastcgi_pass unix:/var/run/php5-fpm.sock;
        # PHP 7 socket location.
        fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
    }

    # Fighting with Styles? This little gem is amazing.
    # location ~ ^/sites/.*/files/imagecache/ { # For Drupal <= 6
    location ~ ^/sites/.*/files/styles/ { # For Drupal >= 7
        try_files $uri @rewrite;
    }

    # Handle private files through Drupal.
    location ~ ^/system/files/ { # For Drupal >= 7
        try_files $uri /index.php?$query_string;
    }

    location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
        expires max;
        log_not_found off;
    }
}

```
> 8 votes

# Answer
Drupal works with nginx, but it takes a great deal of research to get it right (and keep it right). If you have the time and resources to do that well many people are very happy with the performance of their sites once up and running.

Because there is no official community supported documentation covering how to setup nginx, you don't get the reassurance that the security team has reviewed the setup (or anyone else really). If you search around you'll find many partial answers, but I've found that all are incomplete in some way and most contain security errors. As Pierre notes in the comment below there is a quiet group that has worked on this for D6 and D7 but not yet for D8.

One of the most common basic issues is that many are focused on getting Drupal to do all the things it is supposed to do (like generate images) but don't prevent things that are supposed to be blocked (like directly accessing .twig or .inc files). The more complex security issues – like recent changes to headers to mitigate certain types of attacks – are totally absent from any examples I've seen for nginx.

Also, if you run many sites you are likely to have times when you need to change the configuration of all your sites, which means an update to all vhosts. With Apache those changes are often just a matter of pushing out the new code base since the .htaccess files update Apache's behavior.
> 3 votes

---
Tags: 8
---


# Question
Title: Load scripts in the head AND bottom of the page?
I need to load head.js in my head and application.js at the bottom of my page. The following seems to stop all my scripts being loaded! Is there a syntax error? Im confused as I used the documentation from here:

https://www.drupal.org/docs/8/theming-drupal-8/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme

```
global:
  version: 1.x
  css:
    base:
      /ui/style.css: {preprocess: false, minified: false}

  js-header:
    header: true
    js:
      /ui/head.js: {preprocess: false, minified: false, weight: '-100'}

  js-footer:
    js:
      /ui/application.js: {preprocess: false, minified: false, weight: '-99'}

```

UPDATE - It appears to me that `header: true` is used to move either all or none of the scripts to the head. Can someone confirm if this is right?

If this is the case, how can I load scripts in both the head and the bottom of the page?

# Answer
> 3 votes
You have to add additional libraries: https://ffwagency.com/blog/managing-css-and-javascript-files-drupal-8-libraries

So in my theme.info.yaml

```
libraries:
  - THEME-NAME/global
  - THEME-NAME/custom

```

In my theme.libraries.yaml file:

```
global:
  version: 1.x
  css:
    base:
      /ui/style.css: {preprocess: false, minified: false}
  js:
    /ui/application.js: {preprocess: false, minified: false, weight: '-99'}

custom:
  version: 1.x
  header: true
  js:
    /ui/head.js: {}

```

---
Tags: theming, 8
---


# Question
Title: What happens to fields that don't have corresponding database columns?
I'm doing some work around the Salesforce Suite in Drupal 7. It's a suite of modules that load the Salesforce REST API, map objects and fields between Drupal and Salesforce, push data from Drupal to WordPress, pull data down from Salesforce, manage queues for the data, etc.

I'm trying to understand how Drupal handles a flag called `salesforce_pull` (from the `salesforce_pull` module within the Salesforce Suite). This code runs when Drupal knows about a new Salesforce row (presumably on cron or on an Ajax call):

```
  try {
  // Create entity from mapping object and field maps.
  $entity_info = entity_get_info($sf_mapping->drupal_entity_type);

  // Define values to pass to entity_create().
  $values = array();
  if (isset($entity_info['entity keys']['bundle']) &&
    !empty($entity_info['entity keys']['bundle'])
  ) {
    $values[$entity_info['entity keys']['bundle']] = $sf_mapping->drupal_bundle;

    // Because creating term via entities actually needs vid and won't be
    // fixed in Entity API (https://www.drupal.org/node/1409256).
    if (isset($values['vocabulary_machine_name'])) {
      $vocabulary = taxonomy_vocabulary_machine_name_load($values['vocabulary_machine_name']);
      $values['vid'] = $vocabulary->vid;
    }
  }
  else {
    // Not all entities will have bundle defined under entity keys,
    // e.g. the User entity.
    $values[$sf_mapping->drupal_bundle] = $sf_mapping->drupal_bundle;
  }

  // See note above about flag.
  $values['salesforce_pull'] = TRUE;

  // Create entity.
  $entity = entity_create($sf_mapping->drupal_entity_type, $values);

  // Flag this entity as having been processed. This does not persist,
  // but is used by salesforce_push to avoid duplicate processing.
  $entity->salesforce_pull = TRUE;
  $wrapper = entity_metadata_wrapper($sf_mapping->drupal_entity_type, $entity);

  salesforce_pull_map_fields($sf_mapping->field_mappings, $wrapper, $sf_object);

```

A comment there says "// See note above about flag." but the only thing I found was the same flag for other events (update, delete of Salesforce rows). It looks like this (which is fine, but I still am unclear how it works/how to use it):

```
// Flag this entity as having been processed. This does not persist,
// but is used by salesforce_push to avoid duplicate processing.
$entity->salesforce_pull = TRUE;

```

That part about `salesforce_push` using it is what I'd like to understand.

I have not found a database field for `salesforce_pull` (on any of the entities). I've also done a database search (through phpMyAdmin so it could search the whole thing) for TRUE values and the `salesforce_pull` phrase with nothing that seems to be related to this, including in the cache tables.

It seems like the Fields API (at least in D7) has a way to save data that doesn't have a corresponding field in the database. If this is the case, where does the field get saved? How long does it stay before it gets reset? How does it get reset? How do I access it?

I'd like to be able to use this convention, but I don't understand how it works and haven't been able to find any documentation on it.

# Answer
Interesting question, had a quick read through the module's code. I came across this comment that should answer your question:

@salesforce\_pull.module:335

> // Flag this entity as having been processed. This does not persist,
> // but is used by salesforce\_push to avoid duplicate processing.
> $entity-\>salesforce\_pull = TRUE;

It seems that this is not an entity field (or rather an entity property) that is attached to an entity (and therefore stored in the db), but, as the above comment mentions, simply a short-lived flag.

The way this goes is like this:

1. The salesforce\_pull module sets the flag on an entity (see @salesforce\_pull.module:335)
2. salesforce\_pull conditionally wraps that entity in an entity\_wrapper object and calls the -\>save() function on the object (see @salesforce\_pull.module:341)
3. This call will call hook\_entity\_update implementations, including the one from salesforce\_push (see @salesforce\_push.module:20)
4. salesforce\_push will call the salesforce\_push\_entity\_crud function that checks the value of that flag before using the Salesforce API to sync data (see @salesforce\_push.module:44)

All the steps above take place in the same request, which is why persisting the flag is not required.

Hope this helps, good luck!
> 2 votes

---
Tags: 7, entities, crm
---


# Question
Title: How can I “Link to the Content” for teaser view mode of custom content type module?
I've created a module that's add a content type to my site and I now want to understand how can I Link a **Plain text** fields to the Content in Teaser view mode programmatically in my module?
I currently can Link to the Content any Plain text field in:

> Home\>Administration\>Structure\>Content types\>Content types name\>Manage display

Teaser Manage display page, see below image:  and I want to understand how can I get access or implement this property (feature) in my module, I try to achieve this by adding below code to my module:

```
#core.entity_view_display.node.teaser
field_version:
  type: string
  weight: 2
  label: inline
  settings:
  third_party_settings: {  }

```

To no avail.

Thank you for any help.

# Answer
> 1 votes
This is the setting `link_to_entity: true`:

```
field_version:
  type: string
  weight: 2
  label: inline
  settings:
    link_to_entity: true
  third_party_settings: {  }

```

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


# Question
Title: (File) File: Path outputs only first item
I have a view that renders a node page as a view, that node has e.g. 100 images, so technically they are all on same node, so then we go to views fields settings and untick the option to show images in same row. So now each image has it's own row.

Now we add the relationship for file to enable extra fields. We add the File field and it also gets printed next to every image.

Except problem is that it prints the same and only path of the very first image under every other image. It should print the path of each image in the same row.

EDIT: tried the https://www.drupal.org/project/image\_url\_formatter module, same. It outputs the very same first image field only.

View:

# Answer
This is expected behaviour following from your Views configuration, there is no way to instruct Views to maintain a 1-1 relation between the `(File) File: Path` (which gives you one file path for each image) and the `Content: Image` (which gives you one image formatted field with multiple images included). As a result, they are 'combined' (cartesian product) and you should actually be getting a very long list of all combinations of images and image paths.

By using the Image URL Formatter module you should be able to do what you need, here is a screenshot:

---

I added the `"Content: Image"` field twice, each time unticking the "show images in same row" option. The first one was formatted as an Image, the second one as an Image URL. And things worked as expected.

Good luck!
> 0 votes

---
Tags: 7, views, files
---


# Question
Title: How to disable webform Results tab in webform without uncheked Access all webform results?
I'm using D7, i like to hide web form result tab, i try with tab tamer module,but it doesn't work i still got access to submission results,when i unchecked Bypass views access control and Access all webform results permissions, results tab become disable but in this case i couldn't change my webform workflow submissions anymore. Could any one suggest me an idea how to disable result tab without disabling the possibility to change my webform worflow state

# Answer
> 0 votes
The Webform access callback, `webform_results_access()`, for the submissions tab is structured so evoking the built its hook `hook_webform_results_access()` can't override *Access all webform results* permissions check.

However, a custom module could override the tab's access callback with your own custom logic:

```
/**
 * Implements hook_menu_alter().
 */
function MYMODULE_menu_alter(&$items) {
  $items['node/%webform_menu/webform-results']['access callback'] = 'MYMODULE_webform_results_access';
}
function MYMODULE_webform_results_access() {
  $result = FALSE;
  // @TODO: Add access logic
  return $result;
}

```

---
Tags: 7, webforms
---


title: Content types are missing

text:
# Question
Title: Content types are missing
I'm working with a drupal 7.50 installation on a local host.

My problem is that the basic content types are missing from my site. My custom content type is still visible and usable.

So far, I have checked under all menus to see if they've moved or been disabled, but I don't even see them. I've also tried clearing my cache, which didn't fix it.

Some of the modules I have enabled are drupal commerce, display suite, panels, and search api.

Any help would be much appreciated.

# Answer
> 1 votes
It seems like you are running a Drupal that was installed with the minimal profile. That profile does not create the Article and Basic Page content types. So, they are simply not there, clearing the cache will not help.

In order to get the content-types back you need to either:

a) Create them manually
b) Use the parts of the `standard_install()` function from `profiles/standard/standard.install` file that are additional to the `minimal_install()` function from `profiles/minimal/minimal.install` file to add the missing configuration. Kind of tricky, but not too much code there all in all.
c) Use the Features module to transfer the configuration of the content-types you are missing from another site installed using the standard profile.

N.B.: You know that already, but still, you should keep backups all the time, this may need a couple of try-n-error runs.

Good luck!

---
Tags: nodes, navigation
---


# Question
Title: Programming Layout Changes into Theme Templates & CSS Files
I've kicked a problem down the road for too long and am now stuck in the fact that I finally need to get it fixed.

I need to program layout changes into the php code so that the right CSS rules can apply to changes based on whether or not the left sidebar and/or the right sidebar is present on the page. In these sidebars are a variety of blocks that I have added to the templates and theme .info file.

So here's an example of my situation. If you need access to my current template files let me know.

So for one page, say I have one side bar the main content area, the css rules would read : Left\_Sidebar (width: 33%) and Main\_Content (width 66%). But when switching pages, say to one without a sidebar, I want the css rule for Main\_Content to be (width: 100%).

I've seen it done on other themes, but this theme is all of my own design. Some examples I've seen are in the "body class" where you see "with-sidebar", "no-sidebar", "two-sidebars" -----

I've tried looking around, but I must be not using the correct terms for what it is I'd like to do. If there is anyone who can help, please let me know! Thank you in advance!

# Answer
> 1 votes
Many existing themes already provide this kind of feature (usually using a preprocess function) so I would recommend looking at a theme like Zen or another popular base theme for examples of varying the page layout with a body class which specifies the overall structure of the page.

---
Tags: 7, theming
---


# Question
Title: Blog monthly archive block - list of posts grouped by year then month
See the implementation on this guy's blog: http://deglos.com/blog

```
YEAR
-- Month
-- Month
YEAR
-- Month
-- Month

```

Anyone know how this was accomplished?

# Answer
> 0 votes
It's normally done using Views and a good tutorial on the process has been explained by Chris Shattuck on his blog - see How to create a monthly archive block for a Drupal blog with Views

A little sleuthing on how the blog you mention was generated leads me to believe that the author wrote the wp\_blog module on Drupal.org which provides a view that ultimately generates the year -\> month -\> post hierarchy. You can see an exported view for the blog archive block here: http://cgit.drupalcode.org/wp\_blog/tree/views/wp\_blog.view?id=47246da29d176c028a749632807d207dfe0461e1

---
Tags: views, theming, blocks, nodes
---


# Question
Title: How do you remove product from shopping cart?
I have three product variations: Postpaid, Prepaid, and Accessories. I can't seem to figure out why when I add a product with the Accessories product variation, I'm unable to remove it from the Shopping Cart. However with the Postpaid and Prepaid product variation I am able to. Also, previously someone took care of the store, and I can't get support anymore.

I double checked the workflow Rules, and can't seem to find the options. I know it's not a view issue, because it shows the remove link with the Postpaid product variation.

My only work around is to add a new product through the Postpaid and Prepaid product variation, but I don't really want to do this because it's messy.

Please see screenshot below.

# Answer
> 2 votes
If that button is missing for some reason on just a specific product type, then it's more than likely the result of custom form altering in a module file on your site. I'm not aware of any Views configuration that could remove that button just for products of a certain type. Just in case, you can check your shopping cart form View's configuration for the line item delete button to see if any advanced settings are somehow hiding it conditionally.

My hunch is on custom code, though.

# Answer
> 0 votes
I finally was able to fix this issue, I found the custom module, the previous developer added, and added the new line item types, and it worked perfectly.

---
Tags: commerce
---


# Question
Title: Install Commerce 2.x project template windows using composer and got HTTP 500 error
I want to install Drupal Commerce 2.x in Drupal 8.x in Windows. I followed as in Commerce 2.x project template in Github. I installed composer and from my cmd window, I ran command: composer create-project drupalcommerce/project-base mystore1 --stability dev --no-interaction

All was going fine. It loaded many components like phpunit 4.8.27. Then it displayed messages like commerceguys/addressing suggests installing sysfony/intl ... and like these. Then Writing lock file , Generating autoload file, Downloading file:100%, Downloading file:100%,

Then I got Downloading file:Failed

Composer/Downloader/TransportException The "http://cgit.drupalcode.org/drupal/plain/.eslintignore?h-8.2.0-rc1: file could not be downloaded (HTTP/1.1 500 Internal Server Error)

I also searched if it had created some folder somerwhere in my C:\xampp\htdocs or somewhere, I could not get anywhere. Please help me install it completely and access drupal from browser. I have attached screenshot. The errors are seen in lower section:

# Answer
Retry ! It solves download issues. Then find project location in C:\Users\current\_user\project\_name Copy inside htdocs and browse localhost\project\_name\web and continue installation.
> 0 votes

---
Tags: commerce
---


# Question
Title: Can I use Full-Text Search Functions in db_select()?
Does it possible to use Full text search functions like `match() against()` with Drupal 8 database Api's OR any alternative to make it work?

# Answer
No. If you look at the internal `Condition::match()` function that's used when building conditional statements with the `condition()` method, you can see the list of operators does not include the `MATCH()` `AGAINST()` operators. The cost of having a DB abstraction layer that supports different DBMS, is you can only support the greatest common feature among them; these operators are MySQL/Postgres specific.

In order to utilize these feature of your database, you'll need to use the `Connection::query()` method to perform the query directly.
> 2 votes

---
Tags: 8, database
---


# Question
Title: Converting a content type into a Profile2 profile
I'm working on a site that's a user-contributed directory of local businesses. Each business that registers gets a user account.

I've thus far built the entire site using "Place" as a content type. However, in order to get users to contribute their listing as soon as they register (And to let the user easily edit that node), using Profile2 might make sense.

So, either one of two questions:

a. Is there any way of easily exporting a Drupal content type into something importable into Profile2?

b. Is there a way to get users to create a node just after or as they're signing up?

Thanks!

# Answer
To your first question, create a view of the required information and using the Views Data Export module you can export it to a csv file.

Then you can import the information to users and profiles using the User Import module.

To your second question, Rules will do it for them. Create a new rule executed on the event 'After Saving New Account' with the action of 'Create an Entity' and define the node you want created, using the new user as author.
> 2 votes

# Answer
An easy way to have users create a node on signup is to use Logintoboggan:

Create a new user Role called pre-auth and give it limited permissions. For example allow that role to create a particular content type. (To avoid spambots I would leave that content type set as unpublished.)

Then simply set Logintoboggan to allow login on registration, and redirect the user to node/add/your-content-type.

There is some self-explanatory configuration of the Non-authenticated role, the Welcome and Account activation email templates which are required; as Logintoboggan overrides the default account activation workflow.
> 0 votes

---
Tags: nodes, users
---


# Question
Title: From what directory should "drush cc all" command be run?
I've always ran drush cc all this way:

```
 C:\example\sites\all\modules>drush cc all

```

But can I also run it this way?

```
 C:\example>drush cc all

```

Does the second option fully clear the cache and the first one only the modules cache?

I never thought about this, always did it the first way...)

# Answer
It's irrelevant. The command:

```
drush cc all

```

clears all caches. The directory has no affect on what is cleared. If you want to target modules use:

```
drush cc module-list

```

Or if you want to target another cache use:

```
drush cc

```

which will prompt you for a cache to target.
> 2 votes

---
Tags: drush
---


# Question
Title: copying out Hierarchical Select terms into other textboxes
I have one Hierarchical Select with 4 depth term. What I need is to copying out every depth term level to other fields/textboxes at the same form as described by the attached image.

And also, how can every time we change the Hierarchical Select value, it also should change the corresponding fields/textboxes.

Thank you for the help.

------------ extra information on the problem ------------------

@Yogesh

I have mininal knowledge on javascript/jquery, where to save the \*.js file and how to call it properly.

I just read from one tutorial that it should save to a "js folder" and called it from the template .info file. So, following are two images that trying to tell you what I've been doing. Kindly help me to examine every detail of the images and hopefully you can tell where a did a wrong.

and i call the script from /sites/all/themes/zen/zen.info with command: "scripts\[\] = js/isian.js"

Please advise, Thank you

# Answer
> 0 votes
You can use Drupal JavaScript API for setting the values of fields, based on selection made by user in Hierarchical Dropdown field.

The below sample code is for fixed number (3) of fields, you can further extend this to dynamically set the values of n number of fields using jQuery $.each().

```
(function($){
  Drupal.behaviors.exampleModule = {
    attach : function(context, settings) {
      // On hierarchy change event.
      $(".hierarchical-select .selects select").change(function(event) {
        updateFieldsValue();
      });

      function updateFieldsValue() {
        var First = $.trim($(".hierarchical-select .selects select[name='field_hierarchical_dropdown[und][hierarchical_select][selects][0]'] option:selected").text());
        var Second = $.trim($(".hierarchical-select .selects select[name='field_hierarchical_dropdown[und][hierarchical_select][selects][1]'] option:selected").text());
        var Third = $.trim($(".hierarchical-select .selects select[name='field_hierarchical_dropdown[und][hierarchical_select][selects][2]'] option:selected").text());

        // set value of Fields.
        $("input[name='field_prop_1[und][0][value]']").val(First);
        $("input[name='field_prop_2[und][0][value]']").val(Second);
        $("input[name='field_prop_3[und][0][value]']").val(Third);
      }

    }
  };
})(jQuery);

```

You can find more details about Drupal Behaviors on 'Better understanding of Drupal behaviors' and 'Understanding JavaScript behaviors in Drupal'.

---
Tags: taxonomy-terms
---


# Question
Title: Getting error You are not authorized to access this page in custom module
I have a custom module which previously working fine before adding its view part. **form\_example.module**

```
   <?php
function form_example_permission() {
  return array(
    'submit form_example' => array(
      'title' => t('Submit form_example'),
      'description' => t('Submit the form_example form'),
    ),
    'access form_example submissions' => array(
      'title' => t('Access form_example submissions'),
      'description' => t('Access the form_example submissions'),
    ),
  );
}
function form_example_menu() {
  $items = array();

  $items['form-example'] = array( //this creates a URL that will call this form at "examples/form-example"
    'title' => 'Example Form', //page title
    'description' => 'A form to mess around with.',
    'type' => MENU_NORMAL_ITEM,
    'access arguments' => array('submit form_example'),
    'page callback' => 'drupal_get_form', //this is the function that will be called when the page is accessed.  for a form, use drupal_get_form
    'page arguments' => array('form_example_form'),

      );

 $item['form-submissions'] = array(
    'title' => t('List'),
    'page callback' => 'form_example_submissions',
    'access callback' => TRUE,
    'access arguments' => array('access form_example submissions'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function form_example_form($form, &$form_state) {

$form['empcode'] = array(
  '#weight' => '0',
  '#required' => '1',
  '#type' => 'textfield',
  '#title' => t('Employee Code'),
);
$form['empname'] = array(
  '#weight' => '1',
  '#required' => '1',
  '#type' => 'textfield',
  '#title' => t('Employee Name'),
);
$form['file'] = array(
  '#weight' => '2',
  '#type' => 'file',
  '#size' => '30',
  '#title' => t('Employee Photo'),
);
 $form['submit'] = array(
     '#weight' => '3',
    '#type' => 'submit',
    '#value' => t('Submit'),
  );

return $form;

}

function form_example_form_validate($form, &$form_state) {
  /*if (!($form_state['values']['price'] > 0)){
    form_set_error('price', t('Price must be a positive number.'));
  }*/
 // print('<pre>'.print_r($form_state['values'],1).'</pre>');
  //die();
 $file = file_save_upload('file', array(
    'file_validate_is_image' => array(),
    'file_validate_extensions' => array('png gif jpg jpeg'),
  ));
  if ($file) {
    if ($file = file_move($file, 'public://')) {
      $form_state['values']['file'] = $file;
    }
    else {
      form_set_error('file', t('Failed to write the uploaded file the site\'s file folder.'));
    }
  }
  else {
    form_set_error('file', t('No file was uploaded.'));
  }
}

function form_example_form_submit($form, &$form_state) {
   $file=$form_state['values']['file'];
  unset($form_state['values']['file']);
  $file->status = FILE_STATUS_PERMANENT;
  file_save($file);
  drupal_set_message(t('The form has been submitted and the image has been saved, filename: @filename.', array('@filename' => $file->filename)));

 $fe_id = db_insert('form_example')
        ->fields(array(

          'empcode' => $form_state['values']['empcode'],
          'empname' => $form_state['values']['empname'],
          'empphoto' => $file->filename,
        ))
        ->execute();
        drupal_set_message(t('Successfully added'));

}
/*function form_example_list(){
    //$form_example =drupal_get_form('form_example_search_form');
    // If wants to implement searching.
    //$content = '<div class="block" >'.drupal_render($form_example).'</div>';
    //$content .= '<div style="clear:both" ></div>';
    $header = array(
        array('data' => t('empcode'), 'field' => 'empcode', 'sort' => 'asc'),
        array('data' => t('empname'), 'field' => 'empname'),
        //array('data' => t('empphoto'), 'field' => 'empphoto'),
    );

    $query = db_select('form_example', 'pd');
    if(isset($_GET['empcode']) && $_GET['empcode'] != ''){
        $query->condition('pd.empcode', $_GET['empcode'],'=');
    }
    if(!empty($_GET['empname'])){
        $query->condition('pd.empname', $_GET['empname'],'=');
    }
    $query->fields('pd');

    $table_sort = $query->extend('TableSort')->orderByHeader($header);
    $pager = $table_sort->extend('PagerDefault')->limit(10);

    $result = $pager->execute();
    $rows = array();

    foreach($result as $res){
      $rows[] = array($res->empcode, $res->empname);
    }
    $content .= theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('id' => 'sort-table')));
    $content .= theme('pager');
    return $content;
}*/

/* view the form submissions*/
function form_example_submissions()
{
  $results =  db_query("Select * from {form_example}");
  $header = array(t('ID'),t('Empcode'));
  $rows = array();
  foreach($results as $result)
  {
    $rows[] = array(
        $result->fe_id,
        $result->empcode,
      );

  }
  return theme('table',array('header=>$header','rows' => $rows));
}
/*function form_example_list(){
    //$form_example =drupal_get_form('form_example_search_form');
    // If wants to implement searching.
    //$content = '<div class="block" >'.drupal_render($form_example).'</div>';
    //$content .= '<div style="clear:both" ></div>';
    $header = array(
        array('data' => t('empcode'), 'field' => 'empcode', 'sort' => 'asc'),
        array('data' => t('empname'), 'field' => 'empname'),
        //array('data' => t('empphoto'), 'field' => 'empphoto'),
    );

    $query = db_select('form_example', 'pd');
    if(isset($_GET['empcode']) && $_GET['empcode'] != ''){
        $query->condition('pd.empcode', $_GET['empcode'],'=');
    }
    if(!empty($_GET['empname'])){
        $query->condition('pd.empname', $_GET['empname'],'=');
    }
    $query->fields('pd');

    $table_sort = $query->extend('TableSort')->orderByHeader($header);
    $pager = $table_sort->extend('PagerDefault')->limit(10);

    $result = $pager->execute();
    $rows = array();

    foreach($result as $res){
      $rows[] = array($res->empcode, $res->empname);
    }
    $content .= theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('id' => 'sort-table')));
    $content .= theme('pager');
    return $content;
}*/

?>

```

# Answer
Remove `'access arguments' => array('administer users')`, and add `'access callback' => TRUE,`

`$items['form-submissions']` instated of this `$item['form-submissions']` need to write. (missing "s").

Clear the cache before check.
> 1 votes

# Answer
I think this should be the error `'acccess callback' => TRUE,` , you have typo which should

> 'access callback' =\> TRUE,

Clear the cache and check. Change `$item['form-submissions']` to `$items['form-submissions']` and clear the cache.
> 1 votes

---
Tags: users
---


# Question
Title: Users restricted from editing own profiles
I found that non-site-admins cannot edit any of the custom fields attached to their profile. I have found the Organic Groups (fixed) feature request "Authenticated users cannot edit his custom profile fields" that appears to explain the issue, but that's not clear enough for me.

Who exactly is the Group Audience for the User (the User?) and how do I set up the settings correctly to ensure all users can access and view their custom profile fields?

Is the User a "Group" and the Custom Profile Fields "Group Content"?

# Answer
> 0 votes
It turned out that the permissions needed to be rebuilt as well as verified that that the user had the ability to edit the "Group", which are actually there own user profiles, albeit confusing with the labels.

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


# Question
Title: Render a custom module inside an existing node
I have a site in Drupal 7 and I have created a custom module for a functionality that I need. Usually, I create custom modules and I create a new page to show them, using the following code:

```
function my_custom_module_theme() {
    $items = array();
    $items['my_custom_module'] = array(
        'render element' => 'form',
        'path' => drupal_get_path('module', 'my_custom_module') . '/templates',
        'template' => 'my_custom_module-template',
    );
    return $items;
}

function my_custom_module_menu() {
    $items = array();
    $items['my_custom_module'] = array(
        'title' => t('my_custom_module'),
        'page callback' => 'drupal_get_form',
        'page arguments' => array('my_custom_module'),
        'access callback' => TRUE,
    );

    $items['my_custom_module'] = array(
        'title' => t('my_custom_module'),
        'page callback' => 'drupal_get_form',
        'page arguments' => array('my_custom_module_empty_form'),
        'access callback' => TRUE,
    );
    return  $items;
}

function my_custom_module_preprocess_page(&$variables, $hook) {
    $alias = drupal_get_path_alias($_GET['q']);
    if ($alias == "my_custom_module") {
        $variables['theme_hook_suggestions'][] = 'my_custom_module';
        $variables['show_messages'] = TRUE;
    }
}

function my_custom_module_empty_form($form_state) {
    $form = array();
    return $form;
}

```

and my module appears on mysite/my\_custom\_module .
What I want to achieve now is to add my custom module at the bottom of an existing node, which has it's own content and functionality.
What should I add to my\_custom\_module-template.tpl.php or in my node--xx.tpl.php to display my custom module inside the node?
I have already used

```
<?php
   $nid = xx; // NOTE :: Hard coded, but need to be variable!!
   print drupal_render(node_view(node_load($nid)));
?>

```

from a similar Stack overflow question, but it does the opposite of what I want, it renders the node inside the module.

# Answer
You can implement `hook_node_build()` in a custom module to add or alter elements when a node's content is by assembled for viewing, right before rendering.

```
function MODULE_node_build($node, $view_mode, $langcode) {
  // Only do something if the node is rendered on its own page, in full.
  if ($node->type == 'MODULE_type' && $view_mode == 'full' && node_is_page($node)) {
    $node->content['MODULE_stuff'] = array(
      // Insert render array content here
    );
  }
}

```

For sorting, you can add a `#weight` property in the element(s) added to `$node->content`. But a nicer solution is to implement `hook_field_extra_fields()`, so you can position the added element(s) using the usual Field UI.
> 4 votes

# Answer
You need to create the functionality in a block. And then display the block wherever you need from /admin/structure/block. To create the functionality use the below code in .module file -

```
/**
 * Implements hook_block_info().
 */
function MY_MODULE_block_info() {
  $blocks = array();
  $blocks['mycustomform'] = array(
    'info' => t('My custom block'),
    'cache' => DRUPAL_NO_CACHE,
  );
  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function MY_MODULE_block_view($delta = '') {
  $block = array();

  switch ($delta) {
    case 'mycustomform':
      $block['subject'] = t('Title of the form');
      $block['content'] = drupal_get_form('MY_MODULE_form');
    break;
  }
  return $block;
}

/**
 * Implements hook_form()
 */
function MY_MODULE_form($form, &$form_state) {
  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Name'),
  );

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

  return $form;
}

/**
 * Implements hook_form_submit()
 */
function MY_MODULE_form_submit($form, &$form_state) {
    drupal_set_message("You form is successfully submited");
}

```

Now place it any region of your choice. Say footer of your node.

If you want to control the view from tpl file. Use this code - $block = module\_invoke('custom\_nodeprocess', 'block\_view', 'mycustomform'); print drupal\_render($block);
> 0 votes

# Answer
First it's not clear what you mean by "displaying a module"?!? Module is bunch of code - it can not be "displayed".

Anyway, why complicating thing when you can do it simple? You have your content type and it's template file - `node--xx.tpl.php`. At bottom of that template file just simply add content that you need. If you have to call some function from your module to generate content dynamically - just do that. It's just question of code organization, but generally you can put any kind of code in your content type's node template, query DB, execute views...do anything you need to acquire data, generate markup out of it and print it directly there, in node template.

Purpose of blocks is allowing admin to dynamically add, remove, re-position content. But if content should always be at the same place having a blocks is overkill. Don't waste code/server resources.
> 0 votes

---
Tags: 7, nodes
---


title: Getting $_POST empty in AJAX callback

text:
# Question
Title: Getting $_POST empty in AJAX callback
I just want to send address information to drupal for check content existence through the AJAX.

Request is sending successfully and callback function also executing. but I am not getting any data in `$_POST` array.

here is my AJAX code.

```
    var address = [{'add1':'address line1','add2':'address line2','add3':'address line3'}]
    $.ajax({
            url: Drupal.settings.property_check.base_url + '/search/property-by-address',
            type: 'POST',
            data: JSON.stringify(address),
            headers:{
              'Content-Type': undefined,
            }
        })
        .done(function(response) {
            console.log(response);
        })

```

This is callback routing & function

```
  $items['search/property-by-address'] = array(
     'title' => 'property by address',
     'page callback' => 'search_property_by_address',
     'access arguments' => array('access content'),
     'type' => MENU_CALLBACK,
   );

  return $items;

function search_property_by_address(){
  drupal_json_output($_POST);

}

```

At where I am making mistake? is there any other way? Or is there any problem with `headers`?

# Answer
Try something like this:

```
$.ajax({
   url: Drupal.settings.property_check.base_url + '/search/property-by-address',
   type: 'POST',
   data: {
       'add1':'address line1',
       'add2':'address line2',
       'add3':'address line3'
   },
   headers:{
       'Content-Type': undefined,
   }
}).done(function(response) {
        console.log(response);
})

```

or

```
 var address = {'add1':'address line1','add2':'address line2','add3':'address line3'};

 $.ajax({
     url: Drupal.settings.property_check.base_url + '/search/property-by-address',
     type: 'POST',
     data: address,
     headers:{
         'Content-Type': undefined,
     }
 }).done(function(response) {
     console.log(response);
 })

```
> 4 votes

---
Tags: routes, ajax
---


title: IE conditional comments for HTML class?

text:
# Question
Title: IE conditional comments for HTML class?
I need to have the following html classes with IE conditional comments in my Drupal 8 site:

```
<!--[if lt IE 9]>      <html class="no-js lt-ie10 lt-ie9"> <![endif]-->
<!--[if IE 9]>         <html class="no-js lt-ie10"> <![endif]-->
<!--[if gt IE 9]><!-->
<html class="no-js">
<!--<![endif]-->

```

Ideally I would use html\_attributes.addClass see this question: Safe to add a class attribute to the HTML element via the theme?

I tried this:

```
<!--[if lt IE 9]>      <html{{ html_attributes.addClass('no-js lt-ie10 lt-ie9') }}> <![endif]-->
<!--[if IE 9]>         <html{{ html_attributes.addClass('no-js lt-ie10') }}> <![endif]-->
<!--[if gt IE 9]><!-->
<html{{ html_attributes.addClass('no-js') }}>
<!--<![endif]-->

```

But it seems once you add a class to html\_attributes then its printed every time, so my final instance which should only have a class of `no-js` instead has this:

```
no-js lt-ie10 lt-ie9 no-js lt-ie10 no-js

```

# Answer
> 0 votes
Your best bet is to print the class attributes separately, and use the `without` twig filter, then hard code the IE stuff, e.g.

```
<!--[if lt IE 9]> <html{{ html_attributes|without('class') }} class="{{ html_attributes.class }} lt-ie10 lt-ie9"> <![endif]-->
<!--[if IE 9]>    <html{{ html_attributes|without('class') }} class="{{ html_attributes.class }} lt-ie10"> <![endif]-->
<!--[if gt IE 9]><!-->
<html{{ html_attributes.addClass('no-js') }}>
<!--<![endif]-->

```

---
Tags: theming, 8
---


title: View filter computed date field

text:
# Question
Title: View filter computed date field
i have content type in Drupal 6 that has date field, that is date when some historical event happened.

I want to create a view that will show all historical events that happened today.

I created 2 computed fields that will take data from that date field, one for month and other for day. Also i created view and added this two fields as filter. And when i enter exact numbers in filter, like 9 and 20 it shows the articles that happened on this month and day.

But since its not exactly a date field i cant enter relative values like "now" or "today" and someone needs to change this manually every day.

What is best way to get this filter take todays day and month.

# Answer
OK i found the solution.

I had to use Arguments ( contextual filters ), and in argument i would use php code as validator and than just get todays day with simple code:

```
$day = date("j");
return $day;

```

Hope this helps someone in future.
> 0 votes

---
Tags: 6, views
---


# Question
Title: Use administration theme for verified users when adding or editing content
I'm having a problem with the administatration theme. I want verified users to see the administration theme when they are adding or editing content. Right now only the admin user sees the administration theme and verified users see the standard theme. Is it possible to also enable this for verified users?

Thanks!

# Answer
Enable **`View the administration theme`** permission for verified/authenticated users.
> 1 votes

---
Tags: 7, theming
---


title: Checkout page change theme

text:
# Question
Title: Checkout page change theme
i use drupal 7 with Commerce module installed. I am searching a couple days to find out a way to change (alter) the presentation (theme) of Checkout page. I mean the first page that someone visit after pressing Checkout button. (Not the review or payment pages).

What is trying to do, is to have only the cart contents on top and below that i want to create a tab system with the following tabs:

* Login
* Create Account
* Complete checkout as a guest

So i need to hide the billing or shipping or any other pane and make them visible only on the third tab.

I think i have some pieces of the puzzle, for example i have tried creating a custom module and playing with **hook\_commerce\_checkout\_pane\_info\_alter** to unset some panes and **hook\_form\_commerce\_checkout\_form\_alter** to create panes programmatically but i am lost in space...

Another puzzle piece, is the php code of the login form for the first tab(Login) for example:

```
<?php
   $elements = drupal_get_form("user_login");
   $form = drupal_render($elements);
   echo $form;
?>

```

I may need your help to make things clearer. I need to reorder panes, add some custom html and javascript to create the tab system and bring some forms there. Where is this canvas, the template that loads everything so to bypass that and create my own ? Where do i have to look, search and study ?

Thank you :)

# Answer
> 0 votes
In a custom module you can change the theme like this:

```
function YOUR_MODULE_custom_theme() {
  if (current_path() == 'checkout') {
    return 'plain';
  }
}

```

With this approach you need a full new theme (in the above example named *plain*). You then can directly use it's page.tpl.php. In **template\_preprocess\_page** you could add javascript and fill variables with your html (or blocks).

Also you can place the blocks like you want for this theme.

To get the correct current\_path you would need to debug a lil. checkout is just guessed by me ..

---
Tags: theming, commerce
---


# Question
Title: Custom Module Route run by External Cron Task
I created a Drupal 8 module that cURL to a SFTP, grab a xml file and write it on the files folder. This module as a route (with \_access: 'TRUE'), pointing to a controller that does the task.

While I'm connected as admin, and go to that route URL, the XML is downloaded as expected. When I do it as an anonymous user, it doesn't work, not throwing any error. My goal is to have this route run by an external Cron task (every 5 minutes). However, when it runs, it's not recognized as admin, so it doesn't work.

What would be the best practice to have it working with a Cron Task but also secure enough so that not everybody could run it by going to that URL ?

# Answer
I would make an API endpoint with authentication. Like: mysite.com/api/crontasks?u=user&p=password

And then authenticate it via controller!
> 0 votes

---
Tags: 8
---


# Question
Title: Disabling text field for all users / roles
is there an easy way to disable (readonly) fields in the backend for ALL users and roles (also superadmin).

I already found a module -\> https://www.drupal.org/project/disable\_field but this module allows superadmins to edit the fields.

**Why do i need this?**

Because the 5star rating module isn't ported to D8 yet i need a solution to realize a 5star voting in D8 with the vote data (5star rating) from an old drupal installation.

My thought was to work with a field collection, where i want to import the main 5star rating values from the old site into the new installation.

Afterwards i want to build a custom 5star voting.

The users should not be able to change this values in the field collection.

Any ideas?

Regards

M.

# Answer
I don't know why would you need to disable any fields in the first place (that's not turns out from your post), but if you need 5 voting field, you could easily create it:

You may need just a part of them or all of them:

Creating a custom Field
> 0 votes

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


title: Translate routing and menu titles

text:
# Question
Title: Translate routing and menu titles
I've made two yml files, for both routing and menu item:

Route:

```
tester_helper.products_controller_overview:
  path: '/assortment'
  defaults:
    _controller: '\Drupal\tester_helper\Controller\ProductsController::overview'
    _title: 'Assortment'
  requirements:
    _permission: 'access content'

```

Menu item:

```
tester_helper.products_controller_overview_link:
  title: Assortment
  parent: main
  route_name: tester_helper.products_controller_overview
  menu_name: main
  weight: 3

```

Is it possible to translate both the path and the menu item title?

For example: EN (english): "Assortment" =\> /assortment

DE (german): "Sortiment" =\> /sortiment

# Answer
> 6 votes
`_title` in `*.routing.yml` and `title` in `*.links.menu.yml` are translatable by default. Go to user translation (/admin/config/regional/translate) and search there for 'Assortment' and translate it.

The path is not translatable. See this similar question:

Translating paths in routing.yml

In the answer you find some ideas.

---
Tags: 8, routes, navigation
---


title: q?=admin page accessible for anonymous

text:
# Question
Title: q?=admin page accessible for anonymous
How do I prevent this? I'm not sure what is causing this. This site is running over 60 modules now and yesterday I noticed something changed my admin\_menu toolbar layout, but don't know if this has to do anything with this.

# Answer
Check the user permissions. The anonymous role might have one too many permissions granting access, such as "Use the administration pages and help".

You aren't running any sort of caching setups that might be caching a logged in experience and displaying it for anonymous users are you?
> 4 votes

---
Tags: 7, users
---


# Question
Title: Load a page with only the form, no drupal theme/element around
In Drupal 8, I created a form Class. I can access to this form with the route defined in the yml file.

I want load the form page without any theme/elements Drupal, just show the form (with a minimal css for align the form to the center of the page). Is there a simple way for do that ?

# Answer
> 1 votes
I know it's possible to have a Controller action return raw HTML, by returning a Symfony\Component\HttpFoundation\Response object with the html string as an argument. IE

```
namespace Drupal\my_module\MyController;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\Response;

class MyController extends ControllerBase {
  public function content() {
    $markup = '<h1>Behold my markup!</h1>';
    return new Response($markup);
  }
}

```

If that's what you are going for, you could hard code the form instead of using the drupal form api. It does mean abandoning the functionality of the form api as well though - you are basically creating a route to a plain html page.

---
Tags: theming, forms, 8
---


# Question
Title: How do I programmatically add a field to an existing fieldset that's part of the user entity?
I'd like to know how to add a field to an existing fieldset in a user entity

I've seen this example:

Add Fields to Field Group programatically https://drupal.stackexchange.com/a/71902/1082

```
$groups = field_group_read_groups(array(
    'name' => 'node',
    'bundle' => 'article',
    'view_mode' => 'full'));
  $your_group = $groups['node']['article']['form']['group_your_group'];
  $your_group->children[] = 'field_your_new_field';
  field_group_group_save($your_group);

```

But I'm unsure what to supply for 'name' and 'bundle' and also what to supply for the line

```
$your_group = $groups['node']['article']['form']['group_your_group'];

```

# Answer
I think you should try hook\_form\_alter. try this may it helpful to you.

```
function mymodule_form_alter(&$form, $form_state, $form_id) {

  // Check your form-ID
  if ($form_id == 'user_profile_form') {
    // Creating custom field
    $form['new_field'] = array(
      '#weight' => 4,
      '#type' => 'textfield',
      '#title' => t('New Field Name'),
    );
  }
  // Attach to the existing group
  // Suppose group machine-name is group_general
  $form['#group_children']['new_field'] = 'group_general';
}

```
> 2 votes

# Answer
In case anyone stumbles upon this, here is what worked for me: in `hook_form_alter`,

```
 $form['#fieldgroups']['group_name']->children[] = 'field_name';

```

Where '`#fieldgroups`' is the actual name of the $form element, and 'group\_name' is the machine name of your fieldset, and 'field\_name' is the name of the field you want to insert.

This was for a commerce product form...not sure how it works attaching it to a user entity.
> 1 votes

# Answer
I used a different method based on your opening code:

```
$groups = field_group_read_groups(array(
 'entity_type' => 'node',
 'bundle'      => 'article',
 'mode'   => 'form'
));
$your_group = $groups['node']['article']['form']['my_group'];
$your_group->children[] = 'field_event';
field_group_group_save($your_group);

```
> 1 votes

---
Tags: 7, entities
---


# Question
Title: Content teaser view, Read more shows only in admin mode
I manage a Drupal 7 site with custom theme and I have no FTP access and was not involved in development but I have to manage the content and have every right on the web surface.

## The situation

I created some content based on the type article (which has a Body of "Long text and summary" field type and of "Text area with a summary" widget), and a view to show this content.

In the view display (created both Block and Page), Format is set to "Unformatted list" (Force using fields is disabled at the settings), and Show is set to "Content | Teaser". Check the image for the settings.

With these settings, the content on the editorial view is fine for me: title, a picture, a text and a read more link. Check the image for the result.

Unfortunately, "Read more" does not appear on the page shown for the visitors. Not even not shown, it cannot be found in the html source code.

Note: Read More Control and Read More Link modules are not installed.

## Question

Is this behavior intended? Is there a bug in a module? Did I miss something, and there's a way to show "Read more" on the page for the visitors too? Can you please tell me how can I manage to show a "Read more" link to the visitors with the same view settings? I neither understand why modifying the Block style implies the modification of the Page Display, i.e. I modify one of them (like the displayed fields), the other display is modified too automatically.

I already have a workaround, but it is not a solution. What I've done is that I changed the setting and checked the box "Force using fields" at Format: unformatted list and manually added the title, image, text, a manual texted link to read more and a horizontal rule.

# Answer
The "Read More" link is part of the contextual links for each post. So, you need to simply tell Views that you do not want the links shown.

* Go to: `Format, Show, Teaser` (the first image you showed in your question).
* Under the dropdown for "view mode", you will see a checkmark for `Display links`. Uncheck that and they should disappear.
> 0 votes

---
Tags: views, navigation
---


title: setup centos 7 enviorment

text:
# Question
Title: setup centos 7 enviorment
I try to setup a Centos 7 enviorment in order to install Drupal 8. I have followed a few tutorials like these ones:

http://orangeweb.com.au/installing-drupal-8-centos-7

http://www.linuxtechi.com/how-to-install-drupal-8-on-centos-7/

Every thing goes well until I try to install the drupal site. when I try to install it, I get an error massage that Drupal requires a higher PHP version (5.5.9 or higher).

when i try to update the PHP version to 5.6 (according this tutorial). I still get the same error.

writing php -v on the terminal I see that the php version is now 5.6. but when i upload a phpinfo(); file to the server I still see that the version is still 5.4.

why in the phpinfo I still see the 5.4 version?

# Answer
It sounds to me like you are running more than one PHP version on the server.

Did you remove the current (old) PHP version before adding the new one? Did you restart apache/the server after installing?

You may need to tell Apache manually to use the new php56.

check your `httpd.conf` for the `LoadModule` definition that defines it and make sure it's referencing the correct PHP installation.

Centos 7 http.conf location: `/etc/httpd/conf/httpd.conf`

*Note that any changes you make here require that you restart apache. Also note that changing here has a risk of bringing down apache, so modify with caution.*
> 0 votes

---
Tags: 8, installation
---


# Question
Title: Add subquery with count, having, and orderby
I just started working with Drupal 7 and I'm stuck at something I believe should be really easy (I could easily write it using plain SQL).

I have a query, rather complex (but that's not relevant) which I wanted to extend with hook\_views\_query\_alter. What I need to achieve:

Based on base table *users* I need to:

1. Join a table *node* based on *users*.*uid* (many-to-one)
2. Then join a table *node\_param* on *node*.*id* (one-to-one)
3. select count(*node\_param*.*id*) WHERE *node\_param*.*value* is greater than X
4. Order everything based on that count field

I've done research on Drupal website and stackoverflow, but couldn't find anything that would actually work, everything I've tried ended up with no results at all and I did build the query with SQL that returns results - therefore I believe my altered query gone wrong.

I will really appreciate your help here! :)

P.S. I can only modify this query using this hook!

# Answer
So, from reading your question, it seems you're missing a fundamental step to data modeling with Drupal. The first thing you're going to want to do is to build out content types and fields for your data. This is done through the content types user interface. Once you have all of your data in node content types and fields, it becomes much easier to access this data in views.

When it comes to creating joins in views, you'll want to use "relationships" under "advanced" on the right hand side of the views UI. Since you're new to Drupal, but not to SQL, you might find it helpful to turn on "Show the SQL Query" here: /admin/structure/views/settings

So, the big realization here is that you don't create custom tables in Drupal databases manually. There are use cases where using a node doesn't make sense. In that case, you'll want to create a custom content entity. This is *not* done manually in Drupal. While creating entities can be done through code, you're better off using this module to generate your tables:

https://www.drupal.org/project/eck

Finally, most Drupal developers prefer nodes for data storage because Nodes are special entities that have many wonderful features that almost all data in Drupal needs.
> 1 votes

---
Tags: 7, hooks, views
---