# Question
Title: A way to have an unchecked "end date" input field?
The date module gives the possiblity to collect an end date.
The thing is, in the node creation form, 'Show end date' is checked by default and the date calendar popup field is displayed.

I would like to have the opposite scenario.
With the **End date** field hidden by default, and it would only appear if we check the 'Show end date' checkbox.

Thanks to anyone who can help with this

# Answer
We can do this easily using hook\_form\_alter hook, by setting `#checked` value of checkbox to `FALSE`. Since the date module doesn't add both fields at initial form load, we've to add #after\_build to form where we can modify `#checked` value of checkbox (i.e. `show_todate` field) in form.

Below is the sample code for hiding the end date in date field. For this we've to add a Date Type field (field name as `field_date`) with ability to add end date in article Content Type. After which we've to implement hook\_form\_alter and checked if current form is add new article form to make sure we don't override node edit field value. And then added `#after_build` to add article form. Which then set the `#checked` value to `FALSE`.

```
/**
 * Implements hook_form_alter().
 */
function [MODULE_NAME]_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'article_node_form':
      if (empty($form['nid']['#value'])) {
        $form['#after_build'][] = '_modify_end_date_form';
      }
      break;
  }
}

/**
 * Proxy function to call _modify_end_date_form_after_build().
 * @param type $form
 * @param type $form_state
 * @return void
 */
function _modify_end_date_form($form, &$form_state) {
  return _modify_end_date_form_after_build($form, $form_state);
}

/**
 * After_build callback for Article Content Type.
 * @param type $form
 * @param type $form_state
 * @return void
 */
function _modify_end_date_form_after_build($form, &$form_state) {
  $form['field_date'][LANGUAGE_NONE][0]['show_todate']['#checked'] = FALSE;
  // $form['field_date'][LANGUAGE_NONE][0]['show_todate']['#value'] = FALSE;
  return $form;
}

```
> 1 votes

---
Tags: javascript, datetime
---


# Question
Title: Easiest way to add popup dialog with snippet of html/text using a wysiwyg editor?
My client isn't too technical and cannot code, but she wants a popup dialog when the user clicks on a link to show a snippet of html or text.

What solutions are there for the end user to be able to add and edit text popups like this using only a wysiwyg editor without having to code in stuff?

# Answer
Since I do not know of a single module that can achieve that functionality out of the box, here is how I'd do it:

1. Create a new content-type with an entity reference, a trigger string and a dialog text area.
2. In the referenced node, query for any referencing entities from the new content type. Most likely with a preprocess function and preferably in a newly created custom module.
3. Load referencing entities if found and attach a JS file that will receive the triggers and dialogue values through the settings array.
4. If all is well then JS file will have triggers in selectors and dialogues to display.
> 1 votes

# Answer
Here is a recipe for that:

* CKEditor Link: Used for linking to other content in your Drupal. In this case, I would create another Content-Type, e.g. Popup Snippet or sth similar. This is an optional component, depending on your exact requirements.
* Colorbox Node: Used for presenting node content in a popup, stripped of the surrounding regions and other theme elements. It also provides an easy way to turn links into popups, by providing a 'magic' class, `colorbox-node`. This is the main component, and the main idea, allowing the user to 'popify' links by adding a class name to the link's properties in CKEditor.

Below are some screenshot of the result on a D7.

**Linking to content**

**Setting the colorbox-node class**

**End-result**

Good luck!
> 4 votes

---
Tags: wysiwyg
---


# Question
Title: How to change Option Label with Hook_form_alter
I've added the Cheque module to my Drupal Commerce site so that users can select that payment option instead of paying by credit card.

However, I'm seemingly unable to edit the label for that payment option which currently reads as 'Cheque' next to the radio button.

In hook\_form\_alter, I'm attempting the following, but all it does is add another radio button and another option...it doesn't change the existing option.

```
$form['commerce_payment']['payment_method']['#options']
['commerce_payment_commerce_cheque'] = t('Send me an Invoice');

```

Note: I also tried the above code with `['#title']` at the end and it just gives me another option with the label 'Array' attached to it.

So, how do you change the label text of an option with hook\_form\_alter?

# Answer
You're just adding to the existing array of options, when actually you want to clear it and just use your option.

Try this...

`$form['commerce_payment']['payment_method']['#options'] = array('commerce_payment_commerce_cheque' => t('Send me an Invoice'));`
> 2 votes

# Answer
You could also try Commerce Payment Alter module. In that case no custom development would be required.
> 1 votes

---
Tags: commerce
---


# Question
Title: Can't import from XML using Feeds importer and XPath parser
I'm trying to import book objects from the XML file you can see XML file Here. I will tell step by step what I did to achieve this, so it would be easier to help me.

1. Created a Book content type with all the corresponding fields from the XML file
2. Installed Feeds importer and XPath parser modules with their dependant modules
3. Created a Feed importer called bookImport
4. In the Basic settings I attached it to Book content type
5. The fetcher is a default one - HTTP
6. For parser I chose XPath XML parser
7. Processor is Node. As I want to create new Nodes for every single book
8. In the Node processor settings I chose Book bundle and everything else is left as it was by default.
9. In the mapping I mapped all the `xpathparser:*` source values to target ones from Book content type.

When trying to import, in the XPath Parser Settings for context I put **book** and leave everything (all the other book fields empty), I turn on my error messages and after clicking Import I get these two lines:

```
context :
There are no new nodes.

```

I've been trying to solve this for 2 days now without any luck, any help would be highly appreciated and I hope my post is informative enough, if there is something missing, please let me know and I will update!

# Answer
Solved this on my own, the problem was that in context I had to write //book, instead of book. Stupid mistake which caused me headache for 2 days. I hope this will be helpful for people who will face the same problem.
> 2 votes

---
Tags: 7, importing-exporting, feeds
---


# Question
Title: How do you add table column sort functionality to an EntityFieldQuery?
I have an EntityFieldQuery that gets displayed in a table. How do I add clickable sort-by-column functionality? When I use regular db\_select queries I can sort using the following code:

```
 $query = db_select('tablename', 't')
   ->extend('PagerDefault')
   ->limit(50)
   ->extend('TableSort')

 // ...

 $query = $query->orderByHeader($header)
 $results = $query->execute();

```

Everything looks good and when the table is displayed I can click on the columns and they are hyperlinks and I can sort just fine. However, now that I have an EntityFieldQuery I can't seem to duplicate the functionality. This is what I have so far:

```
$header = array(
  'title' => array(
    'data' => t('Date'),
    'type' => 'field',
    'specifier' => array(
      'field' => 'field_articledate',
      'column' => 'value',
    ),
  ),
);
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'article')
  ->propertyCondition('status', 1);

$query = $query->tableSort($header);
$query = $query->pager(100);

$results = $query->execute();

```

A one-column header appears and it says "Date" as expected, but it is not a clickable hyperlink. What am I doing wrong? What is the correct syntax?

# Answer
I know this thread is a little old but adding 'field' to the array fixes the issue.

e.g.

```
$header = array(
  'title' => array(
    'data' => t('Date'),
    'type' => 'field',
    'specifier' => array(
      'field' => 'field_articledate',
      'column' => 'value',
    ),
    'field' => '', //There is an Isset call that prevents links from showing without this.
  ),
);
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'article')
  ->propertyCondition('status', 1);

$query = $query->tableSort($header);
$query = $query->pager(100);

$results = $query->execute();

```

See: https://www.drupal.org/node/885014#comment-3464666 for a comment on the issue.
> 2 votes

---
Tags: database
---


title: Removing title from content pane

text:
# Question
Title: Removing title from content pane
I have used a content pane in a panel to add a description on top of it. It was a success but I can't find a way to remove the pane title in the view. The screenshots are below:

I have also set the content pane title to none

There is no option in the panel for title.

So how can I remove it?

# Answer
You can hide the title using CSS, for example with `style="display:none;"`.
> -1 votes

# Answer
In the view, there is an 'allow settings' link (bottom right of your screen shot). This allows you to select which settings can be changed within panels, including the title.

You can then, in panels, override the title with an empty string.
> 8 votes

# Answer
If I am not mistaken if you write `<No Title>` in the pane title field the pane title will not be displayed.
> 6 votes

# Answer
In drupal 7, if we don't want to show title in Content Pane, then leave the **Title** field empty, even don't write `None` in the textfield, Just leave it empty.
> 3 votes

# Answer
Module Exclude Node Title:

Configure by content type and display mode from

* admin/config/content/exclude\_node\_title
> 1 votes

# Answer
I use `<none>` in the title field. Seems to work just fine.
> 0 votes

# Answer
If you implement your panel through `hook_default_page_manager_pages`or `hook_default_page_manager_handlers` you can add this code:

```
    $pane->configuration = array(
      'override_title' => 1,
      'override_title_text' => '',
      'override_title_heading' => 'h2',
    );

```
> 0 votes

---
Tags: views, panels
---


# Question
Title: Drupal 8, include a subtemplate in a form
I created a Class form, then I can access to the page form and submit it. My form use the default template of my website.

When I submitted the form, I want redirect the user to the form page (the same page) and display some elements in front of page. Theses elements depends on the results of the form has been submitted.

I can easily do that with simples drupal messages, but instead, I would like to show more complex messages.

I think I can create a little template file and include it in my form. But I haven't any ideas how can I do that in Drupal 8, can you provide me a very simple example or tell me how I can include a sub-template in my form ?

I think my sub-template looks something like this (Pseudocode, not twig :) ) :

```
// the form return an array
    foreach formarray as element
        <h1>element1<h1>
        <p>property1 : {element[property1}</p>
        <p>property2 : {element[property2}</p>
        ...
    end foreach
// I include this template in the form, if the formarray is empty, nothing is displayed (when the user load the forme the first time)

```

Thanks for help !

# Answer
Most likely you are looking at adding to the "render array" of the page (or form). A render array can refer to a "type" or Render Element, and that type can render into a template.

The scenario of rendering after form submission on the same form can be done within the Form itself by setting the form state to rebuild.

```
  public function submitForm(array $form, FormStateInterface $form_state) {

    // Set the rebuild state to TRUE to persist $form_state when the form is reloaded.
    $form_state->setRebuild();
    $form_state->set('display_extra', TRUE);
  }

  public function buildForm(array $form, FormStateInterface $form_State) {

    // Conditionally display something from form state.
    if ($form_state->has('display_extra') && $form_state->get('display_extra')) {
      // Structure the render array here including setting up a custom RenderElement ('#type'), which has a custom template defined in hook_theme().
      $form['display_something'] = [];

    }

    // Rest of form...

    return $form;
  }

```
> 3 votes

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


# Question
Title: how to set custom permission to custom menu access?
I am trying to create student management system in which i have been created custom 'registration form', for registering to website then i have created 'list of registered students' menu to show registered students.I want to set permissions such that admin can edit registration form and authenticated user can only see 'registration form',admin can see list of registered students but authenticated user can not see that list.So please guide me to do so.

# Answer
If you do this using a custom module, you can use hook\_permission to defile your permissions, and use in the views. You can also restrict access by role and set the visibility if you use blocks fir the 'list of registered students'.
> 1 votes

---
Tags: users
---


# Question
Title: How to add a value to the object group in group module?
I have been using the Group module with D7 for a while, but I always regretted that there was no 'creation date' value for each group. I added a column in my database which fills in that value automatically, but I would like it to be part of the object *group* so that I can retrieve the value more easily. Ideally I want to be able to do this:

```
$group = group_load($gid);
$thedate = $group->creation_date;

```

How should I go about it? Thanks.

# Answer
Groups are fieldable entities, so you could add a field with a fieldname of, say, `creation_date`.

And if you'd then use the Rules module, you could create a custom rule like so:

* Rules Event: *After saving a new group*.
* Rules Action: *Set a data value*, i.e. to set the value of your `creation_date` field.

**Note**: If the field (like such `creation_date` field) does not show up within the Rules Action to be added, you may have to first add a Rules Condition like "Entity has field".
> 1 votes

---
Tags: 7, group
---


title: Catch first node in a view template

text:
# Question
Title: Catch first node in a view template
I created a view for the front page and also a node--view--frontpage.html.twig to design this view. Is there any opportunity to catch the first node with a if statement to design it differently?

In this case I want to change the order of the first iteration in the `node--view--frontpage.html.twig`:

```
{% set createdDate = node.getCreatedTime | date('j.m.Y') %}
<article{{ attributes }}>
  {{ content.field_picture }}
  <div class="meta">
    {{ createdDate }}
    {% if content.typ | render | trim %}
      , {{ content.typ }}
    {% endif %}
  </div>
  <h2 class="news" {{ title_attributes }}>
    <a href="{{ url }}" rel="bookmark">{{ label }}</a>
  </h2>
  {{ content.body }}
</article>

```

# Answer
The display suite module has a views integration that allows you to choose a different display mode for the first node in a view versus all the others. In this case you can easily create a separate tpl for that view mode and you're good to go. Its extremely powerful. Take a look at this post and look for "Alternating view modes" in the last screen shot.
> 1 votes

---
Tags: views, theming
---


# Question
Title: How to achieve MuchoMenu Multilingual functionality?
I have used MuchoMenu in my site. Now I'm struck at translation.

There is no option to translate the MuchoMenu, also there is no translation strings available. How do I translate the menu links specified in the muchomenu?

# Answer
> 1 votes
Looking their module code, it appears as though they did not encapsulate many of their strings in the `t()` function. Therefore it's not exposed to Drupal's string translation functions. Unless you want to undertake the task of fixing it then, unfortunately, it's not available.

You could also lodge a bug in their issue queue and maybe that will motivate some discussion on their end.

Regardless, as long as mucho menu uses Drupal's native menu handler, it SHOULD still use the same functions for translation for links. Assuming you set up the menu to be translatable the links should be exposed as any other menu in Drupal.

---
Tags: 7, navigation
---


title: on submit does not allow login to occur

text:
# Question
Title: on submit does not allow login to occur
When I add an additional "onsubmit" function to the login button, the login doesnt continue this is my code `function xxx_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
 if ($form_id=='user_login_form') {
 // Add a custom submit handler to save the array of types back to the config file.
 $form['actions']['submit']['#submit'][] = 'xxx_form_submit';
 }
}`

and it goes through the submit but doesnt continue the login functionality.

# Answer
> 5 votes
Use `$form['#submit'][] = 'xxx_form_submit';` instead of `$form['actions']['submit']['#submit'][] = 'xxx_form_submit';`.

---
Tags: 8, forms
---


# Question
Title: How do I programmatically use an external database?
How do I programmatically use an external database?

```
$databases = array();
$databases['default']['default'] = array(
  // Drupal's default credentials here.
  // This is where the Drupal core will store its data.
);
$databases['my_other_db']['default'] = array(
  // Your secondary database's credentials here.
  // You will be able to explicitly connect to this database from your modules.
);

```

# Answer
> 3 votes
1. Setup the external database on settings.php
2. Select the correct database

```
$con = \Drupal\Core\DatabaseDatabase::getConnection('default','my_other_db');

```

I took the example from http://www.drupal8.ovh/en/tutoriels/175/use-multiple-databases-drupal-8.

---
Tags: 8, database
---


# Question
Title: How do I prevent an entity to be saved on update depending on conditions?
I use content moderation, recently present in drupal 8 core, for editorial workflow.

I'd like to prevent the entity from being saved in an update if the current user is the author of the document.

how could I achieve that ?

this does a redirection but the entity saves still does happen

```
 function hook_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {

 if ($entity->getEntityTypeId() !== 'content_moderation_state' ) {
    return;
}

$article_id=$entity->get('content_entity_id')->getString();
$article = \Drupal\node\Entity\Node::load($article_id);
 if($article->bundle()=='article') {

    $author_name=$article->getOwner()->getAccountName();
    $current_user_name=\Drupal::currentUser()->getAccountName();

    $moderation_state = $entity->get('moderation_state')->getString();

    switch ($moderation_state) {
        case 'peer-reviewing':

           $author=$article->getOwner();
           $current_user=\Drupal::currentUser();

            //$entity= $entity->original;
             //if author same as current user:
            drupal_set_message(t('original author cannot be reviewer.'), 'error');
            $url = $base_url.\Drupal::service('path.current')->getPath();
            $response = new Symfony\Component\HttpFoundation\RedirectResponse($url);
            $response->send();
            return;

 }

```

# Answer
> 3 votes
Could you not instead implement a `hook_form_alter` and do your condition checks, and hide/remove the submit button if it is the same user trying to review?

You could set the same message at the top of the form and not have to do any redirects.

# Answer
> 2 votes
how i did it:

```
function my_module_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id){
  if ($form_id='node_article_edit_form')
{

    $article=$form_state->getFormObject()->getEntity();
    //get the associated content moderation entity
    $id = Drupal::entityQuery('content_moderation_state')
       ->condition('content_entity_id', $article->id())
        ->execute();

    $stateEntities = Drupal::entityManager()
        ->getStorage('content_moderation_state')
        ->loadMultiple($id);
    $stateEntity=array_values($stateEntities)[0];
    $moderation_state = $stateEntity->get('moderation_state')->getString();

    if($moderation_state=='review){
        $form['#validate'][] = 'my_module_node_article_edit_form_validate';
    }
}

function my_module_node_article_edit_form_validate(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
$article=$form_state->getFormObject()->getEntity();
$author_name=$article->getOwner()->getAccountName();
$current_user_name=\Drupal::currentUser()->getAccountName();

if(($author_name==$current_user_name) && ($current_user_name!='admin'))
{
    $error_msg="En tant qu'auteur de l'article, ".$current_user_name.", vous ne pouvez être relecteur.";
    $form_state->setErrorByName('user_moderation_constraint', $error_msg);
}

return;

```

}

---
Tags: 8, entities, hooks
---


# Question
Title: Will groups with more number of users cause the page to load slower?
Anonymous page takes 1 to 2 secs to load After the successful login, we are showing the same page but with some menu. I have disabled that menus too. But the page load takes 10 secs to load with same content. We have groups. To check,have disabled the groups assigned to the user, then the page loads faster 1 to 2 sec. At first we though that, assigning groups might cause the issue. But the scenario is like, if I add single group which have more content(700) and users like (1500) cause the issue.Except dat grp,if I add more groups to the user,the page loads faster.

After disabling organic subgroups, and adding that single group causes the page to load faster.

Can you share your thoughts?

# Answer
The more modules you add to a site, the more code that likely has to execute, which equates to more overhead per request. Organic Groups particularly can be heavy, depending on what you are trying to achieve. I do not know how much progress they've made in the last few years, but in my experience it was always pretty heavy.

Logged in users also bypass caching, whereas anonymous users see as much cache as possible. This isn't as true for 8.x, but the differences in 7.x can be pretty black and white. Juggling multiple logged in users simultaneously can put a hurt on low end setups or especially if you haven't implemented caching. Or a runaway module could be calling functions every single request per user, adding to that time.

Honestly, the best tools that will help you pin down potential bottlenecks are xhprof and using a service like New Relic. It will give you far more intel about your application than anyone here ever could.

Other things you can do simply comes down to good planning. Are pages made up of lots of Views? Implement Views caching on displays that don't change often. Are you using Panels? Do you need to use Panels? Are you running memcache, does PHP have 256M memory limit, is your server underpowered?

I would start with New Relic, honestly, and xhprof. New Relic is easier to setup than xhprof, depending on your experience. You will need to profile your site before you know what steps to take first.

If you are running Drupal 8, also install the Web Profiler toolbar included with Devel.
> 0 votes

---
Tags: organic-groups, performance
---


# Question
Title: Rules send email on entityform submission with current node field content
I have a rule which sends an email on saving an entityform. The entityform appears on several nodes.

I would like to 'grab' field content specific to these nodes and include this data in the email message body.

I think I might need a rule component but I'm unsure how to build a relationship between the node content and the entityform.

Can anyone help?

# Answer
Add an entity reference field to the entityform in question and - using Entityreference Current module - check the option to reference current. This gives you access to current page data.

It's at this point you may want to install the Hidden Fields Widget module which will allow you to set the entity reference widget to hidden. Do this if you don't want the field to be visible on your entityform.

At the time of writing this, you also need to patch the Hidden Fields Widget module with https://www.drupal.org/node/1821008 to support the entity reference field type.

Next, create your rule with Event: After saving a new entityform submission, Conditions: Entity has field (select the entity reference field) and Actions: Send mail.

Now all you need to do is add another condition relating to the field token you want to use in your email body. Use the previous entity reference field condition as your data selector, then select the relevant field. This will now be available as a token in the Send mail action.

You can do this as many times as you want to get each field out.

I'm sure there's a more efficient way of doing this, but this worked for me.
> 2 votes

---
Tags: 7, entities, rules
---


# Question
Title: How can I findout where a custom variable is being created?
In a current Drupal 7 install i realize that all our CSS files are being declared in html.tpl.php using a variable $styles instead of through the templates .info file. I tried using Xdebug but all i managed to get is the info the variable holds. The same is also being done to javascript files which should really be at the footer instead of the header.

I have checked my themes template.php but i have not found a declaration of it anywhere.

# Answer
`$styles` is set in the `$variables` array during template\_process\_html. It is a result of calling `drupal_get_css`, and you can add to, remove, or change the order of this array by implementing `drupal_add_css`, adding a css file to your theme info file, or using `hook_css_alter`. The reason you do not see it in your theme's template.php is because it is a higher level function that Drupal does, the page is assembled using a majority of the application, core and contrib modules informing or responding to requests.

https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal\_get\_css/7.x

As you can see, `drupal_get_css` allows for altering, which is where you would implement `hook_css_alter` to adjust anything in the array of CSS files before they are added to the page.

See: hook\_css\_alter

The same applies for the `$scripts` variable. You can add javascript with `drupal_add_js`, library hooks, or by adding it to your theme info file.

For example, if you want to change every JS file in drupal to load in the footer, instead of the head, you can do this with `hook_js_alter`:

```
/**
 * Implements hook_js_alter().
 * @param $items
 */
function mytheme_js_alter(&$items) {
  foreach ($items as $key => $script) {
    $items[$key]['scope'] = 'footer';
  }
}

```

Lets say on certain node types, you also want to remove scripts from loading to the page because they are not necessary for the page to function:

```
/**
 * Implements hook_js_alter().
 * @param $items
 */
function mytheme_js_alter(&$items) {
  foreach ($items as $key => $script) {
    $items[$key]['scope'] = 'footer';
  }

  if ($node = menu_get_object('node')) {
    if ($node->type == 'campaign') {
      // unset all the JS we won't need to reduce page weight
      unset($items['sites/all/themes/mytheme/js/jquery.waypoints.min.js']);
      unset($items['sites/all/themes/mytheme/js/jquery.fitvids.js']);
      unset($items['sites/all/themes/mytheme/js/isotope.min.js']);
      unset($items['sites/all/themes/mytheme/js/imagesloaded.min.js']);
      unset($items['sites/all/libraries/ckeditor/plugins/codesnippet/lib/highlight/highlight.pack.js']);
      unset($items['sites/all/modules/contrib/wysiwyg_codesnippet/wysiwyg_codesnippet.js']);
      unset($items['sites/all/modules/contrib/addthis/addthis.js']);
      unset($items['http://s7.addthis.com/js/300/addthis_widget.js']);
    }

    // we only need addthis to load on an article
    if ($node->type != 'article') {
      unset($items['sites/all/modules/contrib/addthis/addthis.js']);
      unset($items['http://s7.addthis.com/js/300/addthis_widget.js']);
    }
  }
}

```

See hook\_js\_alter
> 2 votes

---
Tags: 7, theming
---


# Question
Title: Get page number of multistep webform in tpl.php
I have a multistep webform that I would like to display a video only on page one.

I am trying to find a reliable variable that will only be available on the first page.

I have tried this in hook\_form\_alter but it is unreliable when the user navigates back to a previous page. It works initially. Page one video shows, page two no video, back to page one no video, page two video shows.

I am using drupal\_add\_js to add a display:none on the video div when page\_number \> 1, but it isn't working as I expected. Any ideas?

# Answer
I hacked it and used jquery to hide the div when there is an existence of a previous page class.
> 0 votes

---
Tags: webforms
---


title: Embedding view in form breaks ajax

text:
# Question
Title: Embedding view in form breaks ajax
EDIT4: **As it turns out**, the view was using exposed filters, which causes the view to return html for a form. HTML isn't allowed to have multiple forms, so the browser might remove the second one, confusingly. The only solution I could imagine was putting the view somewhere else, or putting it inside of an iframe.

I'm putting an embedded view into an existing form with `hook_form_alter`, and when I do this, it's causing the `Add another item` button for one of the form's elements to stop working. It sends an ajax request and gets a 500 response. Here's how I'm doing it:

```
$the_view = \Drupal::service('renderer')->render(views_embed_view('images', 'page_1'));
$form['newthing'] = array(
  '#type' => 'markup',
  '#markup' => $the_view,
);

```

The interesting thing is, it's not actually the second part that causes it, it's just the `render()` line that causes the problem. The rendered view data doesn't actually have to be inserted into the form.

I've tried it with different views, and I legitimately can't figure out the reason why some views break my form's ajax and some don't. It doesn't seem to be exposed filters, or having "Use ajax" enabled, or having a pager.

Whatever it is, it seems to cause the Form Data to not be sent, when clicking the "Add another item" button. This information, which would normally be sent on the ajax request:

name\[0\]\[value\]:
form\_build\_id:form-eX\_LK4K7R4X0csFlHfJGIZ7auabXu7kVIa1cctPA1iE
form\_token:1tBuaaaRRJ6RHJdTtHwGWpo3gieX4ukYsfkf1QFdeyw
form\_id:my\_form
user\_id\[0\]\[target\_id\]:admin (1)
field\_story\_reference\[0\]\[target\_id\]:
field\_story\_reference\[0\]\[\_weight\]:0

...is missing.

EDIT: I guess I never really phrased it in the form of a question. How do I get it to not break my `Add another item` button? Should this be reported, or is there a known workaround?

EDIT 2: Thank you 4k4, but now something even stranger is happening, now that I'm not doing the render part. When I click the Add another story button, it now disappears and prints the message "An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (2 MB) that this server supports. But, obviously I'm not uploading any file. The ajax request is still not sending the form data that was missing when I did it the other way.

EDIT 3: I can see that after I've embedded my view, there is a tag, which would normally have been at the end of the form, after the save button. It hasn't been moved, it's just that there's an extra one. When I embed the view, there are two forms, one inside of the other. It looks like Chrome's Inspector had removed the second tag automatically from the html, but left the extra closing tag. I can see it when I go to view page source, though.

# Answer
> 1 votes
You can remove the rendering, you don't need it:

```
$the_view = views_embed_view('images', 'page_1');
$form['newthing'] = $the_view;

```

In fact, you should not render yourself in D8. And if you have the rare case you need to do this, read this first:

https://www.drupal.org/node/2513810

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


# Question
Title: How to allow anonymous users to view page?
I would like to make a new page, before publishing it I'd like to send it to other people to review/approve the content without having to log in.

Is this possible?

# Answer
> 3 votes
I think it is hard to achieve. However, using Access Unpublished module, maximum you can do is you can provide the specific URL to anonymous user(which includes all), so they can see the unpublished node with that specific URL(So, this way you are hide content from all other users, as they have not that URL), however they can not edit. For Editing option you have to set the separate user role, hence it ends up with login.

# Answer
> 1 votes
It's best for them to log in. Setup a limited role that gives them only what they need to access the content for review.

---
Tags: users
---


# Question
Title: How to use/show different path alias of same URL according to user roles?
Hi I have set URL alias of for node add from path like below :

> 1. node/add/my\_content\_type = addlink
> 2. node/add/my\_content\_type = suggestion

When user is logged-in we make access of node add form via this URL:

> www.example.com/addlink

Now for not logged-in user we want users to use node add from via below URL:

> www.example.com/suggestion

I am trying with rules on event "Initialize drupal" then checking path and roles and trying to redirect but not able to achieve that.

Please suggest is that possible to make it happen in some way!

Thanks!

# Answer
The ensure the right path is used when displaying links, you need to implement `hook_url_outbound_alter()` in a custom module.

```
/**
 * Implement hook_url_outbound_alter().
 */
function MODULE_url_outbound_alter(&$path, &$options, $original_path) {
  if ($path == 'node/add/my_content_type') {
    $path = user_is_logged_in() ? 'addlink' : 'suggestion';
  }
}

```

Ensuring the right path is always used can be achieved with a hook\_menu\_alter(). There, you can alter the page callback for `node/add/my_content_type`. And in your callback, check whether the user is accessing the page using the expected path.

```
/**
 * Implements hook_menu_alter().
 */
function MODULE_hook_menu_alter(&$items) {
   $type_url_str = str_replace('_', '-', 'my_content_type');
   $items[['node/add/' . $type_url_str]['page callback'] = 'MODULE_my_content_type_add';
}

/**
 * Page callback for the add new My Content node page.
 *
 * @see MODULE_hook_menu_alter
 */
function MODULE_my_content_type_add($type) {
  $expected_path = user_is_logged_in() ? 'addlink' : 'suggestion';
  if (current_path() != $expected_path) {
    drupal_goto($expected_path);
  }
  else {
    return node_add($type);
  }
}

```

If you site use multiple language with prefix language selector, then `current_path()` will also contains the language prefix whch need to be accounted for in your code.
> 3 votes

# Answer
Finally I am able to solve this by using theme\_menu\_link:

```
function theme_menu_link__main_menu(array $variables) {

  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#original_link']['mlid'] == "610") {

       if ($element['#original_link']['mlid'] == "610") {

          $path = user_is_anonymous() ? 'suggestion' : 'addlink';
          $element['#original_link']['link_path'] = $path;
          $element['#href'] = $path;
     }
  }

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '' . $output . $sub_menu . "\n";

}

```
> 0 votes

---
Tags: 7, path-aliases
---


title: Drupal 7 upgrade Image module

text:
# Question
Title: Drupal 7 upgrade Image module
I was upgrading a site to Drupal 7 but as you may know there are couple of modules which are moved to the core modules in Drupal 7.

I had installed Image and Image Cache module in Drupal 6, but now I am finding it hard to upgrade to Drupal 7. After the upgrade the image doesn't load up.

I also tried migrating the image field, but it says "missing plugin".

Can anyone guide me through the process of upgrading Image and Image Cache module content to Drupal 7.

# Answer
Over the years, and the major versions, Drupal's image handling has seen more flavours than Baskin Robbins. After my D5-\>D6 upgrades, I followed what was being talked about for image handling in D7. It allowed me to take a strategic approach to site design in D6 which would, hopefully, improve the compatibility of the site for the next upgrade.

If you are upgrading to D7, your first task is to create a D6 version of your site which is based on functions which are supported by D7. Convert all image handling to imagefield in D6, then your upgrade should go smoothly. If, however, you are still using modiles like Node Images or Upload Image you will have problems because there is no upgrade path.
> 0 votes

# Answer
Here is a good guide: Migrating D6 Content Construction Kit (CCK) to D7 Fields

To summarize:

* Upgrade core
* Download CCK for Drupal 7
* Enable CCK Content Migrate
* Browse to the migrate fields page
* Follow instructions

You might need to manually copy some configurations, but that should be it.
> 0 votes

---
Tags: 7, media
---


# Question
Title: Drush 8 issue under Linux: 'drush up' ends with 'pm-updatestatus failed' while 'drush ups' works correctly
I'm hosted on a Linux server with Apache 2.2, PHP 5.5, MySQL 5.6 installed. I still run D6 sites for the moment, whose some modules I can update by using Drush 8 combined with the myDropWizard module.

The `drush up` command works correctly with all the sites except for this one:

```
[~/public_html/fr/sites/fr.mysite.com]# drush up
pm-updatestatus failed.                                              [error]

```

The curious thing is that the `drush ups` command does work and end correctly.

On the one hand, this issue prevents an easy update of the site's modules (even if it can be done module after module by using the `drush dl` command), on the other hand I'm afraid that it could cause problems when I'll migrate from D6 to D8 by using Drush 8.

Edit:

```
[~/public_html/fr/sites/fr.mysite.com]# drush -dv up
Using the Drush script found at /home/myuser/.composer/vendor/drush/drush/drush.launcher using proc_open
Drush preflight prepare loaded autoloader at                         [preflight]
/home/myuser/.composer/vendor/autoload.php [0.01 sec, 2.43 MB]
Starting Drush preflight. [0.01 sec, 2.43 MB]                                                                              [preflight]
Loading drushrc "/home/myuser/.drush/drushrc.php" into "home.drush" scope. [0.01 sec, 2.44 MB]                           [bootstrap]
Cache HIT cid: 8.1.3-commandfiles-0-e781ef82ff5e93e79e640f0c0ab268c0 [0.02 sec, 2.5 MB]                                        [debug]
Scanning into /etc/drush for /.*aliases\.drush(8|)rc\.php$/ [0.06 sec, 4.78 MB]                                                [debug]
Scanning into /etc/drush for /self\.alias\.drush(8|)rc\.php$/ [0.06 sec, 4.78 MB]                                              [debug]
Scanning into /home/myuser/.composer/vendor/drush/drush/includes/.. for /.*aliases\.drush(8|)rc\.php$/ [0.06 sec, 4.78       [debug]
MB]
Scanning into /home/myuser/.composer/vendor/drush/drush/includes/.. for /self\.alias\.drush(8|)rc\.php$/ [0.07 sec, 4.78     [debug]
MB]
Scanning into /home/myuser/.drush for /.*aliases\.drush(8|)rc\.php$/ [0.07 sec, 4.79 MB]                                     [debug]
Scanning into /home/myuser/.drush for /self\.alias\.drush(8|)rc\.php$/ [0.07 sec, 4.79 MB]                                   [debug]
Scanning into /home/myuser/public_html/fr/../drush for /.*aliases\.drush(8|)rc\.php$/ [0.07 sec, 4.79 MB]                    [debug]
Scanning into /home/myuser/public_html/fr/../drush for /self\.alias\.drush(8|)rc\.php$/ [0.07 sec, 4.79 MB]                  [debug]
Scanning into /home/myuser/public_html/fr/drush for /.*aliases\.drush(8|)rc\.php$/ [0.07 sec, 4.79 MB]                       [debug]
Scanning into /home/myuser/public_html/fr/drush for /self\.alias\.drush(8|)rc\.php$/ [0.07 sec, 4.79 MB]                     [debug]
Scanning into /home/myuser/public_html/fr/sites/all/drush for /.*aliases\.drush(8|)rc\.php$/ [0.07 sec, 4.8 MB]              [debug]
Scanning into /home/myuser/public_html/fr/sites/all/drush for /self\.alias\.drush(8|)rc\.php$/ [0.07 sec, 4.8 MB]            [debug]
Scanning into /home/myuser/public_html/fr/sites/default for /.*aliases\.drush(8|)rc\.php$/ [0.07 sec, 4.8 MB]                [debug]
Scanning into /home/myuser/public_html/fr/sites/default for /self\.alias\.drush(8|)rc\.php$/ [0.07 sec, 4.8 MB]              [debug]
Bootstrap to phase 0. [0.23 sec, 7.44 MB]                                                                                [bootstrap]
Bootstrap to phase 6. [0.23 sec, 7.45 MB]                                                                                [bootstrap]
Drush bootstrap phase : bootstrap_drupal_root() [0.24 sec, 7.82 MB]                                                        [bootstrap]
Initialized Drupal 6.38 root directory at /home/myuser/public_html/fr [0.25 sec, 7.99 MB]                                [bootstrap]
Find command files for phase 1 (max=6) [0.26 sec, 5.37 MB]                                                                     [debug]
Cache HIT cid: 8.1.3-commandfiles-1-1cc9f5fc7ac03ef4db1de660fcacf131 [0.26 sec, 5.37 MB]                                       [debug]
Cache HIT cid: 8.1.3-annotationfiles-1-818eef3e23f247f112c32dedc548471d [0.26 sec, 5.37 MB]                                    [debug]
Scanning into /etc/drush for /.*aliases\.drush(8|)rc\.php$/ [0.26 sec, 5.38 MB]                                                [debug]
Scanning into /etc/drush for /self\.alias\.drush(8|)rc\.php$/ [0.26 sec, 5.38 MB]                                              [debug]
Scanning into /home/myuser/.composer/vendor/drush/drush/includes/.. for /.*aliases\.drush(8|)rc\.php$/ [0.26 sec, 5.38       [debug]
MB]
Scanning into /home/myuser/.composer/vendor/drush/drush/includes/.. for /self\.alias\.drush(8|)rc\.php$/ [0.26 sec, 5.38     [debug]
MB]
Scanning into /home/myuser/.drush for /.*aliases\.drush(8|)rc\.php$/ [0.27 sec, 5.38 MB]                                     [debug]
Scanning into /home/myuser/.drush for /self\.alias\.drush(8|)rc\.php$/ [0.27 sec, 5.39 MB]                                   [debug]
Scanning into /home/myuser/public_html/fr/../drush for /.*aliases\.drush(8|)rc\.php$/ [0.27 sec, 5.39 MB]                    [debug]
Scanning into /home/myuser/public_html/fr/../drush for /self\.alias\.drush(8|)rc\.php$/ [0.27 sec, 5.39 MB]                  [debug]
Scanning into /home/myuser/public_html/fr/drush for /.*aliases\.drush(8|)rc\.php$/ [0.27 sec, 5.39 MB]                       [debug]
Scanning into /home/myuser/public_html/fr/drush for /self\.alias\.drush(8|)rc\.php$/ [0.27 sec, 5.39 MB]                     [debug]
Scanning into /home/myuser/public_html/fr/sites/all/drush for /.*aliases\.drush(8|)rc\.php$/ [0.27 sec, 5.39 MB]             [debug]
Scanning into /home/myuser/public_html/fr/sites/all/drush for /self\.alias\.drush(8|)rc\.php$/ [0.27 sec, 5.39 MB]           [debug]
Scanning into /home/myuser/public_html/fr/sites/fr.mysite.com for /.*aliases\.drush(8|)rc\.php$/ [0.27 sec,        [debug]
5.39 MB]
Scanning into /home/myuser/public_html/fr/sites/fr.mysite.com for /self\.alias\.drush(8|)rc\.php$/ [0.27 sec,      [debug]
5.39 MB]
Drush bootstrap phase : bootstrap_drupal_site() [0.27 sec, 5.4 MB]                                                         [bootstrap]
Initialized Drupal site fr.mysite.com at sites/fr.mysite.com [0.27 sec, 5.4 MB]                        [bootstrap]
Find command files for phase 2 (max=6) [0.28 sec, 5.4 MB]                                                                      [debug]
Drush bootstrap phase : bootstrap_drupal_configuration() [0.28 sec, 5.4 MB]                                                [bootstrap]
Find command files for phase 3 (max=6) [0.28 sec, 5.41 MB]                                                                     [debug]
sql-query: SELECT 1; [0.29 sec, 5.55 MB]                                                                                [notice]
Executing: mysql --defaults-extra-file=/tmp/drush_4tvjIm --database=myuser_dru600fr --host=localhost --silent  < /tmp/drush_gicAk0
  1
sql-query: SHOW TABLES; [0.3 sec, 5.56 MB]                                                                                [notice]
Executing: mysql --defaults-extra-file=/tmp/drush_eHsHw5 --database=myuser_dru600fr --host=localhost --silent  < /tmp/drush_aFJu7I
  access
  accesslog
  actions
  actions_aid
  advanced_help_index
  aggregator_category
  aggregator_category_feed
  aggregator_category_item
  aggregator_feed
  aggregator_item
  antispam_counter
  antispam_moderator
  antispam_spam_marks
  authmap
  batch
  better_formats_defaults
  blocks
  blocks_roles
  book
  boost_cache
  boost_cache_relationships
  boost_cache_settings
  boost_crawler
  boxes
  cache
  cache_block
  cache_content
  cache_emfield_xml
  cache_filter
  cache_form
  cache_media_youtube_status
  cache_menu
  cache_mollom
  cache_mydropwizard
  cache_page
  cache_panels
  cache_update
  cache_views
  cache_views_data
  captcha_points
  captcha_sessions
  checkout
  client
  client_system
  comments
  contact
  contemplate
  contemplate_files
  content_field_rencontre_type
  content_group
  content_group_fields
  content_node_field
  content_node_field_instance
  content_type_book
  content_type_content_publications
  content_type_image
  content_type_issue
  content_type_meeting
  content_type_page
  content_type_simplenews
  content_type_story
  content_type_video
  ctools_css_cache
  ctools_object_cache
  date_format_locale
  date_format_types
  date_formats
  discussthis
  discussthis_forums
  drupal_install_test
  excerpt
  filefield_paths
  files
  filter_formats
  filters
  flood
  forum
  history
  htmlarea
  image
  image_attach
  imagecache_action
  imagecache_preset
  imce_files
  img_assist_map
  inline
  languages
  locales_source
  locales_target
  masquerade
  masquerade_users
  media_youtube_metadata
  media_youtube_node_data
  menu_custom
  menu_links
  menu_router
  moderation_filters
  moderation_roles
  moderation_votes
  mollom
  mollom_form
  node
  node_access
  node_comment_statistics
  node_counter
  node_revisions
  node_type
  nodequeue_nodes
  nodequeue_queue
  nodequeue_roles
  nodequeue_subqueue
  nodequeue_types
  nodewords
  old_revisions
  page_manager_handlers
  page_manager_pages
  page_manager_weights
  panels_display
  panels_layout
  panels_mini
  panels_pane
  panels_renderer_pipeline
  path_redirect
  permission
  poll
  poll_choices
  poll_votes
  print_mail_node_conf
  print_mail_page_counter
  print_node_conf
  print_page_counter
  profile_fields
  profile_values
  queue
  relatedlinks
  relatedlinks_tracker
  role
  search_dataset
  search_index
  search_keywords_log
  search_node_links
  search_total
  semaphore
  sequences
  sessions
  simplenews_mail_spool
  simplenews_newsletters
  simplenews_scheduler
  simplenews_scheduler_editions
  simplenews_snid_tid
  simplenews_subscriptions
  stylizer
  system
  taxonomy_context_term
  taxonomy_context_vocabulary
  taxonomy_manager_merge
  term_data
  term_hierarchy
  term_node
  term_relation
  term_synonym
  titles_settings
  upload
  url_alias
  users
  users_roles
  variable
  view_argument
  view_exposed_filter
  view_filter
  view_sort
  view_tablefield
  view_view
  views_display
  views_object_cache
  views_view
  vocabulary
  vocabulary_node_types
  watchdog
  webform_role_node
  weblink
  weblinks
  weblinks_node
  wysiwyg
  wysiwyg_user
Drush bootstrap phase : bootstrap_drupal_database() [0.33 sec, 5.59 MB]                                                    [bootstrap]
Successfully connected to the Drupal database. [0.33 sec, 5.79 MB]                                                         [bootstrap]
Find command files for phase 4 (max=6) [0.33 sec, 5.79 MB]                                                                     [debug]
Drush bootstrap phase : bootstrap_drupal_full() [0.33 sec, 5.79 MB]                                                        [bootstrap]
session_start(): Cannot send session cookie - headers already sent by (output started at                                   [warning]
/home/myuser/.composer/vendor/drush/drush/includes/output.inc:40) bootstrap.inc:1182 [0.33 sec, 5.83 MB]
session_start(): Cannot send session cache limiter - headers already sent (output started at                               [warning]
/home/myuser/.composer/vendor/drush/drush/includes/output.inc:40) bootstrap.inc:1182 [0.33 sec, 5.83 MB]
Cannot modify header information - headers already sent by (output started at                                              [warning]
/home/myuser/.composer/vendor/drush/drush/includes/output.inc:40) bootstrap.inc:736 [0.34 sec, 6.62 MB]
Cannot modify header information - headers already sent by (output started at                                              [warning]
/home/myuser/.composer/vendor/drush/drush/includes/output.inc:40) bootstrap.inc:737 [0.34 sec, 6.62 MB]
Cannot modify header information - headers already sent by (output started at                                              [warning]
/home/myuser/.composer/vendor/drush/drush/includes/output.inc:40) bootstrap.inc:738 [0.34 sec, 6.62 MB]
Cannot modify header information - headers already sent by (output started at                                              [warning]
/home/myuser/.composer/vendor/drush/drush/includes/output.inc:40) bootstrap.inc:739 [0.34 sec, 6.62 MB]
Cache HIT cid: 8.1.3-install_profile-c66f37279ee5a91ead31fe763f40c039 [0.57 sec, 21.01 MB]                                     [debug]
Find command files for phase 5 (max=6) [0.57 sec, 21.01 MB]                                                                    [debug]
Cache HIT cid: 8.1.3-install_profile-c66f37279ee5a91ead31fe763f40c039 [0.57 sec, 21.01 MB]                                     [debug]
Cache HIT cid: 8.1.3-commandfiles-5-01051f83954cf3e8358fafb43e707c82 [0.57 sec, 21.12 MB]                                      [debug]
Cache HIT cid: 8.1.3-annotationfiles-5-bf9e2f890cdde593d4615e9c13cd401a [0.58 sec, 21.39 MB]                                   [debug]
Drush bootstrap phase : bootstrap_drupal_login() [0.58 sec, 21.37 MB]                                                      [bootstrap]
Find command files for phase 6 (max=6) [0.58 sec, 21.4 MB]                                                                     [debug]
Found command: pm-update (commandfile=pm) [0.58 sec, 21.4 MB]                                                              [bootstrap]
Calling hook drush_pm_update [0.8 sec, 24.86 MB]                                                                               [debug]
Loading release_info engine. [0.8 sec, 24.91 MB]                                                                              [notice]
Loading version_control engine. [0.8 sec, 24.92 MB]                                                                           [notice]
Loading package_handler engine. [0.81 sec, 24.93 MB]                                                                          [notice]
Executing: wget --version
Loading update_status engine. [0.82 sec, 24.92 MB]                                                                            [notice]
Including /home/myuser/.composer/vendor/drush/drush/includes/../commands//pm/updatecode.pm.inc [0.82 sec, 24.93 MB]      [bootstrap]
Calling hook drush_pm_updatecode_validate [0.82 sec, 25.02 MB]                                                                 [debug]
Returned from hook drush_pm_updatecode_validate [0.82 sec, 25.02 MB]                                                           [debug]
Calling hook drush_pm_updatecode [0.82 sec, 25.03 MB]                                                                          [debug]
Cache HIT cid: 8.1.3-alias-path--1303f2fb8c44e5041e5bb02a40a7da2c [0.82 sec, 25.04 MB]                                         [debug]
Cache SET cid: 8.1.3-alias-path--1303f2fb8c44e5041e5bb02a40a7da2c [0.83 sec, 25.04 MB]                                         [debug]
Backend invoke: /usr/bin/php-cli /home/myuser/.composer/vendor/drush/drush/drush.php --php=/usr/bin/php-cli  --backend=2   [command]
--verbose --debug --root=/home/myuser/public_html/fr --uri=http://fr.mysite.com
--db-url='mysql://myuser_fr:fr123@localhost/myuser_drupal600fr'  pm-updatestatus 2>&1 [0.83 sec, 25.05 MB]
/usr/bin/php-cli /home/myuser/.composer/vendor/drush/drush/drush.php --php=/usr/bin/php-cli  --backend=2 --verbose          [notice]
--debug --root=/home/myuser/public_html/fr --uri=http://fr.mysite.com
--db-url='mysql://myuser_fr:fr123@localhost/myuser_drupal600fr'  pm-updatestatus 2>&1 [0.83 sec, 25.06 MB]
pm-updatestatus failed. [1.38 sec, 25.13 MB]                                                                               [error]
Returned from hook drush_pm_updatecode [1.38 sec, 25.07 MB]                                                                    [debug]
Changes made in drush_pm_updatecode have been rolled back. [1.38 sec, 25.07 MB]                                                [debug]
Command dispatch complete [1.38 sec, 25.03 MB]                                                                                [notice]
Returned from hook drush_pm_update [1.38 sec, 24.99 MB]                                                                        [debug]
Command dispatch complete [1.38 sec, 24.95 MB]                                                                                [notice]
 Timer  Cum (sec)  Count  Avg (msec)
 page   1.101      1      1100.6

```

# Answer
I've finally found where the problem was: in the alias file, the 'db-url' was wrong. I've corrected it and now `drush up` seems to work well.
> 0 votes

# Answer
To know more detail about why a drush command fails you should add the -d and or -v flags to the command. -d adds debug messages and -v increases the verbosity level of messages returned, from the docs:

> -d, --debug Display even more information, including internal messages.
> -v, --verbose Display extra information about the command.
> 0 votes

---
Tags: drush, updating
---


title: Including image styles in custom module

text:
# Question
Title: Including image styles in custom module
I was following topic. I can including image style in my custom module. But I have a problem. I can't reinstall module because of following error:

> Unable to install Module ABC, image.style.black\_white already exists in active configuration.

Can I include an image style in custom module with file config and maybe reinstall module?

# Answer
> 4 votes
Your problem is don't delete image style when uninstall module. So when you reinstall image style already exist. Use can use hook\_uninstall to delete image style to finish uninstall: write code in file **module\_name.install**

```
<?php
use Drupal\image\Entity\ImageStyle;

function module_name_uninstall() {

  ImageStyle::load('image_style_name')->delete();

}

```

# Answer
> 2 votes
I think you are trying to add a new image style 'black\_white' but an image style with the same name already exist.

Solution 1. Delete the image style '`black_white`' from `/admin/config/media/image-styles`.

Solution 2. If your module has a image style configuration file "`image.style.black_white.yml`" Check or Remove it. Have you already installed / uninstalled the module ?

If you have already install/uninstall this module, try to review uninstall processes to clean up properly.

---
Tags: 8, media, configuration
---


# Question
Title: Views: What setting is available in Views to hide or skip the first entry in a multi-value field? (example skip first image)
On my site, I have created an "Images" field with "unlimited" values. I have used "image delta=0" to show only the first image as the main gallery image. I then created a grid with a contextual filter of "content: nid" to display up to 10 of the images in that field. I would like to now hide the first image from the output, so that it isn't repeated with the first/main image on the page.

I have the contextual reference working well, but I haven't been able to figure out how to skip the first image. I tried a playing around with the Image Delta settings "=1", assuming that this means to increment by 1, but when I save, my view is empty.

I'm sure this is straight forward, but I have come up empty in my attempts (literally) and searches.

Thanks, keb

# Answer
I vaguely remembered doing this in a Views tutorial and remembered it was a control located within the center region of the Views interface.

Turns out it's under "Pager": Use pager: Display a specified number of items \>\> "You may also adjust the **settings** for the currently selected pager"

Click **setttings** and you'll be able to add an offset.
> 0 votes

---
Tags: views, media
---


title: Change Field Label from h2 to div

text:
# Question
Title: Change Field Label from h2 to div
I am looking for days the PHP file which characterizes the Field label with the tag. From a certain number of tags that SEO is technically quite counterproductive.

Can Someone show me how or where to Taxonomy Term: in Taxonomy Term: can change?

I found this solution, among other things, but nothing works. Change a label element to an \<h2\>?...

Im using Commerce Kickstart 2.39 on AT-Commerce

Thank you very much

# Answer
> 2 votes
If you want a fast solution, you might want to look into using Display Suite or Fences... I recommend Display Suite.

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

It will let you change the label as you want from the admin UI, no file editing needed.

# Answer
> 2 votes
One of the good solutions for you is using Fences module,

> Fences is a an easy-to-use tool to specify an HTML element for each field. This element choice will propagate everywhere the field is used, such as teasers, RSS feeds and Views. You don't have to keep re-configuring the same HTML element over and over again every time you display the field.
>
> Best of all, Fences provides leaner markup than Drupal 7 core! And can get rid of the extraneous classes too!

and for learn how you can achieve what you want take a look at: Custom Wrappers With Fences Module (Drupal Tutorial)

---
Tags: 7, theming, commerce
---


title: How can create a download counter?

text:
# Question
Title: How can create a download counter?
How can tracks downloads of private files attached to nodes via the core upload or contributed filefield modules for custom content type, I created a file field and I simply want to count the number of times have been downloaded this file and display this count number in node template?

My Project purpose:

* Upload a file as Admin, or any authenticated user
* Store the file in a private directory (But accessible by public users)
* Allow the all people or anonymous users to download the files.

These are some details about my content type module.

* **Module name:** My Module
* **Content type name:** My Content
* **Field Type:** File
* **Display Format:** URL to file (or Generic)
* **Field name:** field\_file

I know that there are some module like:

For drupal 7, but seem none of them work in drupal 8.

Thanks for any help.

# Answer
> 3 votes
The only Drupal-centric of doing this is by making sure your content type is utilizing the Private files directory for your file field. Otherwise, downloads are served by the web server.

When private file storage is utilized, this enables Drupal as the file download gatekeeper through its **/system/files/{filepath}** route. When the controller for the download route is called, it evokes `hook_file_download()` which can be used to store your ongoing file download count.

For example a custom module could implement:

```
/**
 * Implements hook_file_download().
 */
function MYMDOULE_file_download($uri) {
  // @TODO: Store/Increment count for unique $uri.
}

```

Then reference the count when building variables for your node template:

```
/**
 * Implements hook_preprocess_node().
 */
function MYTHEME_preprocess_node(array &$variables) {
  if (isset($variables['node']->field_MYFILE_FIELD)) {
    $uri =  $variables['node']->field_MYFILE_FIELD->entity->getFileUri();
  } else {
    $uri = '';
  }
  // @TOOD: lookup count for $uri and inject it into
  // $variables['field_MYFILE_FIELD_count'] for display
}

```

---
Tags: 8, entities, files
---


# Question
Title: Display field's label only when any value added to it
For example Taxonomy Terms field **Label** is always displayed even if no tags added to it. How can I show Taxonomy Terms field's Label and its values (tag's links), only when there have been a value added to it?

I try to achieve that by adding conditionals based fields, something like below code to node template:

```
{% if content.field_tag is not empty %}
{{ content.field_tag }}
{% endif %}

```

or

```
{% if content.field_tag %}
{{ content.field_tag }}
{% endif %}

```

According to the article:Comparison of PHP Template and Twig theming paradigms but whatever I try I can't get any result.

# Answer
> 1 votes
almost you did , instead of `content.FIELD_MACHINENAME` use `node.FIELD_MACHINENAME.value` I mean try something like

```
{% if node.field_tag.value %}
{{ content.field_tag }}
{% endif %}

```

for make sure that this solution work correctly(for debug) try `{{ kint(node.field_tag }}`.

---
Tags: theming, nodes, 8, entities, taxonomy-terms
---


# Question
Title: How to modify existing language's language code?
We have found a typo with one of our language codes. We already have content within that language, but would it be possible to update the language code without having to delete/remove the language and then reading it back in?

WE are unable to find a good way to do modify just the language code..

# Answer
> 0 votes
I'm not sure if this will work, so BACK UP YOUR DATABASE FIRST, but I think that you should be able to run the following query to change fix it:

Let's say for example you were wanting to use Japanese. The language code is 'ja', but people often mistake it as 'jp'. If this was your case, and you wanted to change 'jp' =\> 'ja', you can run the following query:

```
UPDATE locales_target SET language = 'ja' WHERE language = 'jp'

```

Then clear your cache.

If this doesn't work, return your database to its previous state using the backup you took at the start (because you took a backup, right?!)

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


# Question
Title: How to show "Alternative text" of image fields in a custom content type?
I created a custom content type that its name is **News** and has an image field with **news\_image** machanic name and I added an `alternative text` to it from administration page, now I want to print that alternative text when the node content type twig template rendered.
what I want to achieve finally is schematically something like below:

```
<img src="#" title="#" alt="Alternative text">

```

> It seems this problem can be traced back to custom content type only because alternative text can be printed without any problem in default content type like article.

# Answer
> 1 votes
you can get "alt" property with `node.FIELD_MACHINE_NAME.alt` (and for image title as the same ), So your answer is

```
<img src="{{ file_url(node.field_news_image.entity.fileuri) }}" alt="{{ node.field_news_image.alt }}" >

```

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


# Question
Title: Is it possible to set block weight inside template?
I display some blocks using context module and others using template. Is it possible to set block weight inside template?

# Answer
> 1 votes
Block weight is stored in the database. There are functions to change their weight, but templates aren't the place for manipulating database data, that's where you write the HTML out.

If you want to display context blocks in a different order from the blocks in the system UI, use the "Show row weights" link to set a value that's higher/lower than the value in block admin UI.

---
Tags: 7, theming
---


# Question
Title: How to create custom rules action event conditions?
Is there any universal formula or module to create custom rules actions, events and conditions? So that I just have to replace the required values and rest of the code remains the same. I searched, but I did not find such code. I found few, but those were targeted towards a specific need/question.

For example there are lot of things missing. I am using message module to log activity. I am using statuses module and flag 2 (flag 3 is not compatible with the statuses module) I am trying to do following

1. Log statuses comments. Logs only for "currently logged in user". Cannot determine who commented. for e.g. John commented on your status update. Event available, but only shows current user name instead of who commented.
2. Log activity for "John liked your status update". No event available.
3. Similarly, for status updates comments, "likes flag".
4. John started following you on stackexchange. Event is available, but it also lacks option to tell who followed you. It also only shows current user name. Obviously you do not need your name here, you want to know who followed you.
5. John mentioned you on stackexchange. Again, instead of john, it will show current user because you do not have any option when setting up the rule.

The simple activities are easily created though.

# Answer
> 6 votes
A "*universal formula or module to create custom rules actions, events and conditions*" (as is your question), is to write a custom module. To do so, you either create a new module, or you extend any of your existing custom modules. Refer to Drupal custom Rules how to write your own events conditions, actions and custom object (+custom tokens) for a great tutorial about how to do so. The main steps that are detailed in this tutorial are further described below (with the code included below quoted from that link).

## Part 1: Defining the Event, Condition and Action

### Define the Rules Event

```
/**
* Implementation of hook_rules_event_info().
* @ingroup rules
*/
function your_module_rules_event_info() {
  return array(
    'your_module_package_bought' => array(
      'label' => t('A package was bought'),
      'module' => 'your_module',
      'arguments' => array(
        'acting_user' => array('type' => 'user', 'label' => t('The user who bought the package.')),
        'package' => array('type' => 'package', 'label' => t('The purchased package.')),
      ),
    ),
  );
}

```

### Define the Rules Condition

```
/**
 * implementation of hook_rules_condition_info()
 */
function your_module_rules_condition_info() {
  return array(
    'your_module_condition_package_type' => array(
      'label' => t('Type of the package'),
      'arguments' => array(
        'package_id' => array('type' => 'value', 'label' => t('The type of the purchased package.')),
        'package_type' => array('type' => 'string', 'label' => t('The type of the purchased package is')),
      ),
      'module' => 'your_module',
    ),
  );
}

```

### Define the Rules Action

```
/**
 * Implementation of hook_rules_action_info().
 */
function packages_rules_action_info() {
  return array(
    'your_module_action_change_order_status' => array(
      'label' => t('Change the order status'),
      'arguments' => array(
        'order' => array('type' => 'value', 'label' => t('The order object.')),
      ),
      'module' => 'your_module',
    ),
  );
}

```

## Part 2: Coding the custom Event, Condition and Action

### Event:

Somewhere in your custom module, you need to include logic to trigger the event, with something similar to this example (note the `your_module_package_bought` in it):

```
  //here the code for buying a package will be located
  //when that code returns that a package was bought trigger the rule
  $order = order_load($oid);//$oid will be the id of the order made
  $package = package_load($pid);//pid will be the id of the bought package
  global $user;
  rules_invoke_event('your_module_package_bought', $user, $package, $order);

```

### Condition:

To evaluate the Rules condition (to check if it is TRUE or FALSE), the function `your_module_condition_package_type` is executed using the arguments provided. Here is an example of how such function could look like:

```
function your_module_condition_package_type($pid, $type) {
  $package = package_load($pid);
  return ($package->type == $type) ? true : false;
}

```

### Action:

Somewhere in your custom module, you need to include logic to perform the actual action, in this example it should be done within the function named `your_module_action_change_order_status`.

---
Tags: 7, users, rules, flags, actions
---


# Question
Title: Why does my rule have no effect on a VBO list of unpublished nodes but does work for published nodes?
I set up a rule that is supposed to delete some unpublished nodes. I created a view with VBO for the rule to work with. The rule is triggered by cron, leads a list of nodes provided by the view with VBO. The rule loops through the listed item and has delete content as action.

The problem is that the rule has no effect on unpublished nodes, even though I found out that the rule and view as they're set up can delete published nodes. Could someone give me a pointer here, why the rule works on published nodes but not unpublished nodes?

# Answer
> 0 votes
Anything about Rules that uses the Rules Scheduler, runs for sure with "Anonymous" authorizations. There are cases (Rules Actions) for which that auth is insufficient of course.

So a possible explanation for the cause of your issue, is that your unpublished nodes are not included in your VBO views result. To verify if this is indeed the reason that causes your issue, just check the views results you get by looking at the Views results without being logged in (so as Anonymous user). If those unpublished nodes are included anyway, verify if Anonymous users are authorised to delete those nodes.

---
Tags: 7, nodes, rules, views
---


# Question
Title: How can I add HTML tags into menu title?
How can I add HTML tags into menu title?

I'm also tryed the following code.

```
function adminimal_theme_preprocess_menu(&$vars) {
  if ($vars['menu_name'] === 'main') {
    $vars['items']['standard.front_page']['title']='<i class="icon-home"></i>';
  }
}

```

It also converts tags into HTML entities.

# Answer
You need to tell drupal that the string is safe. When you use `t()` this is done automatically. But this would make no sense here, because there is nothing to translate.

In this case you can use an untranslatable markup:

```
use Drupal\Core\Render\Markup;

function adminimal_theme_preprocess_menu(&$vars) {
  if ($vars['menu_name'] === 'main') {
    if (isset($vars['items']['standard.front_page'])) {
      $vars['items']['standard.front_page']['title'] = Markup::create('<i class="icon-home"></i>');
    }
  }
}

```
> 6 votes

# Answer
You can use supporting modules for this task. please check the following:

> https://www.drupal.org/project/menuimage
>
> https://www.drupal.org/project/menu\_icons

Hope it will be helpful for you.
> 0 votes

---
Tags: 8, navigation
---


# Question
Title: How to change link in a view depending on state of a certain field
I have a content type called conference, there are two types of conferences; supported and unsupported.

Supported have their own node inside Drupal, unsupported link out to external websites rather than having their own node. Supported also have the same external link.

There is a field selection for this in the conference content type so the user picks whether a conference is supported or unsupported.

Now I have a view of conferences and their title is a link. However I need to check whether each conference is supported or unsupported, as this link will either be a link to the node or a link externally.

Looking for any suggestions on how to achieve this, I'm guessing views PHP would achieve this, but is this the best option?

# Answer
> 0 votes
You can use the field token of the field which is used to picks whether a conference is supported or unsupported. Then you can link it to a node or external link,

---
Tags: views
---


# Question
Title: How to create custom blocks for a custom theme?
I am new to Drupal and creating a custom Drupal theme from a HTML template.

For some sections, I want to create custom blocks with some specific functionality. For example there is a counter running on right sidebar in HTML template. I want to create a block so users can adjust this block in any region they want.

My main concern is that if users install my Drupal theme on their site, this block should automatically be available in structure block list like main menu and others shows by default.

There is no particular ways defined on any site?

# Answer
> -2 votes
you probably need to create a custom module as well to create a custom block. Look at this http://redcrackle.com/blog/how-create-block-drupal-7 to get an idea how to create a block.

The block you create inside the custom module will always be available at admin/structure/block page. Then it can be assigned to any region.

---
Tags: 7, theming, blocks
---


# Question
Title: Rules does not have any action for publish selected content
In `admin/content` page we have some update options. I want to execute a Php code only when I use `publish selected content` or `unpublished selected content` on that page.

This rules should be fired JUST when I `publish/unpublished selected content`

# Answer
> 0 votes
You can use drupal's `hook_form_alter()` for firing your PHP code. Check below example:

```
function contr_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'node_admin_content'){
    $form['admin']['options']['submit']['#submit'][] = 'CUSTOM_SUBMIT_HANDLER';
  }
}

```

and then you can write your PHP code in CUSTOM\_SUBMIT\_HANDLER function as below:

```
function CUSTOM_SUBMIT_HANDLER($form, $form_state){
  if($form_state['values']['operation'] == 'publish'){
    // Do your stuff when PUBLISH here.
  }elseif ($form_state['values']['operation'] == 'unpublish') {
    // Do your stuff when UNPUBLISH here.
  }
}

```

# Answer
> 0 votes
You probably need to alter the action performed on publish or unpublish of the node.

Try using hook\_action\_info\_alter to alter the existing actions.

https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_action\_info\_alter/7.x

---
Tags: 7, nodes, rules, actions
---


title: Migration of content

text:
# Question
Title: Migration of content
I am able to migrate organic groups easily enough, but when I attempt to migrate the group content, I am not able to successfully migrate the "parent" group ID(s) (or group audience if you prefer). I could only find snippets of code, and never a complete example, so hopefully I'm missing something simple.

Here is my complete migration code for the group content (as per multiple sources, but for example and per the OG issue page:

```
  $arguments = $common_arguments + array(
    'description' => t('Migration of group nodes from Drupal 6'),
    'machine_name' => 'RanchoNodeGroupNews',
    'source_type' => 'groupnews',
    'destination_type' => 'groupnews',
  );
  Migration::registerMigration('RanchoGroupNewsMigration', $arguments['machine_name'], $arguments);

class RanchoGroupNewsMigration extends RanchoNodeMigration {
  public function __construct(array $arguments) {
    parent::__construct($arguments);

    // OG Audience field
    $this->addFieldMapping('og_group_ref', 'og_group_ref')
         ->separator(',')
         ->sourceMigration('RanchoNodeGroup');
    $this->addFieldMapping('is_public', 'is_public');
    // Set the default owner to rm.com
    $this->addFieldMapping('uid', 'uid')
         ->defaultValue(4);

    $this->addUnmigratedSources(array(
    ),'DNM', FALSE);

    $this->addUnmigratedDestinations(array(
    ),'DNM', FALSE);

  }

  protected function query() {
    // Get the default query
    $query = parent::query();
    $query->leftJoin('og_ancestry','oga','n.nid = oga.nid');
    $query->addExpression('GROUP_CONCAT(DISTINCT oga.group_nid)', 'og_group_ref');
    $query->addField('oga', 'group_nid', 'group_nid');
    $query->addField('oga', 'is_public', 'is_public');

    return $query;
  }

  public function prepareRow($row) {
    if (parent::prepareRow($row) === FALSE) {
      return FALSE;
    }
    drush_print_r($row->og_group_ref);
    return TRUE;
  }

  public function prepare($node, stdClass $row) {
    // Set og field_mode to 'admin' so we can save this group content despite not being a member of the group.
    // See https://www.drupal.org/node/2399997
    if (!empty($node->og_group_ref[LANGUAGE_NONE])) {
      foreach($node->og_group_ref[LANGUAGE_NONE] as $delta => $value) {
        $node->og_group_ref[LANGUAGE_NONE][$delta]['field_mode'] = 'admin';
      }
    }
    drush_print_r($node->og_group_ref);
  }
}

```

The output I receive from drush\_print\_r is as follows:

```
drush mi RanchoNodeGroupNews --idlist=60274 --user=1
56288
Array
(
    [und] => Array
        (
            [0] => Array
                (
                    [target_id] => 56288
                    [field_mode] => admin
                )

        )

)

Processed 1 (1 created, 0 updated, 0 failed, 0 ignored) in 0.2 sec (267/min) - done with 'RanchoNodeGroupNews'

                          [completed]

```

Note that nid 56288 is indeed the parent group node, and is the only parent that has been migrated. I am able to edit the group content and set the parent manually. Any idea what's wrong with my code?

# Answer
Seems like a bug, but needed to add a complete() function as follows:

```
class RanchoGroupNewsMigration extends RanchoNodeMigration {
  public function __construct(array $arguments) {
    parent::__construct($arguments);

    // OG Audience field
    $this->addFieldMapping('og_group_ref', 'og_group_ref')
         ->separator(',')
         ->sourceMigration('RanchoNodeGroup');
    $this->addFieldMapping('group_access','group_content_access');

    ...

  }

  protected function query() {
    // Get the default query
    $query = parent::query();
    $query->leftJoin('og_ancestry','oga','n.nid = oga.nid');
    $query->addExpression('GROUP_CONCAT(DISTINCT oga.group_nid)', 'og_group_ref');
    $query->addField('oga', 'group_nid', 'group_nid');
    $query->leftJoin('og_access_post','oa','oa.nid = n.nid');
    $query->addField('oa','og_public','group_content_access');

    return $query;
  }

  public function prepareRow($row) {
    if (parent::prepareRow($row) === FALSE) {
      return FALSE;
    }
    // Seems the access setting is actually the opposite in D7, so we need to
    // toggle the boolean here.
    $row->group_content_access = !$row->group_content_access;
    return TRUE;
  }

  public function prepare($node, stdClass $row) {
    // Set og field_mode to 'admin' so we can save this group content despite not being a member of the group.
    // See https://www.drupal.org/node/2399997
    if (!empty($node->og_group_ref[LANGUAGE_NONE])) {
      foreach($node->og_group_ref[LANGUAGE_NONE] as $delta => $value) {
        $node->og_group_ref[LANGUAGE_NONE][$delta]['field_mode'] = 'admin';
      }
    }
  }

  public function complete($node, stdClass $row) {
    $values = array(
      'entity_type' => 'node',
      'entity' => $node->nid,
      'state' => OG_STATE_ACTIVE,
      'membership_type' => OG_MEMBERSHIP_TYPE_DEFAULT,
      'field_name' => 'og_group_ref',
    );
    // Update the node
    $group_id = $row->og_group_ref;
    og_group('node', $group_id, $values);
  }
}

```

The above works regardless the number of groups the node is assigned to.

Note because this took me quite some time to figure out: the og\_access and og\_public have the opposite meaning from D6 to D7.
> 0 votes

---
Tags: 7, migrations
---


title: how to run cron hook after a week

text:
# Question
Title: how to run cron hook after a week
i have created a module to hook Drupal cron system and the function in my module is being executed on every cron run, which is perfect.

I need this hooked cron function to run only once weekly without scheduling the default Drupal cron job . Any help on this ? Thanks

# Answer
> 3 votes
Check out the variety of cron modules that set intervals, like Elysia cron.

https://www.drupal.org/project/elysia\_cron

---
Tags: 7, cron
---


# Question
Title: Loading taxonomy term missing the custom field data
```
  foreach ($tids as $tid) {
200     try{
201       $term = taxonomy_term_load($tid);
202       if(!empty($term) && !empty($teams_records[$term->name])) {
203         //term objects before update
204         $pre_term_objects_log .= print_r($term, TRUE);
205         $pre_term_objects_log .= "\n";
206         $pre_log_message .= ap_cfb_get_log_msg($term);
207         $term->field_conf_record[LANGUAGE_NONE][0]['value'] = $teams_records[$term->name]['in_conference'];
208         $term->field_overall_record[LANGUAGE_NONE][0]['value'] = $teams_records[$term->name]['overall'];
209         taxonomy_term_save($term);
210         $post_log_message .= ap_cfb_get_log_msg($tid, 1, $post_object_log_file);
211       }
212     }
213     catch(Exception $e){
214       $transaction->rollback();
215       $taxonomy_save_log_file_path = $cfb_files_path.'ap_teams_taxonomy_log.txt';

```

Some associated fields data of the taxonomy term are missing when loading the data using the Drupal functions taxonomy\_term\_load() and taxonomy\_term\_load\_multiple(), but data exist in the database.

On further investigation, I came to know that the Drupal functions taxonomy\_term\_load() and taxonomy\_term\_load\_multiple() are not getting the values from database for one of the team/term.

Are there any issues with Drupal core functions fetching the data from cache\_tables\* ?

Does the above function code have any issues?

Do we need to write custom SQL queries to fetch the term ID?

# Answer
> 0 votes
If entity\_cache is preventing that, you can call: `entity_get_controller('taxonomy_term')->resetCache(array($tid));` directly in your code, to ensure that specific term cache is reset (but without clearing more caches than needed).

Note that without entity\_cache, the controller for taxonomy\_term is TaxonomyTermController, but with entity\_cache enabled it is EntityCacheTaxonomyTermController – so check out how EntityCacheTaxonomyTermController::resetCache works (this is what will be called with the above snippet.

Regarding your question about a custom query: I'm adding my comment above to my answer because it is part of your original questions:

> Also note that if you do construct custom queries to pull out the data directly from tables you are aware of, this may be the lightest but most fragile approach, making code difficult to maintain and brittle as new code is added to the project.

---
Tags: taxonomy-terms
---


# Question
Title: Get default min and max default values in views exposed filter form element
I have a views display that lists out content that meets a criteria defined by an exposed form. One of the filters is 2 values which a content attribute must be between. In views, I can define this as a default min and max value.

I would like to get these default values out as data attributes on the form fields for some javascript validation, and therefore will need to be able to get these as twig variables in the form element template, or set these as attributes in the form element preprocess.

The inputs initially have the value of the default min and max, but as soon as these are changed there is no way I can see to access the defaults.

How can I do this?

# Answer
> 0 votes
```
function MYTHEME_preprocess_input(&$variables) {
  if (isset($variables['element']['#default_value'])){
    $variables['attributes']['data-default-value'] = $variables['element']['#default_value'];
  }
}

```

---
Tags: views, 8
---


# Question
Title: How to pass variables to a theme template file from EntityAPIController::buildContent()
I may be going about this incorrectly, if so please point me in the right direction.

I currently have a custom entity type and I'm adding the display fields via a controller class that extends EntityAPIController. I want to attach some content from elsewhere (non-entities) to the display of this custom entity.

I have an implementation of `hook_theme`:

```
function module_theme($existing, $type, $theme, $path) {
  return [
    'module_plugin_instance' => [
    'template' => 'module-plugin-instance',
    'path' => $path . '/templates',
      'variables' => [
        'instance_id' => NULL,
      ],
    ],
  ];
}

```

Then, in `EntityTypeController::buildContent()` I have:

```
$buildContent['module_plugin_instance_' . $instance_id] = [
  '#theme' => 'module_plugin_instance'
];

```

Where I'm failing is I can't figure out how to pass variables to the theme template here. The dummy html I'm putting in the template renders fine, just no variables. I've tried several different things, but I can't seem to get `$instance_id` to my template - what am I doing wrong?

# Answer
You can provide theme variables through properties, e.g.:

```
$buildContent['module_plugin_instance_' . $instance_id] = [
  '#theme' => 'module_plugin_instance',
  '#instance_id' => 'foo',
];

```
> 2 votes

---
Tags: 7, theming, entities
---


# Question
Title: How to display menu link language in List Link view of menu?
We have a menu, Main Menu. When we view List Links of that menu we can see all the menu links. However, we do not know which menu link is associated to what language.

What would it take to make the page also display the language on the List Links Display? WE tried to modify the menu.admin.inc file to include the language value that is not working.

Page of interest: admin/structure/menu/manage/main-menu

# Answer
> 0 votes
You're looking at making significant changes to the form builder `menu_overview_form` (e.g. via `hook_form_alter()`) or perhaps a complete replacement at the menu route **admin/structure/menu/manage/%menu** handler (e.g. `hook_menu_alter()`) in `menu_menu()`.

Looking at the form builder shows the scope of the problem, it is making DB query that you'll need to augment with relevant logic for combining with language column. In addition, there is helper function, `_menu_overview_tree_form()` that builds out the form elements that is coupled with the `$tree` structure that's coupled with the result of DB query.

Given that, it might be easier for you to replace the route handler with your own custom form than trying to hack around the existing form. You certainly don't want to start hacking menu.admin.inc as your question implies.

---
Tags: 7, hooks, forms, navigation
---


# Question
Title: Redirect when translation of node is unavailable
I have installed pathauto and i18n and I would like to create a node which is only available in one language. Lets say I have a Basic Page with the URL:

www.example.de/test-page-in-german

so I dont want this page to be available from

www.example.pl/test-page-in-german

because I am afraid google is gonna ban my site for double content. Ive already selected "Require language (Do not allow Language Neutral)" for my content type and for "test-page-in-german" I have selected german and their is no translation but the node is still visible from other language domains.

# Answer
I finally got it working with the Global Redirect Module

I had to enable the option ***Language Path Checking***.

Then I got another problem with the redirects which was fixed by this patch:

https://www.drupal.org/node/1514166#comment-11657665
> 0 votes

---
Tags: i18n-l10n, redirection
---


title: Taxonomy else if not working

text:
# Question
Title: Taxonomy else if not working
my code not working. I'm trying to get custom breadcrumbs if user is different taxonomy vocabulary category page. if elseif's not working, but I don't know why..

Example: If I go to taxonomy term page that vocabulary id is 2, breadcrumbs is:

Page 1 \> Page 1 \> Term name

and vocabulary id 2, breadcrumb looks like this:

Page 2 \> Page 2 \> Term name

and if ID is not defined it shows default breadcrumbs ( else )..

It shows page 1 and else breadcrumbs but else if statement not working..

Is that code correct or what?

```
 /*
 * Taxonomy term callback page
 */

function taxonomy_taxonomy_term_page($term_id) {
$term = taxonomy_term_load($term_id);
$html = '';
$breadcrumb = array();
$parents = taxonomy_get_parents($term->tid);
$desired_vocab_1 = 1; // Vocabulary ID
$desired_vocab_2 = 2; // Vocabulary ID
$desired_vocab_3 = 3; // Vocabulary ID

if(count($parents) > 0) {

    $show_sub_cat = false;
    $list = get_legal_articles($term->tid);
    foreach($parents as $item)
        $_parent = $item;

    $breadcrumb[] = l(t('Default page'), 'Default page');
    $breadcrumb[] = l($_parent->name, 'taxonomy/term/'.$_parent->tid);

    $html =  theme('category_details', array('term' => $term, 'list' => $list, 'is_sub_cat' => $show_sub_cat));

 } else {

 if (((arg(0) == 'taxonomy')
 && (arg(1) == 'term')
 && is_numeric(arg(2))
 && ($term = taxonomy_term_load(arg(2)))
 && ($term->vid == $desired_vocab_1))) {

$breadcrumb[] = l(t('Page 1'), 'Page 1');

$childs = taxonomy_get_children($term->tid);

$html = theme('parent_category_details', array('term' => $term, 'list' => $childs));

 } elseif (((arg(0) == 'taxonomy')
  && (arg(1) == 'term')
  && is_numeric(arg(2))
  && ($term = taxonomy_term_load(arg(2)))
  && ($term->vid == $desired_vocab_2))) {

$breadcrumb[] = l(t('Page 2'), 'Page 2');
$breadcrumb[] = l(t('Page 2.1'), 'Page 2.1');

$childs = taxonomy_get_children($term->tid);

$html = theme('private_category_details', array('term' => $term, 'list' => $childs));

} else {

$breadcrumb[] = l(t('Page 3'), 'Page 3');
$breadcrumb[] = l(t('Page 3.1'), 'Page 3.1');

$childs = taxonomy_get_children($term->tid);

$html = theme('private_category_details', array('term' => $term, 'list' => $childs));

}

// Set Breadcrumbs
drupal_set_breadcrumb($breadcrumb);
drupal_set_title($term->name);

return $html;
}

```

# Answer
> 0 votes
In your code the html of 'Default page' is never returned. I have refactored it a little bit to make it cleaner and easier to maintain.

```
/*
 * Taxonomy term callback page
 */
function taxonomy_taxonomy_term_page($term_id) {
  $term = taxonomy_term_load($term_id);
  $breadcrumb = array();
  $parents = taxonomy_get_parents($term->tid);
  // Vocabulary IDs
  $desired_vocab_1 = 1;
  $desired_vocab_2 = 2;
  $desired_vocab_3 = 3;

  if (count($parents) > 0) {
    $show_sub_cat = false;
    $list = get_legal_articles($term->tid);

    foreach ($parents as $item) {
      $_parent = $item;
    }

    $breadcrumb[] = l(t('Default page'), 'Default page');
    $breadcrumb[] = l($_parent->name, 'taxonomy/term/' . $_parent->tid);
    $html = theme('category_details', array('term' => $term, 'list' => $list, 'is_sub_cat' => $show_sub_cat));
  }
  else if (arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))) {
    $term = taxonomy_term_load(arg(2));

    switch ($term->vid) {
      case $desired_vocab_1:
        $breadcrumb[] = l(t('Page 1'), 'Page 1');
        break;
      case $desired_vocab_2:
        $breadcrumb[] = l(t('Page 2'), 'Page 2');
        $breadcrumb[] = l(t('Page 2.1'), 'Page 2.1');
        break;
      case $desired_vocab_3:
        $breadcrumb[] = l(t('Page 3'), 'Page 3');
        $breadcrumb[] = l(t('Page 3.1'), 'Page 3.1');
        break;
      default:
        $breadcrumb[] = l(t('Default page'), 'Default page');
    }

    $childs = taxonomy_get_children($term->tid);
    $html = theme('private_category_details', array('term' => $term, 'list' => $childs));

    drupal_set_title($term->name);
  }

  // Set Breadcrumbs
  drupal_set_breadcrumb($breadcrumb);

  return $html;
}

```

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


title: What is wrong with my render code?

text:
# Question
Title: What is wrong with my render code?
I am trying to create a custom content pane where I would be able to specify 8 values and create 4 divs with 2 values in each one of them. For this I am extending cTools module by creating a plugin. I am already able to fetch input and store it in `$conf` variable. The problem is that it seems that everything I do in render `function` doesn't work. At first I though I had some naming problems. My module name is

> uzduotis

And here is my code for render function:

```
function uzduotis_render($subtype, $conf, $args, $context) {

  $block = new stdClass();
  $block->title = "4Divs";

  $html = '';
  foreach ($conf as $key => $items) {
       $html .= '<div class="element">' . $items['text'] . $items['link'] . '</div>';
  }

  $block->content=$html;

  return $block;

  dpm($block);
}

```

I try to dpm my block and I get nothing, also another strange thing is that even a block title doesn't show up which I guess notifies that something is completely wrong. Can someone please point out what is wrong? If you need some additional information, please ask for it and I will update. Thank you in advance.

# Answer
Blocks need to be render array. You are returning an object. This is how to do it:

```
function uzduotis_render($subtype, $conf, $args, $context) {
  $block = array(
    'title' => '4Divs',
    'content' => array(),
  );

  foreach ($conf as $key => $items) {
    $block['content'][] = array(
      '#prefix' => '<div class="element">',
      '#suffix' => '</div>',
      '#markup' => $items['text'] . $items['link'],
    );
  }

   return $block;
}

```
> 0 votes

# Answer
You cannot run any code after a `return` statement. By definition the `return` will exit the function. Try moving the `dpm` call to just before the `return` statement.

As an aside, I believe that best practices say that $block-\>content should be a render array and not straight up html...
> 1 votes

---
Tags: 7, chaos-tool-suite
---


title: Change view css based on field value?

text:
# Question
Title: Change view css based on field value?
the view shows a simple article, i want to show the view in rtl direction if a specific field value is YES for example, if the value is NO, then the view will be displayed as ltr.

I have a hidden field that have two values, Yes or No, based on them i need to change the VIEW. only the view, everything else in the page must stay the same.

How to achieve that please

# Answer
It is easily achievable with drupal\_add\_css in a hook\_preprocess\_views\_view.

An example of it can be found in the last comment here.
> 1 votes

---
Tags: views
---