# Question
Title: Hide the display of a field conditionally
I have the following scenario:

I have many users created from People-\>Add user

I have a content type (named Project) with the following fields:

--Leaders (Type: Entity Reference to Users)

--Editors (Type: Entity Reference to Users)

--Price (Type: Decimal)

--Duration (Type: Integer)

I want the Price field to be hidden from logged in users belong to Editors field.

**The difficult point here is that one User could be Editor to “Project 1” (a node from content type Project) and Leader to “Project 2 ”.**

I tried some things with the following modules: Rules, Field formatter conditions, Views Entity rules, but with no results…

Could you please advise me, how to hide the display of a field considering if the logged in user belongs to “Editors” field for each Project?

# Answer
> 0 votes
You can alter Add Project content form using hook\_form\_alter and check for **#options** in **Editors** field and if Current User ID exists in #options and then conditionally show/hide **price** field.

You can also check Conditional Fields module, to see if you get current logged in users details in it. Not sure if it does.

**NOTE:** You can get current logged in user details in global $user variable.

---
Tags: views, rules
---


# Question
Title: How to get the count of referenced entity (by views entityreference result)?
For example, a student can register a class. The class node has a date field indicating whether the class is active for registering. The registration node has an entityreference field referencing to the class node. I get the referencing class nodes by using "Views: Filter by an entity reference view" option. This view has a filter of "current date is between the start and the end date". Now, if the count of the reference view result rows is 0, the student should be redirected from the node/add/registration page to an explanation page which tells students there is currently no active classes for registering. On the module entityreference\_count page, it says,

> Currently this module only works with entityreference fields configured to use the "Simple (with optional filter by bundle)" option. It does not work with the "Views: Filter by an entity reference view" option. This may be addressed in a future release.

How can I make it?

# Answer
> 0 votes
Entity Reference Count

> This Entity Reference Count is in-and-of itself, just another field type (called "entityreference\_count" in the code) that may be attached to any Drupal entity. The field may be configured to select which referencing entity types and fields you want to aggregate in the count. The counter field is automatically re-calculated when the referencing or referenced entity get inserted, updated or deleted. The Entity Reference Count's numeric field value may be enabled, displayed and manipulated via view modes, through the "Manage Fields" interface provided by Drupal core's Field UI, and has built-in Views integration.

OR

* Make sure Child has an entity reference to Parent.
* Create a new view
* In Filter Criteria, add a new Type (`= Parent`)
* In Advanced\>Other, set Aggregation to YES
* In Advanced\>Relationships, add a new relationship for "A bridge to the Content entity that is referencing Content via `field_parent`" where `field_parent` is your entity reference. Call this "Parents"
* In Fields, add Content: Title and when prompted set its Aggregation type to Group results together
* In Fields, add Field: Parents and when prompted set its Aggregation type to COUNT (Distinct)

---
Tags: views, entities
---


title: Zebra striping on custom panels layout

text:
# Question
Title: Zebra striping on custom panels layout
Is there a way to get zebra striping on a custom panels layout? I've been looking hook\_preprocess\_panels, but I don't see a way to tell if I'm a certain layout is being used. I don't want it on all layouts, just one in particular. I have the layout made, and I figure if I can add a css even/odd class to a node in the panel, I should be able to get what I need.

# Answer
If you use even/odd pseudo-classes, you don't need even/odd classes

```
:nth-child(even)
:nth-child(odd)

```

Example:

```
.parent_class > div:nth-child(even) {background: #CCC}
.parent_class > div:nth-child(odd) {background: #FFF}

```

or

```
ul.yourclass li:nth-child(even) {background: #CCC}
ul.yourclass li:nth-child(odd) {background: #FFF}

```
> 0 votes

---
Tags: panels
---


# Question
Title: How to programmatically render a view pager?
I'm trying to figure out how to render a view's pager programmatically. I'm renderering my view programmatically as follows:

```
$viewname = 'example_view';
$viewdisplay = 'block';

// get the view machine id
$view = Views::getView($viewname);
// set the display machine id
$view->setDisplay($viewdisplay);
$view->render();

$renderer = $view->rowPlugin;
foreach ($view->result as $index => $row) {
  $view->row_index = $index;
  $vars['content']['view_results'][$index] = $renderer->render($row);
}

```

So now I need to render the pager, but not having any luck. I've tried something like:

```
$pagerrenderer = $view->pager;
$vars['content']['view_pager'] = $pagerrenderer->render($view->pager);

```

but then end up with the following error:

> Recoverable fatal error: Argument 1 passed to pager\_query\_add\_page() must be of the type array, object given, called in /www/projectname/docroot/core/includes/pager.inc on line 246 and defined in pager\_query\_add\_page() (line 311 of core/includes/pager.inc).

Can anyone point me in the right direction?

# Answer
The object returned from `$views->pager()` is an object implementing `ViewsPluginInterface` and extending `PagerPluginBase`. If you look at the parameters `PagerPluginBase::render()` accepts, you will see they are:

> **$input**: Any extra GET parameters that should be retained, such as exposed input.

If you look at `Full::render()`, you have an idea of how that parameter is used.

```
  $tags = array(
    0 => $this->options['tags']['first'],
    1 => $this->options['tags']['previous'],
    3 => $this->options['tags']['next'],
    4 => $this->options['tags']['last'],
  );
  return array(
    '#theme' => $this->themeFunctions(),
    '#tags' => $tags,
    '#element' => $this->options['id'],
    '#parameters' => $input,
    '#quantity' => $this->options['quantity'],
    '#route_name' => !empty($this->view->live_preview) ? '<current>' : '<none>',
  );

```

In any case, you don't pass to the method of that object the object itself.
> 7 votes

---
Tags: views, 8, paging
---


title: How to get field type from $form_state?

text:
# Question
Title: How to get field type from $form_state?
How do i get field type (e.g *textfield*, *option*, etc.) from `$form_state` in below method.

```
public function validateForm(array &$form, FormStateInterface $form_state)

```

# Answer
As said before, it is in

```
$form['fieldname']['#type']

```

You don't need the state for this because it is not a state, it's static.
> 1 votes

# Answer
no filed type in $form\_state

you can use $form instead
> 0 votes

# Answer
The render element types are defined using the #type property in the render array.

The only render element that the form state object (*might \[1\]*) reference directly is the main form element, via the **getCompleteForm** method.

\[1\] the form builder object sets the complete form parameter on the form state while building the form, so I'm the early stages it might not yet be set.

P.S.

The form state object does hold a reference the form object. Which means that in entity forms, you can get the entity and it's fields from the form state object.
> 0 votes

---
Tags: 8, forms
---


title: How do I print a custom menu?

text:
# Question
Title: How do I print a custom menu?
There are lot of tutorials on Internet about how to display menu, but no one works for me. I have tried:

```
$menu_array = menu_navigation_links('menu_menu-login-menu');
print theme('links__menu_login_menu', array('links' => $menu_array));

```

```
print drupal_render(menu_tree_output(menu_tree_all_data('menu-login-menu')));

```

Both don't work.

My menu looks like this.

>

# Answer
Have you tried using the Menu Block module (D7)?

Disable the main menu in the theme settings and create one or multiple menu blocks with a lot of options for the menus. The module can render submenu items with the main navigation and/or in a separate menu-block. The Menu block module can render a custom menu as well.

You can also add an extra region to your theme that renders a menu-block-menu inside a nav-tag:

yourtheme.info file add:

```
regions[nav_custom] = Nav Custom

```

In page.tpl.php add:

```
<?php if ($page['nav_custom']): ?>
    <nav id="nav-custom" role="navigation" class="navigation">
      <?php print render($page['nav_custom']); ?>
    </nav> <!-- /.section, /#nav-custom -->
<?php endif; ?>

```
> 2 votes

---
Tags: theming
---


# Question
Title: How to show all template suggestions for a page without using Devel Themer?
For some reason the Theme developer module doesn't work on my site (whenever i activate it and navigate on my site it just shows a white page with written "Jump to main content"), but all I want to know is which TPL files are being used to render my current page.

I know that if i put `print_r($variables["theme_hook_suggestions"]);` in `preprocess_html` or `preprocess_page` functions (or any other preprocess function for what it matters) I'll be able to see the suggestions for the `html.tpl.php` and `page.tpl.php` files respectively, but i actually need to go deeper and see all the template suggestions that are being checked to render the current page.

Is there any way to do this without using the Theme developer module?

# Answer
> 3 votes
In addition to the function/template specific hooks, there's also `hook_preprocess()`:

> This hook allows modules to preprocess theme variables for theme templates. It is called for all theme hooks implemented as templates, but not for theme hooks implemented as functions.

Combine that with the Devel module's `dpm()` function and you should get what you need:

```
function MYTHEME_preprocess(&$vars, $hook) {
  if (!empty($vars['theme_hook_suggestions'])) {
    dpm(t('Hook - @hook', array('@hook' => $hook)));
    dpm($vars['theme_hook_suggestions']);
  }
}

```

# Answer
> 10 votes
You can put this in your settings.php $conf\['theme\_debug'\] = true;

This outputs html comments on your page which will help you with debugging how the theme suggestions are selected.

---
Tags: 7, theming, debugging
---


# Question
Title: How do I programmatically change the query "limit"?
I've created listing with views module in which page has 9 items and only in first page the sixth item should be advertisement instead of result item. It means all items after sixth element should be shifted for one item. How can I do this? Would be `hook_views_query_alter()` the correct hook?

# Answer
> 0 votes
If you can make your change by altering the query itself than `hook_views_query_alter()` is a reasonable approach, although given your description I suspect `hook_views_pre_render()` is more likely to give you access to the data you are thinking about. The query alter lets you change the actual query run against the database, while prerender lets you edit the result set before Drupal renders it as HTML (or similar) for output.

Depending on the details of your use case it might make sense to actually use two queries: one that pulls the value you want to highlight and one that pulls everything else. If the highlighted item is identified because it's the 6th, this approach would be just as hard as yours, but if it's highlighted because of some other factor (a taxonomy term, or some other field value) than this approach would likely be easier. You can have 1 query that generates the listing page, and a second with a block display that's placed at the top of your listing page.

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


# Question
Title: How to pass along current $form_state for an #upload_validators callback?
I have a managed\_file #upload\_validators callback and when it is called the $form\_state does not get passed along with it. My goal is to use another field in the form to rename the uploaded file. I just need access to that during the validation. Maybe I shouldn't be using a validator callback for renaming the file and displaying in the UI immediately but this but it is all I can think of at the moment.

# Answer
> 0 votes
It appears we can use this code to get the $form\_state, however, there are no $form\_state\['values'\].

$form\_state = form\_state\_defaults(); // $form\_state is passed by reference and will be updated automatically. form\_get\_cache($\_REQUEST\['form\_build\_id'\], $form\_state);

I was able to find the value in `$form_state['field']['field_NAME']['und']['entity'][0]->field_NAME['und'][0];`

However, this will not pass along the value you set in another field without first setting an #ajax callback on that field, the callback can just return NULL, it is just to update the form.

In our case we disable the file upload field until the other field has first been set.

Hopefully this will help someone or most likely myself in a year from now.

sources: https://twitter.com/eojthebrave/status/743544054030336000 && How do I load the $form\_state for a form loaded with drupal\_get\_form?

---
Tags: forms, ajax
---


# Question
Title: Main menu display description as span tag
I modifed my main menu using the following code, but I need the `<span class="description">` elements only for the first level menu items, not for the sub-menu items.

How can I achieve this?

```
function neofelis_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';
  $element['#localized_options']['html'] = TRUE;

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }

  if ($element['#original_link']['menu_name'] == "main-menu" && isset($element['#localized_options']['attributes']['title'])) {
    $element['#title'] .= '<span class="description">' . $element['#localized_options']['attributes']['title'] . '</span>';
  }

  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

```

# Answer
> 1 votes
Looks like your friend is: `$element['#original_link']['depth'];`

You would adjust your conditional to be something like:

```
 // Not sure if top level depth is 0 or 1 for this so experiment with that a bit.
 if ($element['#original_link']['menu_name'] == "main-menu" &&
     isset($element['#localized_options']['attributes']['title']) &&
     $element['#original_link']['depth'] == 0
 ){
    $element['#title'] .= '<span class="description">' . $element['#localized_options']['attributes']['title'] . '</span>';
 }

```

Check out this comment from the drupal documentation.

---
Tags: theming, navigation
---


title: Replacement Tokens in View Template

text:
# Question
Title: Replacement Tokens in View Template
I have several fields in my view:

1. Path (excluded from display)
2. Image
3. Body
4. Button (rewritten to use \[path\])

I need to output the image like so (this is a requirement):

```
<a href='[path]' style='background: url([image]);'>TITLE</a>

```

I cannot do this using rewrite rules because of https://www.drupal.org/node/417956 which explains that views runs all rewrites through `filter_xss_admin()`. This function strips out the style attribute on the a tag.

I am attempting to implement this in a view template, specifically the `Field Content: Image (ID: Image)` template:

```
<?php

/**
 * @file
 * This template is used to print a single field in a view.
 *
 * It is not actually used in default Views, as this is registered as a theme
 * function which has better performance. For single overrides, the template is
 * perfectly okay.
 *
 * Variables available:
 * - $view: The view object
 * - $field: The field handler object that can process the input
 * - $row: The raw SQL result that can be used
 * - $output: The processed output that will normally be used.
 *
 * When fetching output from the $row, this construct should be used:
 * $data = $row->{$field->field_alias}
 *
 * The above will guarantee that you'll always get the correct data,
 * regardless of any changes in the aliasing that might happen if
 * the view is modified.
 */
?>
<a href='/' style='background-image: url(<?php print $output; ?>);'><?php print $row->node_title; ?></a>

```

I have tried this, \[path\] remains unchanged:

```
<a href='[path]' style='background-image: url(<?php print $output; ?>);'><?php print $row->node_title; ?></a>

```

and this, \[path\] remains unchanged:

```
<a href='<?php print token_replace("[path]", array('node' => $row->_field_data['nid']['entity'])); ?>' style='background-image: url(<?php print $output; ?>);'><?php print $row->node_title; ?></a>

```

I cannot find the value of the path anywhere in any of the variables. How can I output the value of \[path\] in my view template?

# Answer
Can you get the node id you are aiming for? If so, try using drupal\_get\_path\_alias()

```
$linknid = $fields['field_link_to_content']->content;

$alias = drupal_get_path_alias('node/' . $linknid);

<a href='<?php print $alias; ?>' style='background-image: url(<?php print $output; ?>);'><?php print $row->node_title; ?></a>

```

**UPDATE** \- this is how I did it, based on this answer:

```
<a href='<?php print drupal_get_path_alias('node/' . $row->nid); ?>' style='background-image: url(<?php print $output; ?>);'><?php print $row->node_title; ?></a>

```
> 1 votes

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


# Question
Title: Is it possible not to use utf8mb4 as encoding?
Due to an old version of libmysqlclient, we are stuck and can't deploy a completed site to our server. The client does not support utf8mb4. We have the datacenter who manages the server looking into the issue, but is there a way to make Drupal use the regular utf8 character set without hacking core?

# Answer
MySQL (and libmysqlclient) have a minimum version requirement of 5.5.3 for Drupal 8 (see https://www.drupal.org/node/2558615, https://www.drupal.org/node/2473301, etc).

It's not often that requirements are applied arbitrarily, so there will almost certainly be something in MySQL \>=5.5.3 that core/vendor code requires.

As such, I would have to assume that no, it's not possible to change this without hacking core. Maybe not even *with* hacking core, as vendor supplied code may rely on it.
> 6 votes

---
Tags: 8, database
---


# Question
Title: Rendering field with the help of functions
I have a field and I can render its value in a such way:

```
<?php print $entity1->field_list_of_options['und'][0]['safe_value'];?>

```

But I have many different entities at the page so I want to hide the following tail in a function in order to get something like this:

```
<?php print $entity1->Get_list(); ?>

```

How can I do it? I tried to get predefined functions in a custom module but couldn't find a proper hook. How can I handle this problem?

I wrote the following in order to collect my "tails":

`function mymodulename_getText($entityId,$field){
 return $entityId->$field."['und'][0]['safe_value']";
}`

And so, I use it in such way:

`<?php
$enityId = 2;
$entity2 = entity_load_single('entitytype', $entityId); ?>

<?php print getText($entity2, field_list_of_options); ?>
`

But I don't know how to implement my function to my custom module in order to get it in node's body where I want to print it using PHP Filter.

# Answer
The correct syntax for your approach would be:

```
function mymodulename_getText($entityId,$field){
    return $entityId->$field['und'][0]['safe_value'];
}

```

I suggest to sanitize that with a isset().
> 0 votes

---
Tags: entities, hooks
---


title: Using kint in views-view-unformatted

text:
# Question
Title: Using kint in views-view-unformatted
What is corect way to use kint in views-view-unformatted.html.twig

I do:

```
{{ kint(rows) }}

```

but I get this error.

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 20794259 bytes) in /home/inatcent/public\_html/core/lib/Drupal/Core/Render/Renderer.php on line 448

And for **{{ kint(row) }}** I get null what is ok. But I want more staff. :)

# Answer
> 3 votes
Option 1: Try to increase your php memory limit above the 250 MB.

Option 2: Don't try to debug all the rows at once.

```
{{ for row in rows }}
  {{ kint(row) }}
{{ endfor }}

```

P.S.

The reason `{{ row }}` was null, was because that variable does not exist in the template unless declared like in my example above.

---
Tags: 8, debugging
---


# Question
Title: Server Error 500 - Edit Tab of Managing Custom Fields of Custom Content Types
Alright, I've got a very irritating error with my site. Whenever I try and Edit a file or image field I get what appears to be a half-loaded page (see image below)

I have check an error log and have received this error at about the same time I was accessing this type of page...

```
 [15-Jun-2016 22:03:35 America/Denver] PHP Fatal error:  Allowed memory
    size of 134217728 bytes exhausted (tried to allocate 9332483 bytes) in
    /home/cocempro/public_html/portal/includes/database/database.inc on line 2171

```

And while double checking that maybe it wasn't just my browser, I also have received this error from Internet Edge (I don't normally use it, just thought I'd try):

```
SERVER ERROR - The server encountered an unexpected condition that prevented it from fulfilling the request. GET - http://example.org/admin/structure/types/manage/site-photograph-gallery/fields/field_-images

```

So is this with my server or my Drupal installation? I will clarify that I have found that no other field type (either text, date, summary, whatever) is affected by this, only file and image field types.

Any ideas?

------EDIT---- Oh and none of the other tabs (such as Widget settings, or delete) are affected by this error...

# Answer
> 0 votes
This turned out to be a max\_post\_limit issue, requiring I go from 128 to 256 on my PHP version configuration.

---
Tags: 7, media, files, debugging
---


# Question
Title: Is there a way to provide the login provision for anonymous user when anonymous commenting is enabled?
I have enabled provision for Anonymous commenting. But it provides the only option of

1. Your Name
2. Email Address
3. Homepage

What I would like is, above this, there should be a provision of Login. Hence this way user can see that, So he/she will have two options, either he/she can login OR he/she can comment anonymously.

What happen with current system is, Anonymous user keep on commenting as anonymous only, If there is a option of Login, then he may think about that.

So, I would like to make the system in commenting like,

> **Add Comment**
>
> ```
> **Login/create account**
>
> OR
>
> **Comment Anonymously**
>
> Your-name*  |  Email*  |  Homepage
>
> Comment field
>
> ```

**Update:**

I just need a Link, like what appears above the comments title on every drupal site, as shown in following image, `Log in or register to post comment`

Image

# Answer
Since you want to edit something in the contact form, you can use the same hook\_form\_FORM\_ID\_alter of my previous answer to alter the comment\_form.

As you can see in the comment form all author details are in an array `$form['author']`. So you need to add an item to this array and move it to the top.

```
function MODULENAME_form_comment_form_alter(&$form, &$form_state, $form_id) {
  // Any code you already have here

  // Check if the user was not yet logged in. (It would be useless to show this otherwise.)
  if (!user_is_logged_in()) {

    $form['author']['login_url'] = array(
      '#type' => 'markup',
      '#markup' => t('<a href="@login">Login</a> or <a href="@create">create account</a>', array('@login' => url('user/login'), '@create' => url('user/register'))),
      '#weight' => -10, // Play with this value to control the height.
    );
  }
}

```
> 1 votes

---
Tags: 7, users, comments
---


# Question
Title: Programmatically added comment form on node page doesn't work
I have attached a view which displays comments to basic page content type using EVA module. I've also implemented the following to have the "add comment" form displayed just above the comments list:

```
/**
 * Implements hook_views_pre_build().
 */
function mymodule_views_pre_build(&$view) {
  if ($view->name == 'page_comments') {
    if ($node = menu_get_object()) {
      $comment = new stdClass;
      $comment->nid = $node->nid;
      $form = drupal_get_form('comment_form', $comment);
      $form['#redirect'] = current_path() . '?page=' . (int)$_GET['page'];
      $header = drupal_render($form);
      $view->add_item('default', 'header', 'views', 'area', array('content' => $header, 'format' => 'full_html'));
    }
  }
}

```

It should work like this:

1. on page /node/12, which contains the node, comment list and the "add comment" form, the user enters new comment and submits
2. the page reloads quickly
3. the submitted comment appears in the comment list on the same page, together with another "add comment" form

What actually happens:

1. as above
2. user is redirected to page /comment/reply/12 which also contains the node, comment list and the "add comment" form
3. however, the previously submitted comment is lost, it doesn't appear in the database or anywhere else
4. the user can then again enter a comment and submit
5. if he does so, he is redirected to page /node/12#comment-1561, which contains the node, comment list and the "add comment" form
6. the second submitted comment is on the comment list

So there are two problems with my added form: comment is not submitted and there is redirection. What needs to be done to make it work the way it should?

# Answer
I'm not sure about the failure to submit, but `drupal_get_form` caches the form config, so making changes to the `#redirect` after calling it will be lost by the time the form submits. You'd need to use `hook_form_alter` for that change to persist.

As an alternative, you might consider the AJAX comments module. In theory that will work with a manually embedded comment form, and it'll sidestep your current issue while providing a slightly better UX for comments site-wide.
> 2 votes

---
Tags: 7, views, forms, comments
---


# Question
Title: Is it possible to setup reports per individual user when using the Commerce Reporting Module?
My project involves multiple users selling products on the site. I am liking the simple displays of the Commerce Reporting module and I am wondering if it can be set up per user.

> **For example** :
>
> User1 when logged in would see sales reports that relate to them (all products created by that user).
>
> User2 when logged in would only see products they created.

What I can see so far is that I have Views options to display Views Blocks of these charts on a specific page. That way i can make duplicate views and add a relationship. This is now where i get stuck. In the relationship options of these specific views there are no "user id" options.

> **List of relationship options**
>
> Commerce Order: Owner
>
> Commerce Order: Payment Transaction
>
> Commerce Order: Referenced customer profile
>
> Commerce Order: Referenced customer profile
>
> Commerce Order: Referenced line items
>
> Commerce Order: Representative payment transaction
>
> Commerce Order revision: Order
>
> Commerce Order revision: User

# Answer
This question seems fairly similar to the question "https://drupal.stackexchange.com/questions/141473/how-to-only-include-data-in-a-commerce-reporting-report-about-products-created-b" ... Which has a comment that might be the answer to what you're looking for ... Did "I" hereby answer "this" question?

Aso, while waiting for the Commerce Reporting handbook to get some real content (cfr. your valid comment in the other reply), you may want to look at the Visualization documentation, which includes a link to a video about Commerce Reporting (the Visualization module is the charting API used by the Commerce Reporting module).

**Be Aware**: I'm a co-maintainer of the Visualization module
> 1 votes

# Answer
You need to add a relationship to the Commerce Products through the "Commerce Order: Referenced line items" relationship. From there you should be able to filter on the creator of the product entity.
> 0 votes

# Answer
Make a clone of the sales view. Add a relationship commerce-order with line-item. add another relationship line-item with product. add another relationship product with user (creator)

Then add a contextual filter setting the default parameter to be based on current logged in user.

Note the user has to have permission to view any orders in order for the view to work.

Hope that helps.
> 0 votes

---
Tags: commerce, charts, log-messages
---


title: FAPI #prefix YAML filter tag

text:
# Question
Title: FAPI #prefix YAML filter tag
```
  button_submit:
   '#prefix': '<div class="col-md-4 text-right">text<button>button text</button>'
   '#suffix': '</div>'
   '#value': Send
   '#type': submit

```

I have the code above in YAML form. When I edit the code, I see the button tag; when rendering, only the following markup is left.

```
<div class="col-md-4 text-right">
ALGOasd
<input id="edit-button-submit" class="button js-form-submit form-submit" type="submit" value="Send" name="op" data-drupal-selector="edit-button-submit">
</div>

```

It´s clear that I have some filter, but I can't find it out. I also tried putting a `<button>` in a container item, but the same thing happens.

Why does this happen? How can I fix it?

# Answer
> 0 votes
You need to include the #allowed\_tags property which is applied to #markup, #prefix, and #suffix. (See: Pass raw html to #markup)

```
button_submit:
  '#prefix': '<div class="col-md-4 text-right">text<button>button text</button>'
  '#suffix': '</div>'
  '#value': Send
  '#type': submit
  '#allowed_tags':
    - div
    - button

```

---
Tags: forms, 8
---


# Question
Title: how to create a custom form and embed it on a node
Right now, I want to create a form which only have an email textfield and a submit button.

This is what I did in my "custom\_request\_price.module":

```
function custom_request_price_form(&$form, $form_state) {

  $form['email'] = array(
    '#type' => 'textfield',
    '#size' => '20',
    '#maxlength' => '255',
    '#required' => TRUE,
  );
  $form['email']['#attributes']['placeholder'] = 'Email Address';

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

```

However, I don't know how to embed it to my article. I don't want to add this into a menu or make this as a new page. What I want to do is: when I open my article page, it directly showed up and visitors can enter their email address and simply to click "send" button.

**My search:** For doing this, I thought I need to add "drupal\_get\_form()" in my node-article.tpl.php to show this form on my article page. I am totally new for doing this. I don't know how to add form-ID in my custom module. Also, I don't know whether this is the correct way to embed my form.

# Answer
> 1 votes
The way I would go about it is to create the form within a Drupal block. In this manner, you could configure when & where the form could be placed on the page and with what types of content. You also wouldn't have to edit your theme if you'd ever wanted to add the form to another type of content.

Look at `hook_block_info()` & `hook_block_view()`, and reference the user module's implementation (`user_block_info()` & `user_block_view()`) for how it create its user login block.

---
Tags: 7, forms
---


# Question
Title: Unable to edit node translation other than current language
On my multilingual site I seem to have problem at `admin/content` when editing a particular translation.

I have a Contact Us page, translated:

```
Contact Us [EN], node/286
Contact Us [ES], node/300

```

I don't have an explicit Path Translation set, but the nodes are bound together, in the Translate tab.

Now the problem is, that when my current language is English and I want to edit the Spanish version from the Content listing, the edit link takes me to its English version `(node/286)`. Apparently the admin overlay inherits the language prefix and forces the English translations to open.

What luckily works correctly is editing the node from within its view (by hitting the Edit tab).

Is this normal behavior?

# Answer
> 0 votes
Anyone having this issue should read https://www.drupal.org/node/1399506.

The problem arises from the feature Language Path Checking within the Global Redirect module. Use the dev version to correct the problem.

---
Tags: i18n-l10n, users
---


# Question
Title: Receiving Access Denied with altered CRUD paths in ECK
I have altered the CRUD paths for entity types and bundles created with Entity Construction Kit. The change propogates correctly, all views which use the ECK provided views fields (Link, Edit, Delete) are now using the correct URL.

The issue is when trying to hit those URL's, the page is always access denied. What I have found in my troubleshooting:

1. The menu is built within eck.entity.inc. I have used the following test code, inserted at line #93

```
if ($bundle->name == 'inventory_item' && $action_label == 'Edit') {
  print_r($access_args);
  die();
}
// result = Array ( [0] => edit [1] => inventory_item [2] => inventory_item [3] => 5 )

```

Note that the `$access_args` does contain the correct entity id (index 3 in the result array).
2. The menu `access callback` is `eck__entity_menu_access()` which is found in `eck.module` and I have included the following there, inserted at line 762:

```
if ($action == 'edit' && $bundle_name == 'inventory_item') {
  print_r(func_get_args());die();
}
// result = Array ( [0] => edit [1] => inventory_item [2] => inventory_item [3] => )

```

Note that index 3 (`$entity_id`) is null now.

I can't figure out where the entity id is lost. I don't think it matters, but I did check the loader, `eckentity_load()` and it is loading the correct entity.

Any ideas why the entity id is not making it to the access callback?

# Answer
It would be helpful to see an example of an original ECK path (for a single entity), and then your updated one. If you re-arranged the arguments, or changed their quantity, the `access arguments` passed to the access callback will not be correct.

You will almost certainly need to implement `hook_menu_alter` to update the `access arguments` property of ECK paths.
> 0 votes

---
Tags: 7, entities
---


# Question
Title: Update command won't work for multisites
I have a Drupal 7 site with a half-dozen multisites/subsites and I am trying to setup Drush so that I can run my modules updates from the command line for the subsites. Running Drush for the main site works fine. Running Drush for ONE of the sub sites works fine. However for about 5 of the subsites I can run commands like

```
drush @subsite status

```

or

```
drush @subsite updb

```

but if I try to run

```
drush @subsite update

```

or

```
drush @subsite ups

```

I get an error:

```
Command pm-updatestatus needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command.

```

So I don't understand what makes all the other sites different from the one, or why some commands would work and others not. I am running these commands from my main Drupal install path:

```
/var/www/html
```

What am I doing wrong, and how can I get update to work for my subsites?

It's worth noting that the majority of these subsites were setup at a time when I didn't necessarily know what I was doing, so I can only describe their configuration as "wacky". One of the affected sites is setup in a fairly standard way and the working subsite is of the "wacky" variety, however, so I don't expect that's the problem.

EDIT: Because it is working for one site and not others, I'm wondering if it's a file permission issue. What user does Drush run as, and what level of access does it needs to which files? In my case, I am working on Ubuntu.

# Answer
As a test, change your working directory to the directory that contains the settings.php file for the site you want to operate on, and then run `drush pm-updatestatus`. See if that bootstraps correctly. If so, the issue is with your alias files. These should work, so long as 'root' and 'uri' are set.

Note, however, that if all of your contrib modules are in `sites/all`, then one run of pm-updatecode will update the code for all sites. You will need to run `drush updatedb` for every site that shares any code updated by the last run of pm-updatecode. Drush does not manage this for you, even with pm-update (which runs updatedb on just one site).

This is the added cost of multisite configurations -- you have to be a lot more careful with your update processes, and must update all of the sites at the same time.
> 0 votes

# Answer
Okay, after digging further I figured out what the issue was. It was indeed having to do with my so-called "wacky" Drupal subsite config. Basically, the problem was with the database configuration. For my sites, I want each subsite to have its own database EXCEPT FOR all the tables related to the user accounts, such that a user can create/login to their account from any of the sites. Previous to this, I had things configured oddly in the sense that my database configuration in the settings.php file set the MAIN site's database as the database, but then set the default prefix to the subsite's database, and specified exceptions for the user account tables. The reason SOME of the sites were working okay, is because before I knew what I was doing, I would just give the subsites' tables a prefix, but they would still live in the main site's database. Complicated, I know. Anyways, the solution was to reverse the settings.php config so that the subsite's database is specified as it's own and I use the table prefixes to specify the user account tables, which are the exception. I.E., my config now looks like this:

```
mnpn = subsite database
drupal = main site database

```

```
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'driver' => 'mysql',
      'database' => 'mnpn',
      'username' => 'drupaluser',
      'password' => 'XXXXX',
      'host' => 'localhost',
      'port' => '',
      'prefix' =>
      array (
        'default' => '',
        'users' => 'drupal.',
        'users_roles' => '',
        'users_uid_seq' => 'drupal.',
        'sessions' => 'drupal.',
        'authmap' => 'drupal.',
        'role' => '',
        'sequences' => 'drupal.',
        'profile_fields' => 'drupal.',
        'profile_values' => 'drupal.',
        'variable' => '',
        'actions' => ''
      ),
    ),
  )
  );

```
> 0 votes

---
Tags: 7, drush, multi-sites
---


# Question
Title: "Cannot use a scalar value as an array" error
I'm getting a bunch of PHP errors every time the cron runs. I can't seem to track down what is causing them all.

> Cannot use a scalar value as an array in drupal\_render() (line 5822 of /var/www/vhosts/tlthost.net/httpdocs/includes/common.inc).
>
> Cannot use a scalar value as an array in drupal\_render() (line 5767 of /var/www/vhosts/tlthost.net/httpdocs/includes/common.inc).
>
> Invalid argument supplied for foreach() in element\_children() (line 6300 of /var/www/vhosts/tlthost.net/httpdocs/includes/common.inc).
>
> Cannot use a scalar value as an array in adaptivetheme\_page\_alter() (line 235 of /var/www/vhosts/tlthost.net/httpdocs/sites/all/themes/at\_core/inc/alter.inc
>
> Cannot use a scalar value as an array in user\_relationships\_ui\_page\_alter() (line 247 of /var/www/vhosts/tlthost.net/httpdocs/sites/tlt/modules/user\_relationships/user\_relationships\_ui/user\_relationships\_ui.module).
>
> Cannot use a scalar value as an array in fbconnect\_page\_alter() (line 568 of /var/www/vhosts/tlthost.net/httpdocs/sites/all/modules/fbconnect/fbconnect.module).
>
> Cannot use a scalar value as an array in block\_page\_build() (line 269 of /var/www/vhosts/tlthost.net/httpdocs/modules/block/block.module).

I'm hoping you know what's causing this one. it might help me figure out the rest of the errors.

# Answer
> 2 votes
Sometimes these error messages come up on my sites if cron is run while the site is in maintenance mode. I'm guessing the maintenance mode template for our site has something to do with it, but it could be a variety of things.

When cron runs, it is still running through Drupal's theme system, so you probably have something awry in either your theme or one of your custom modules. Does this happen every time cron runs, or just sometimes?

A final troubleshooting step would be to install elysia\_cron and run each cron task individually to see which one might be causing all these errors.

See also: Warning: Cannot use a scalar value as an array

# Answer
> 1 votes
That error occurs when you use a stdClass() type object as an array.

e.g

Given a node object:

```
$node->title = 'foo'; // right
$node['title'] = 'foo'; // wrong

```

Perhaps that will help debug the solution, maybe it's a php syntax issue in a hook\_cron implementation

# Answer
> 0 votes
Drupal is set to skip the cron run when in maintenance mode. I suggested this years ago, because I felt if you're in maintenance mode, you are most likely trying to prevent database changes while taking backups. Someone else wrote a patch, and that's how it works now.

---
Tags: 7, cron
---


# Question
Title: PDOException : SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'registration
Using: commerce+entity registration+commerce registration

During the checkout sequence, after completing the registration step, I get this fatal error:

> PDOException : SQLSTATE\[23000\]: Integrity constraint violation: 1062 Duplicate entry 'registration-144-0-0-und' for key 'PRIMARY': INSERT INTO {field\_data\_field\_nom} (entity\_type, entity\_id, revision\_id, bundle, delta, language, field\_nom\_value, field\_nom\_format) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2, :db\_insert\_placeholder\_3, :db\_insert\_placeholder\_4, :db\_insert\_placeholder\_5, :db\_insert\_placeholder\_6, :db\_insert\_placeholder\_7); Array ( \[:db\_insert\_placeholder\_0\] =\> registration \[:db\_insert\_placeholder\_1\] =\> 144 \[:db\_insert\_placeholder\_2\] =\> 144 \[:db\_insert\_placeholder\_3\] =\> formulaire\_inscription \[:db\_insert\_placeholder\_4\] =\> 0 \[:db\_insert\_placeholder\_5\] =\> und \[:db\_insert\_placeholder\_6\] =\> dfgh \[:db\_insert\_placeholder\_7\] =\> ) in field\_sql\_storage\_field\_storage\_write() (line 514 in /home//public\_html///modules/field/modules/field\_sql\_storage/field\_sql\_storage.module).

I have tried to disable some rules that could be problematic, to disable multilanguage (entity registration have some problem whit multilang)... nothing.

What can be the cause of this error?

Thx

# Answer
> 0 votes
If anyone stumble on this error again, note that it is due to corruption in the database. In this case, the registration tables got corrupted at some point.

Just unninstall everything registration related, and start anew.

Thx.

---
Tags: commerce, entities
---


title: Adding Bootstrap Tabs to a content view

text:
# Question
Title: Adding Bootstrap Tabs to a content view
I've created a custom content type which I want to display in a view using Bootstrap's Tabs component.

I've found this tutorial of sorts, but I'm a bit lost trying to process it all (I'm very new to Drupal).

It looks like it does almost exactly what I need it to. I basically need to display the content I have in that view to be placed inside Bootstrap's Tab markup. I know the theme I'm using already has Bootstrap embedded and available, but I can't seem to figure out to make a "Bootstrap Tabs" option available in the "Style" option of my page view.

Can anyone share some pointers on where to start looking for a solution and on what I need to read up on?

**EDIT:**

I've been following the tutorial and was able to get somewhere with it. Right now, a `Format` option for Bootstrap Tabs shows up when editing the view and, when selected, it is followed by a form questioning which field should be used for navigation - as intended, I recon.

Although right after answering the form question, above the preview area, an error message shows up stating:

> Template "modules/custom/bootstrap3tabs/templates/bootstrap3tabs.html.twig" is not defined (Drupal\Core\Template\Loader\ThemeRegistryLoader: Unable to find template "modules/custom/bootstrap3tabs/templates/bootstrap3tabs.html.twig" in the Drupal theme registry.).

Which in turn also shows up in the view after saving.

Can anyone share some pointers on why this happens and how to fix it?

# Answer
you can also use the https://www.drupal.org/project/quicktabs for this (The Quick Tabs module allows you to create blocks of tabbed content, specifically views, blocks, nodes\* and other quicktabs\*. You can create a block on your site containing multiple tabs with corresponding content. Clicking on the tabs makes the corresponding content display instantly, using jQuery. With the 6.x-2.x branch, this can be done in either ajax or non-ajax mode:) available for drupal 8
> -2 votes

---
Tags: views, theming, 8, plugins
---


title: Commerce Price Field formatting

text:
# Question
Title: Commerce Price Field formatting
I'm using a view which is rendering the Product displays as DisplaySuite modes.

Right Now, the generated code for the price looks as follows.

```
<div class="commerce-product-field commerce-product-field-commerce-price field-commerce-price node-12-product-commerce-price">HK$100.00<span>/Month</span></div>

```

In order to achieve a similar rendering as

I need to split the decimal part and the currency into their own markup.

Any idea about how to do that in a clean fashion ?

# Answer
I have found a working solution for that, even if there might be a more clean solution, at least it works.

In the template.php file of my theme in use I put the function :

```
  function MYTHEME_preprocess_field(&$vars) {
  if($vars['element']['#field_name'] == 'commerce_price') {
    // dpm($vars);
    $price = $vars['element'][0]['#markup'];
    $parts = explode(".",$price);
    $parts[0] = str_replace('HK$', '',$parts[0]);
    $markup = '<span class="currency">HK$</span><span class="units">'.$parts[0].'</span><span class="decimal">.'.$parts[1].'</span>';
    $vars['items'][0]['#markup'] = $markup;
  }
}

```

Once this saved, a markup on which it is possible to act is generated. The "per month" par is supplied by a field suffix using Display Suite. The rest is some easy CSS to style the output.

Another method is possible. At uncommenting the dpm($vars) line in the code above, some candidate template files names for the field are provided.
> 2 votes

# Answer
Maybe using CSS nth child? http://www.w3schools.com/cssref/sel\_nth-child.asp to set the decimal font size and then z index and right margin the per month?
> 0 votes

---
Tags: theming, entities, commerce, display-suite
---


title: Can`t alter views filter option

text:
# Question
Title: Can`t alter views filter option
I need to alter my view filter option!

The view must display some comments. Every comment, that I need, has custom field "node reference". And I want to filter comments by this field.

E.g. if my view displays on page with node 9(nid), view should return me all comments where "node reference" = 9;

I have found such solution: http://www.drupaldump.com/view-3-alter-filters-programmatically

And try to rewrite for me:

```
function mymodule_views_pre_view(&$view) {

  if ($view->name === 'contest_winners') {
    $view_filters = $view->display_handler->get_option('filters');

    $node_id = arg(1);

    $view_filters['field_for_contest_nid']['value'] = null;
    $view_filters['field_for_contest_nid']['value'][$node_id] = inttostr($node_id);
    $overrides = array();
    $overrides['filters'] = $view_filters;
    foreach ($overrides as $option => $definition) {
      $view->display_handler->override_option($option, $definition);
    }

    dpm($view_filters); // here value = node_id, but view use default value

  }

}

```

But this does not help: view uses default value.

Maybe i have made some stupid mistake?

# Answer
It seems you read not complete article :(. before this method getting call we should tell hey views we want use your hooks

something like in your `.module` file

```
/**
* Implements hook_views_api().
*/
function yourmodule_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'yourmodule') . '/views',
  );
}

```

Then create a views directory, create `yourmodule..views.inc` file there and put your code there ( please be sure your code getting execution with some `dsm` or `die()` ).

I know your change your way but I think it help you in another task.

take a look at : this article
> 0 votes

---
Tags: views, hooks
---


# Question
Title: How can I create a menu link that shows only to authenticated users?
How can I create an user account menu link that shows up only to registered/authenticated users in Drupal 8? I do not want anonymous users to see it.

For example, I want to have "add node" menu link.

( When anonymous users come to drupal sites they just see "login" on user account menu . When register users come to drupal sites they see "my account" and "logout" . I want show anonymous just "login" and for register users "my account","add node" and " logout . )

# Answer
> 4 votes
> Long story short, you create 2 different Menu versions and give each version different visibility rules.

**All you gotta do is configure your menu link block**

**Then in Roles, check mark ☑ Authenticated users and you may want to also ☑ Administrator**

**Now create another Menu (`/admin/structure/menu`) which does not have the "add node" link.** Then go to blocks (`/admin/structure/block`) in **Primary Menu** (Assuming you're using Bartik, may have a different name if you're using a custom theme) click add, and add the Menu you just created and configure it.

This time for Roles, only check mark ☑ Anonymous

> **PS:** In pages you can restrict so it only shows up in certain pages.

# Answer
> 3 votes
An "add node" menu link is only shown to users who have the permission to create such node. So if you give the permission to authenticated users, and not to anonymous users, you're done.

If you have other samples of links that have a related permission, then use a similar approach for that permission (don't grant it to anonymous users). If some link doesn't have such permission, then go for the approach described in the answer from @No Sssweat.

---
Tags: users, 8
---


# Question
Title: Redirect (or show the node) taxonomy term page to node, if there's only one node associated with that term
So I'd like to redirect taxonomy term page or show the full content of the node on taxonomy page if there's only one node associated with that term.

# Answer
> 1 votes
My solution is handle it in `hook_preprocess_page`(maybe there is another or better solutions but this is good too)

put this in `template.php`

**first solution(maybe not worked)**

```
function YOURTEMPLATE_preprocess_page(&$variables) {
  if (arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))) {
    $tid = arg(2);
    $items = taxonomy_select_nodes($tid;
    if(count($item)==1){
         drupal_goto('node/'.$items[0]->nid);
     }
    }
}

```

**Alternative solution**

```
function YOURTEMPLATE_preprocess_page(&$variables) {
  if (arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))) {
    $tid = arg(2);
    $items = taxonomy_select_nodes($tid);
    if(count($items)==1){

         //another solution is set a variable in preprocess and in page.tpl.php or your taxonomy tempalte page redirect it
         $variables['soheil_redirect_tax'] = array('path' => url('node/'.$items['nid']));

    }
  }

```

**if first solution (drupal\_goto) not worked in page.tpl.php or your custom template for terms page handle redirect**(I mean in `page.tpl.php` file or `taxonomy--term.tpl.php` file) with

```
 if(isset($soheil_redirect_tax)){
    drupal_goto($soheil_redirect_tax['path']);
 }

```

---
Tags: taxonomy-terms, hooks, redirection
---


title: How to save JSON with a node

text:
# Question
Title: How to save JSON with a node
What would be the best way to store JSON content with a node? Can I just use a text field for this or will this destroy the data?

I do not need to query this data, only load it occasionally.

I'm using Drupal 7 and MySQL 5.5.

# Answer
> 2 votes
Text fields can store JSON data since JSON, by definition, is a serialized format. This is provided the JSON data fits the size of your text field. If you go this route, you should make sure your field is validated for valid JSON before saving and is under your storage limits.

If you want something more versatile, you might want to add your own custom field with the Field API. There's also the JSON Field module, but it only has a D8 release.

# Answer
> 0 votes
As Sahwn said, JSON is simple text and you can store/read it in longtext field,(\**Notice set html format to plain, maybe CKEDITOR cause unwanted results).

and finally according to my experiences if you JSON not minified try to minify it with some think like

(first add custom submit handler for your form and in submit handler minify it to minimize database memory used )

```
$form_state['yourfield_name'][0]['safe_value'] = preg_replace('/\s(?=([^"]*"[^"]*")*[^"]*$)/', '',$form_state['yourfield_name'][0]['safe_value']);

```

http://jsonviewer.stack.hu/

---
Tags: 7
---


# Question
Title: how to import from csv file to EntityForm
I have two drupal sites with exactly same entity forms, I would like to import entityform submissions from site A to entityform submissions site B.

I had a look into feed modules which works very well to import node but there is no option for to import data into entityform.

# Answer
There doesn't seem to be any contributed module available for importing Entityform submissions from CSV.

You can simply try creating a small module which read CSV data and import Entityform submissions. To do this you can simply write a batch operation using Batch API and create Entityform Submissions using code snippet available here.

Another way could be to try Bundle Copy module that works with major entity in Drupal Core and also provide simple API for new/custom Entities. I've not tried Bundle Copy with Entities other than Node. You can try if this works with Entityform if not you can use its API and extend it.
> 1 votes

# Answer
use Entity Reference Feeds and Feed Entity Processor

**\> Use case**

> How this module works is perhaps more easily conveyed through a simple example:
>
> Lets say we are importing products, together with product-reviews as XML from a third pary API. This happens to be an ill-designed API, and the reviews are nested in the XML as children of the products they belong to, and cannot be fetched separately.
>
> There are multiple solutions to this problem. One could for example create an API wrapper, preprocessing the file and separate products and reviews in two xml-feeds. This is a bit of work though, comes with additional issues like making sure reviews are imported before products etc.
>
> Entity reference feeds provides a "quick and dirty" solution. After creating an entity reference to product reviews in the product bundle, fields and properties of product reviews will be available as mapping targets in the mapping settings of the product importer. Products and reviews will now both be imported in the same run, product reviews created "in place" as values of the entity reference field.

and if you'll try it by yourself I suggest custom feed mapper instead your CSV parser.how use custom field mapper feeds
> 0 votes

---
Tags: 7, forms, importing-exporting, entities
---


# Question
Title: How to show block on pages with URLs containing a question mark ( 'searchquery' )?
For example I end up with url's like

```
example.com/viewname?f=[0]field_name=%3A21

```

I want to make a block visible on pages like the above but **not** when only the view is displayed.

Only the view will looks like this: `example.com/viewname`

So my thought was to set the block visibility setting to be only visible on:

`example.com/viewname*`

That didn't work ( block did not show up ) so i tried:

`example.com/viewname?*` , `example.com/viewname?f*` and `example.com/viewname/*`

No success.

**EDIT:**

There are some options:

**1)** Creating a block in custom module could be a solution.

**1a** Setting visibility to 'none' by unsetting the block content and title ( which I have chosen to use for now )

**1b** Enabling the PHP filter module and adding a block setting visibility restrictions like so:

```
/**
  * Implements hook_block_info().
  */
function mymod_block_info(){
  $blocks['mymod_job_agent'] = array(
    'info' => t('block description'), //The name that will appear in the block list.
    'cache' => DRUPAL_CACHE_PER_ROLE, //Default
    'region' => 'sidebar_first', // assign block region
    'status' => 1, // enable the block
    'visibility' => BLOCK_VISIBILITY_PHP, // set visibility to use the result of pages
    'pages' => '<?php return TRUE; ?>',
  );
  return $blocks;
}

```

Drawback: since hook\_block\_info is called upon module install only you cant change your code without reinstalling the module. And putting php code in de `pages` just doesn't feel right. So I think we can cross option **1b**.

**2)** Another solution would be to use the Block Conditional Visibility by URI Query Parameters module but I couldn't figure out how to use this for this use case.

Reading the comments this is something that should be done in the theme layer...

Hope this helps anyone searching for a similar question. feel free to edit update my question/answer to improve it!

# Answer
> 1 votes
In the end I created the block using code: Here's how I've done it:

1) Create a new module or copy an existing one and rename it.

2) Create a block using the hook\_block\_info() hook. For example:

```
/**
 * Implements hook_block_info().
 */
function mymodule_block_info(){

  $blocks['mymodule_block_name'] = array(
    'info' => t('Block description'), //The name that will appear in the block list.
    // if you cache blocks on your page and you use the query string for visibility
    // the page doesn't change so you need to set it to DRUPAL_NO_CACHE
    'cache' => DRUPAL_NO_CACHE,
    'region' => 'sidebar_first', // assign block region
    'status' => 1, // enable the block
  );

  return $blocks;
}

```

3) Create the content of the block using hook\_block\_view():

```
/**
 * Implements hook_block_view
 */
function vacancies_block_view($delta = '') {
  // declare empty block
  $block['subject'] = '';
  $block['content'] = '';

  // switch block name
  switch ($delta) {

    case 'mymodule_block_name':
      if( TRUE /* put visibility condition here */ ) {

        $block['subject'] = 'Block title';
        $block['content'] = 'Hello world!';

     }
    break;
  }

  return $block; // dont forget to the return the $block!
}

```

4) upload your code, enable the module, clear cache and check the result.

As suggested by Jimajamma you can hide your block by setting the block subject and content to `''` Makes it nicer to put in your condition in php code then using the php filter module.

# Answer
> 4 votes
You can use the Block Conditional Visibility by URI Query Parameters module to control block visibility via query string.

> Controls block visibility by URI Query Parameters. Drupal natively allows blocks to be placed on pages by using their paths, however, this module allows administrators to also display modules based on url query parameters.

# Answer
> 1 votes
I have always put any fancy visibility logic inside the block view hook, eg,

```
$block['subject']='';
$block['content']='';

switch($delta) {

  case 'foo':

     if ( // visibility condition is true ) {
        // create the block['subject'] and block['content'] here
     }

     return $block;

}

```

since, if `$block['content']` is empty, the block won't be displayed. This might be totally "against the drupal way," but I feel it makes for easier to read code and also takes one less php eval out of the loop.

ADDITION: This appears to get some approval here: Is there a way to set block visibility programmatically without using the PHP Filter module?

# Answer
> 0 votes
You could use the Rules block visibility module for this (with no custom coding). Here is a quote from its project page:

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

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

For an illustration of how to use this module, refer to my answer to "How to stop a Views block from displaying to admins, such as user/1?". It includes a Rules Component (in Rules export format), which you should replace by this variation of it to make it match your specific question):

```
{ "rules_block_visibility_popular_courses" : {
    "LABEL" : "Hide block for filtered course view",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false }
    },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:path" ],
          "match" : "viewname?",
          "operation" : "starts"
        }
      }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}

```

Adapt the value of `viewname` to fit your needs. And to further enhance the above Rules Component (to make it more generic), just replace the Rules condition in it with something using an appropriate regular expression (ie to check if the current path contains a "`?`".

---
Tags: blocks
---


# Question
Title: Is there a way to set block visibility programmatically without using the PHP Filter module?
By enabling the core PHP Filter module, I can use PHP code to set the visibility of a block in the block configure page.

But I don't want to enable the PHP filter module for security measure. So **is there a way to do it in custom module**? I can't find a hook doing so. And a close hook `hook_block_view_alter` can only change the block content.

# Answer
Yes. Setting the blocks content to false will hide it from the display and will hide the region if there are no other blocks present. I'd imagine you would need a setup similar to the following:

```
$block['content'] = _my_module_custom_block();

...

function _my_module_custom_block(){
    if( HIDE_CONDITION )
        return false;
}

```
> 13 votes

# Answer
The Rules block visibility module is another alternative available ... ***which doesn't require the PHP filter to be enabled***. Here is a quote from its project page:

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

Moreover, as per the "*if you can do it with Rules, you can use it to control block visibility*" above, you have the power of Rules available to implement all sorts of custom logic (cfr. the "programmatically / custom module" part of your question).

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

---
Tags: 7, blocks
---


# Question
Title: How to install a local module file with drush?
I have a local environment I am working on and I want to use drush to install a local file/module I have that was created by a exported feature. The reason I am not doing it with update manager is because its giving me a ftp error and rather than try to solve that, I would rather bypass it completely with drush (and since drush is faster anyway).

So basically I have my main site in www/var/mysite

And i have the exported feature module in my home directory / downloads.

So how do I get drush to upload and enable my local file to my drupal site?

# Answer
If you already have the module / feature that you want to install on your local disk, simply copy the files to **DRUPAL\_ROOT**/sites/all/modules. Some folks also like to create "contrib", "custom" and "features" directories inside of "modules" to better organize their files.

Once you have your files in place, run `drush en featurename` to turn it on.
> 5 votes

---
Tags: 7, drush
---


# Question
Title: How to go about creating location selector: a languages like "countries" global variable?
I'm interested how should I approach creating a language switcher like countries switcher?

The idea is that I wish to have country specific content and restrictions (just like with languages) but I want to allow all languages for every country.

Ideally I'd need to have the country value as a global variable and even in the cookies. A great bonus would be if I could assign it to the url like languages (../en/.. -\> --/us/en/..) without ruining routing for core or path auto/url aliases etc..

But I don't know how and where to start and can't even find materials on people having done anything similar before.

My train of thought here would be the following:

* Create custom module
    + Create a countries database/list
    + Set the country as a global variable somehow
    + Set the country as a cookie and fetch on every page load (or if possible to and from url)
    + Create the selector widget

Any ideas how to better understand what I'm facing and recommendations for tackling this? Also a lot of big corporations have location selectors with that locations languages which restrict content, how is this not possible with Drupal? (Couldn't even find anything for D7)

# Answer
> 0 votes
This is a typical use case for domain access:

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

This module includes a domain switcher, which would be the selector widget you asked for. There is only a dev version for D8. This is a heavy weight module and until now I did avoid using it in D8 and did some custom coding for the functionality I need. To get some ideas I would investigate this module.

---
Tags: 8
---


# Question
Title: How to make gmap marker tooltip display node title without tags?
My project uses gmap of nodes locations. When marker is hovered popup tooltip displays link to node with node title in it. Any possibility to display node titles in marker tooltips without any tags?

# Answer
Quote from the Comparison of mapping modules:

> GMap is considered a legacy module.

So maybe you want to have a look at the IP Geolocation Views & Maps module. Partial quote from its project page:

> Despite what the name may suggest, IP Geolocation Views & Maps (IPGV&M) is first and foremost a mapping engine.
>
> The module makes it very easy to create Views-based mapping solutions using the map renderer of your choice (**Google**, **OpenLayers** or **Leaflet**) with any location storage module of your choice, e.g.:

> This allows you to bring together modules and feature sets that without IPGV&M you would not be able to combine.
>
> Like beautiful animated marker clustering on Google or Bing or Mapbox ... any of various map providers.
>
> But more importantly IPGV&M adds some features you won't find as conveniently packaged elsewhere.
>
> These include marker differentiation based on field values or ranges (2nd screenshot) with or without font icons, various centering options, super-imposing the current visitor's location, allowing multiple content types to be displayed on the same map, full screen button and mini-map inset (bottom screenshot), polygon support (Geofield), marker tags and tool tips and cross-highlighting of associated content on the page when markers are hovered (and vice versa).

Head over to its (impressive) project page for even more information about it. That project page also includes various screenshots.
> 0 votes

---
Tags: google-maps, tooltips
---


# Question
Title: Drush 8.1 Drupal 8 throws PDOException: SQLSTATE[HY000] [2002] on MAMP
After installing Drupal 8 (via installation wizard), trying to run any drush command, getting below error:

```
drush en views_ui
PDOException: SQLSTATE[HY000] [2002] No such file or directory in core/lib/Drupal/Component/DependencyInjection/PhpArrayContainer.php on line 79 Drush command terminated abnormally due to an unrecoverable error.

```

Drupal version: 8.2.x

Drush version: 8.1-dev

# Answer
Make sure your database host setting is 127.0.0.1 instead of localhost.
> 11 votes

---
Tags: 8, drush
---


# Question
Title: How to set permissions for cron for other roles (not administrators)
Hello I need to set permissions for editor role. The editors need cron to send maillists/newsletters. How do I make cron available for them? It seems there is no way.

# Answer
> 1 votes
The permission to run cron in Drupal 7 is *Administer site configuration*.

**Warning: Give to trusted roles only; this permission has security implications.**

It can debated whether it is a good idea to give permission to the editor role, as opposed to running cron automatically every five minutes.

However, in my use case cron does some heavy lifting every time it runs, so running it every five minutes would make my site very slow, creating a bad UX. I've scheduled it to just run cron *automatically* once per day (at 3 am). I use **Notify** to distribute newsletters, and it in turn relies on cron, so I permit trusted editors who use the site for sending out newsletters hit cron manually if there is some urgency about getting a newsletter distributed.

The path to the Drupal cron UI is `admin/config/system/cron`. It is probably a good idea to add this path to some menu the editor has access to make it easy to find.

# Answer
> 1 votes
You don't need any Drupal permission to run cron.php. The only permission Drupal uses is for the administrative page containing the link to run cron, but on Drupal 6 you can just use the link to http://yoursite.com/cron.php. On Drupal 7, you need to use the cron key, or Drupal will refuse to run cron, but the correct link is given on admin/config/system/cron.

>

That said, it is probably excessive to run cron tasks more frequently to just be sure the emails are sent more quickly, since cron tasks on Drupal don't do just that. I would rather investigate on which method the module you are using has to allow you to send the email more often, or immediately.

# Answer
> 0 votes
I personally wouldn't. If e-mails need to be sent regularly, I'd just set your server to hit Cron every 5 or so minutes. That way, when an editor sends an e-mail through your site, Cron will run at MOST 5 minutes later and send the message. If you feel every 5 mintues is too much, you can use Elysia Cron to fine tune what runs at what time (eg you can have your mail stuff run every 5 minutes, and everything else on the hour..day..week etc.).

---
Tags: cron
---


# Question
Title: Drupal front page blog entries custom sort order
I have two blog entries which as defaults displays in front page.

1.) Submitted by admin on Thu, 06/16/2016 - 13:32 displays second
2.) Submitted by admin on Thu, 06/16/2016 - 13:33 displays first

I would like to display these at any point of time in a custom order, probably using custom field

# Answer
> 1 votes
You may add your custom field "sort\_order" to the blog content type, then create a page view (/admin/structure/views/add) for the blog content (just like node does it in the "frontpage" view - you may even copy that view and restrict the nodetype to blog in your copy).

Then change the "sort criteria" in the view to your sort\_order custom field.

Then you're done.

---
Tags: 7
---


# Question
Title: CKEditor Link a content with rule as a hypelink with title and url to a custom field
I would like to add a hyperlink entry in a blog which points to a internal content URL with different content type which needs to be display for authenticated users.

1.) The hyperlink should show the title of the content

2.) The hyperlink URL should be mapped to a custom field

3.) The hyperlink should not be visible to a chosen user and should be customizable

Is this possible in drupal ckeditor? or should we write PHP for it using PHP filter?

# Answer
> 1 votes
You don't want to use PHP Filter. That's for embedding PHP code into a Drupal content field and is not what you want (unless you're willing to give your content creators access to PHP code that could potentially break the site).

You want to implement 2 things to provide your custom functionality in a Drupal module:

1. **Provide a custom plugin to CKEditor:** You'll need to build your own CKEditor plugin which will do the work of building your custom markup (e.g. internal URL, title, mapped field, uid, etc.) to embed into CKEditor, You'll need a custom module to define it via `hook_ckeditor_plugin()` in D7 (or a CKEditor plugin in D8), then enable it in the Drupal CKEditor module settings.
2. **Provide a custom input filter:** After your CKEditor button provides the markup for your custom link, you'll need a custom input filter so you can process the CKEditor markup for display that depends on your requirements. This can be defined in D7 with `hook_filter_info()` (or a filter plugin in D8). Once this input filter is enabled for your text format, it should be able to post process the information (e.g. internal URL, title, mapped field, uid, etc.) that CKEditor plugin embedded in its markup so you can render it accordingly.

---
Tags: 7, rules, navigation, wysiwyg
---


# Question
Title: How change 1 line of code in a core module without hack?
Every time I update Drupal core I get the error message,

> Notice: Undefined variable: forum\_term (line 764)

I've implemented this hack on forum.module to get rid of this problem.

How can I implement this change without hacking the core forum.module file?

# Answer
You can take 3 different strategies to mitigate the problem the hack introduces.

1. **Don't Hack/Ignore the error:** Without knowing the deeper context of when this happens, this could be (as the d.o. thread suggests) just a quirk of other contrib modules that show up during the update process. You'll need to do more investigation to see if this occurs during a critical code (e.g. a module update) and if it can be ignored.
2. **Don't Hack/Fix the error:** Assuming the error is fundamentally a part of Drupal's forum module logic (i.e. not just something caused by a contrib module), you could submit a patch for the module to get it fixed for everyone that has the same issue.
3. **Patch Management:** Depending on your own codebase, process, & issues, patching might be unavoidable here. If that's the case, you can create your own patch for Drupal core and create some process where it is consistently applied every time you need to you need to update your codebase.
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: Duplicating commerce kickstart's product types view modes
I can see that Commerce Kickstart distribution has several more view modes for product types like: **product in cart** or **node:product list**, which are not listed, by default, after commerce module installation on plain Drupal.

How can I get those with only commerce module installed?

Is it some additional code or I am just missing some settings?

I found a module, Entity view modes, which seems to be good for the job but Commerce Kickstart does not have this module installed.

Thank you for advice.

# Answer
In Commerce Kickstart, **Commerce Kickstart Product** (`commerce_kickstart_product`) and **Commerce Kickstart Product UI** (`commerce_kickstart_product_ui`) modules provide the extra view modes. And are not available as a separate module.

So, you can use **Entity view modes** (`entity_view_mode`) to create your custom view mode.
> 1 votes

---
Tags: 7, commerce
---


title: JSON Schema of my entities

text:
# Question
Title: JSON Schema of my entities
In the process of building a headless website and one of the first requirements it was to provide JSON schema of my data model (JSON data from my entities.)

Here will be an example of the user entity.

```
{
    "User": {
        "type": "Object",
        "fields": {
            "first_name": {"type": "String"},
            "last_name": {"type": "String"},
            "age": {"type": "Number"}
        },
    }
}

```

This does not provide any real values rather than extra information to front-end developers to have an understanding of API. This is also useful for making sure that the API is always valid because we could provide a middleware that tests the API before even gets to the front-end app.

There are more examples of these JSON schemas at - https://www.npmjs.com/package/web-service-api

Do you know if there is an away to get this type of information in Drupal 8 programmatically?

# Answer
The following code exposes an API that returns the field and properties data of the user entity type. It uses a recursive method and the nature of typed\_data to achieve such goal.

The post and get methods are called because they are the lowercased versions of GET and POST.

The below code relies on Drupal 8.2 because GET requests are problematic in Drupal 8.1 See this issue

```
<?php

namespace Drupal\sandbox\Plugin\rest\resource;

use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\TypedData\ComplexDataDefinitionInterface;
use Drupal\Core\TypedData\DataDefinitionInterface;
use Drupal\Core\TypedData\DataReferenceDefinitionInterface;
use Drupal\Core\TypedData\ListDataDefinitionInterface;
use Drupal\Core\TypedData\PrimitiveInterface;
use Drupal\Core\TypedData\Type\BooleanInterface;
use Drupal\Core\TypedData\Type\FloatInterface;
use Drupal\Core\TypedData\Type\IntegerInterface;
use Drupal\Core\TypedData\Type\StringInterface;
use Drupal\rest\ModifiedResourceResponse;
use Drupal\rest\Plugin\ResourceBase;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Represents entities as resources.
 *
 * @see \Drupal\rest\Plugin\Deriver\EntityDeriver
 *
 * @RestResource(
 *   id = "user_type",
 *   label = @Translation("User type"),
 *   uri_paths = {
 *     "canonical" = "/user_type",
 *   }
 * )
 */
class UserTypeResource extends ResourceBase {

  /**
   * @var \Drupal\Core\Entity\EntityFieldManagerInterface
   */
  protected $fieldManager;

  /**
   * UserTypeResource constructor.
   * @param array $configuration
   * @param string $plugin_id
   * @param mixed $plugin_definition
   * @param array $serializer_formats
   * @param \Psr\Log\LoggerInterface $logger
   * @param \Drupal\Core\Entity\EntityFieldManagerInterface $field_manager
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, array $serializer_formats, \Psr\Log\LoggerInterface $logger, EntityFieldManagerInterface $field_manager) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);
    $this->fieldManager = $field_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->getParameter('serializer.formats'),
      $container->get('logger.factory')->get('rest'),
      $container->get('entity_field.manager')
    );
  }

  public function post() {
    return $this->resolve();
  }

  public function get() {
    return $this->resolve();
  }

  protected function resolve() {
    $field_definitions = $this->fieldManager->getFieldDefinitions('user', 'user');

    $data = [
      'type' => 'Object',
      'fields' => [],
    ];

    foreach ($field_definitions as $field_name => $field_definition) {
      /** @var \Drupal\Core\Field\FieldStorageDefinitionInterface $storage_definition */
      $storage_definition = $field_definition->getFieldStorageDefinition();
      $data['fields'][$field_name] = [
        'type' => 'Array',
        'element' => $this->transformFieldDefinition($storage_definition),
      ];
    }

    return new ModifiedResourceResponse($data);
  }

  protected function transformFieldDefinition(FieldStorageDefinitionInterface $storage_definition) {
    $fields = [];

    foreach ($storage_definition->getPropertyDefinitions() as $property_name => $property_definition) {
      $fields[$property_name] = $this->transformDataDefinition($property_definition);
    }

    return [
      'type' => 'Object',
      'fields' => $fields,
    ];
  }

  protected function transformDataDefinition(DataDefinitionInterface $definition) {
    if ($definition instanceof ComplexDataDefinitionInterface) {
      $fields = [];

      foreach ($definition->getPropertyDefinitions() as $property_name => $property_definition) {
        $fields[$property_name] = $this->transformDataDefinition($property_definition);
      }

      return [
        'type' => 'Object',
        'fields' => $fields,
      ];
    }
    elseif ($definition instanceof ListDataDefinitionInterface) {
      return [
        'type' => 'Array',
        'element' => $this->transformDataDefinition($definition->getItemDefinition()),
      ];
    }
    elseif ($definition instanceof DataReferenceDefinitionInterface) {
      return $this->transformDataDefinition($definition->getTargetDefinition());
    }
    else {
      $type = "Unknown ({$definition->getDataType()})";

      $class = new \ReflectionClass($definition->getClass());
      if ($class->isSubclassOf(PrimitiveInterface::class)) {

        if ($class->isSubclassOf(StringInterface::class)) {
          $type = 'String';
        }
        elseif ($class->isSubclassOf(IntegerInterface::class) || $class->isSubclassOf(FloatInterface::class)) {
          $type = 'Number';
        }
        elseif ($class->isSubclassOf(BooleanInterface::class)) {
          $type = 'Boolean';
        }
      }
      else {
        switch ($definition->getDataType()) {
          case 'language':
            $type = 'String';
            break;
        }
      }

      return [
        'type' => $type,
      ];
    }
  }

}

```

The definition of `rest.resource.user_type` configuration.

```
id: user_type
plugin_id: 'user_type'
granularity: method
configuration:
  GET:
    supported_formats:
      - json
    supported_auth:
      - cookie
  POST:
    supported_formats:
      - json
    supported_auth:
      - cookie
dependencies: {}

```
> 1 votes

---
Tags: 8, entities
---


# Question
Title: Scroll Calendar View so that it Centers (vertically) on page
I've designed a calendar of events. It uses a Next and Previous pager. With the theme I am using, the top of the calendar displays part way down the screen when first viewed. The user typically scrolls the screen using the mouse to bring the entire calendar into view. This is problematic if the user needs to page to the next or prior month because he needs to once again use the mouse to position the entire calendar on the screen.

I'm not exactly clear on the best approach to resolve this. I thought about looking into the theme code but wasn't sure if that's a good place to start. I thought about trapping the display of each page of the calendar and trying to reposition (scroll) the page programmatically, but, that seemed like unnecessary code.

Can anyone advise me on a proper approach to solve this issue? Ideally, I'd like the user to not have to scroll each page of the calendar when he uses the Next or Prior button. It seems like there should be a way to ensure the entire calendar is visible.

# Answer
One solution that comes to mind is to use hook\_pager\_link() to modify your view's pager links to include fragment/anchor that is in your view's header. This would work on the assumptions:

1. You have custom unique text for previous/next pager links (e.g. "previous month"/"next month").
2. You placed an anchor link in your view header (e.g. `<a name="calendar"></a>`).

In your theme's **template.php** you could override like so:

```
function MYTHEME_pager_link($variables) {

  // If we are looking at pager links with our custom title
  // use our modified theme_pager_link code:
  if (in_array($variables['text'], array('previous month', 'next month'))) {
    $text = $variables['text'];
    $page_new = $variables['page_new'];
    $element = $variables['element'];
    $parameters = $variables['parameters'];
    $attributes = $variables['attributes'];

    $page = isset($_GET['page']) ? $_GET['page'] : '';
    if ($new_page = implode(',', pager_load_array($page_new[$element], $element, explode(',', $page)))) {
      $parameters['page'] = $new_page;
    }

    $query = array();
    if (count($parameters)) {
      $query = drupal_get_query_parameters($parameters, array());
    }
    if ($query_pager = pager_get_query_parameters()) {
      $query = array_merge($query, $query_pager);
    }

    // Add our custom #calendar fragment
    $attributes['href'] = url($_GET['q'], array('query' => $query, 'fragment' => 'calendar'));
    return '<a' . drupal_attributes($attributes) . '>' . check_plain($text) . '</a>';
  }
  else { // Otherwise fall back to core theme pager.
    return theme_pager_link($variables);
  }
}

```
> 0 votes

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


# Question
Title: How do I use the Save Draft module for a particular content type only?
I want to use the Save Draft module for a particular content type. When I install this module by default, it will be applied to all the content types. Please let me know how to avoid this.

I'm using version 7.x-1.4 of the module.

# Answer
Currently you have to install the 7.x-1.x-dev version to get settings per content type.

Once you install that version you can configure the settings on the node type settings form (eg. admin/structure/types/manage/article).
> 3 votes

---
Tags: 7, nodes
---


# Question
Title: Remove the ability to import previous imported file
I'm guessing someone must have done this before but I can't find a module for it.

In Feeds the last file you imported can be seen by name on the left hand side. Next to the 'Browse' box.

If the user doesn't browse for a file then the File shown in that box is imported when clicking on the 'submit' button. What I'd like to do is to leave this file being shown as the last import but I don't want it to be imported if no file has been selected.

Has anyone done this or something similar .

# Answer
> 0 votes
you can simplely remove it by using `hook_form_alter`

**don't forget replace form\_id and yourmodulename with yours in following code**

```
function yourmodulename_form_alter(&$form,$form_state,$form_id){
    if($form_id=='feeds_import_form' ){
    unset($form['feeds']["FeedsFileFetcher"]['upload']['#file_info']);
}
}

```

**update** in this section we prevent user to resubmit the old file,this mean if user push import button without browsed new file we prevent him to remport

```
function mymodule_form_alter(&$form,$form_state,$form_id){
    if($form_id=='feeds_import_form' ){
      $form['#validate'][] = 'mymodule_prevent_import_validate';
}
}

function mymodule_prevent_import_validate($form,$form_state){
    if(!isset($form_state['values']['feeds']["FeedsFileFetcher"]['file'])){
            form_set_error('upload', t('Not new file uploaded'));
            return false;
    }
}

```

---
Tags: feeds
---


title: Uncaught exception thrown in shutdown

text:
# Question
Title: Uncaught exception thrown in shutdown
I am trying to solve this issue from last three days. Searched lot regarding this issue but not getting any solution.

I have also visited these links link1 link2 or duplicate questions

This error is occurring at the time of installation, I am installing `Drupal7` on `linux`

I am using `PostgreSQL 9.4.8` database, php `PHP 5.5.9`

The database user has granted all permissions

following are the exceptions

first exception

```
    Uncaught exception thrown in shutdown function.

    PDOException: SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "semaphore" does not exist LINE 1: DELETE FROM semaphore ^: DELETE FROM {semaphore} WHERE (value = :db_condition_placeholder_0) ; Array ( [:db_condition_placeholder_0] => 2108550473576798c2ab0410.91648409 ) in lock_release_all() (line 269 of /var/www/html/rentspeak/includes/lock.inc).

```

second exception

```
Uncaught exception thrown in session handler.

PDOException: SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "sessions" does not exist LINE 3: sessions sessions ^: SELECT 1 AS expression FROM {sessions} sessions WHERE ( (sid = :db_condition_placeholder_0) AND (ssid = :db_condition_placeholder_1) ); Array ( [:db_condition_placeholder_0] => AqE0DsCH1bG6qk3nMspgcEW1J_FUDbF15vNkX5nSdUU [:db_condition_placeholder_1] => ) in _drupal_session_write() (line 209 of /var/www/html/rentspeak/includes/session.inc).

```

# Answer
> 1 votes
I just tried to setup a fresh Drupal 7.44 with Postgresql and I haven't encountered any issues. The setup went fine. Here are the steps I did.

1. `$ su root` \- Switch to root user.
2. `$ su - postgres` \- Switch to Postgres user. Note that you need to be `root` first before doing this.
3. `$ createuser --pwprompt --encrypted --no-createrole --no-createdb gerald` \- Create a new user called `gerald`.
4. `$ createdb --encoding=UTF8 --owner=gerald drupal` \- Create a new database called `drupal`.
5. Run the installation and select the Postgresql type.

Another way to determine the culprit is by reading the logs.

**For Postgresql**

`$ sudo tail -f /var/log/postgresql/postgresql-9.3-main.log`. In you case it should be `$ sudo tail -f /var/log/postgresql/postgresql-9.4-main.log`.

**For PHP (if you're using Apache)**

`$ sudo tail -f /var/log/apache2/error.log`

**Additional Troubleshooting**

Also check if there is a problem with `timeout` in PHP. You may want to increase to default timeout settings.

**My stack:**

```
gerald@von-viel ~/ $ psql --version
psql (PostgreSQL) 9.3.13
gerald@von-viel ~/ $ php --version
PHP 5.5.9-1ubuntu4.17 (cli) (built: May 19 2016 19:05:57)

```

**Note:** I am using the default configuration of Postgresql.

Hope this helps!

---
Tags: 7, installation
---


# Question
Title: How to determine the priority of css files in info file for a theme?
I have several css files in a theme info file. Suppose i have two definitions of h2 in different files? How to configured the files so I manage to get the h2 definion I want?

---

I edited the question as I do not get a solution yet. The question refered as an answer is problaby one of the reasons. So I first set the order of the files oke. They are now oke. Other changes are reflected.

So specific.... I now have two H2 definitions in 1 css file.

```
h2 {
    font-size: 19px;
}

```

and

```
.page-shop .view-header h2 {
    font-size: 100px !important;
}

```

But still the first is applied in the shop page..

Any suggestion?

For everybody who is reading this; I found my solution:

I'm using Sublime Text editor for css styling. As everything in the syntax had the good color I thought the file is build up good. But in some try and error I saw one line like below:

```
form-item ( font-size: 10em;}

```

Note that instead of openening with a { it is opening with a (

And because of this the rest of the css file is not processed well.

# Answer
> 3 votes
The CSS files are processed in order, so if your .info file looks like this:

```
stylesheets[all][] = css/foo.css
stylesheets[all][] = css/bar.css

```

Then the styles from foo.css will be included before those from bar.css. The same applies whether each CSS file is included separately, or whether they're aggregated.

If you're still unsure which rule will be applied at that point, you need to read up on CSS specificity, as Drupal doesn't affect it.

---
Tags: theming
---


# Question
Title: Replacing an object of the UserLoginForm class with one of my own class
Is it possible to replace an object of the UserLoginForm class with one of my own class?

What I want to do is replacing the login form with a custom one which would ask users to enter a code sent to their email address, once they entered the correct user credentials.

The problem is that an object of that class is created from UserController::userPage().

```
if ($user->id()) {
  $response = new RedirectResponse(url('user/' . $user->id(), array('absolute' => TRUE)));
}
else {
  $response = drupal_get_form(UserLoginForm::create($this->container), $request);
}

```

I know I can implement hook\_form\_alter() to alter the form, but I would like to use a class like `UserLogin`, and replacing `$form_state['build_info']['callback_object']` with the object of my class in `hook_form_alter()` is probably too late.

Is it possible to use a class for altering the user login form? How?

# Answer
> 1 votes
As I said in the question, the problem was that `UserController::userPage()` expressly created an object of the class `UserLoginForm`. The method has been changed, and now it contains the following code, which doesn't contain any explicit reference to that class.

```
public function userPage() {
  return $this->redirect('entity.user.canonical', array('user' => $this->currentUser()->id()));
}

```

Using a route subscriber that extends `RouteSubscriberBase` is possible to change the form associated with a route.

```
use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

class MymoduleRouteSubscriber extends RouteSubscriberBase {
  public function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('user.login')) {
      $route->setDefault('_form', '\Drupal\mymodule\Form\MyModuleLoginForm');
    }
  }
}

```

---
Tags: forms, 8
---


# Question
Title: How to hide few default fields for specific user
I want to hide fields such as password, email when a particular user tries to edit few fields of other users.

How can I achieve this?

# Answer
Hi for this there is many possible way to achieve this you can use https://www.drupal.org/project/field\_permissions/releases/7.x-1.0-beta2 (The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.) or by custom module

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

  if ($form_id === 'you_form_id') {

  if (in_array('user_role_type', $user->roles)){
    //do stuff

     // Use var_dump  to dump the $form array to see the fields.
     // var_dump ($form);

     unset($form['mail']);
     unset($form['pass']);
    }
  }
}

```
> 1 votes

---
Tags: users
---