# Question
Title: How to remove language indicator in content region?
It took me a while to figure out how to remove the language switches from the bottom of each page. Eventually the switch was in a somewhat logical location (Multilanguage settings \> Article options). (Oh, new question. I translated those menu items myself, because - mysteriously - my "backend" is in German. I don't remember how that happened. Everything I can find, default language, user language, is set to English. Where can the "backend" language be set?)
But what I've come here for:
There still is a language indicator at the bottom of each page ("Language: English"), and I cannot find how to get rid of that. CSS would be fine, but it does not have a specific class/id, so I cannot grab it.

# Answer
I found it! Or so I believe, but currently it seems to work:

In Structure » Content types » Simple Page » Manage display ... there is an area "CUSTOM DISPLAY SETTINGS". Checkmarking "Teaser" there adds an option to edit settings for teasers where the language indicator can be hidden.
> 3 votes

# Answer
> Home » Administration » Configuration » Regional and language » Multilingual settings

then

go to the "Node Options" tab

check

> Hide content translation links
> 14 votes

# Answer
You haven't mentioned if you're using Drupal 6 or 7. I only have experience with i18n on D7 and my answer is based on that experience.

Visit http://example.com/admin/structure/types/manage/\[content-type\]/display (Admin \> Structure \> Content types \> \[Content Type\] \> Manage Display) and set language to hidden.

Answer to bonus question: Visit http://example.com/user and you can set your default language
> 5 votes

# Answer
None of the above worked for me. In case it helps future readers, there is a different solution if you are using Drupal 7 plus the Entity translation module.

In Structure \> Content types \> \[Content Type\] \> Edit, select "Publishing options" then tick "Hide content translation links".
> 3 votes

# Answer
For Drupal 7:

In Structure \> Content types \> \[Content Type\] \> Edit, select "Publishing options" then click "Disable" under "Multilingual support".
> -1 votes

---
Tags: i18n-l10n
---


# Question
Title: Can the reaction of "Cron Maintenance" in the Rules modules pull data from nodes?
**Overall Goal:** Have an email sent whenever a node has not been commented on for a certain amount of time (ex: 1 hour).

**Previous Attempt:** Have a node become stickied when a comment is posted. Then unsticky the node after a certain amount of time. If a node is not stickied, send an email. This worked for one evaluation time rather than having evaluation over the life of the node.

**How it could be done for continuous evaluations:**
1. Use the same concept from previous attempt and have nodes stickied when commented on.
2. Have a Rule react on Cron Maintenance that will unsticky any nodes that have the newest comment older than a given time amount.
3. Then have another rule that runs on Cron Maintenance to send emails to a user that is specified within a node's field when said node is not sticky.

My main issue about this is that any Rule that is reacting on Cron Maintenance isn't letting me pull information from the node table.

# Answer
> Previous Attempt: Have a node become stickied when a comment is posted. Then unsticky the node after a certain amount of time. If a node is not stickied, send an email. **This worked for one evaluation time rather than having evaluation over the life of the node.**

Activate the Rules Scheduler module (comes with Rules)

Sorry, I missed a step. For your If and Else Statement Add Action of Schedule Component Evaluation and select your component. So you basically re-schedule your component evaluation. Thus, you get continuous evaluation.

Result:
> 3 votes

---
Tags: 7, rules, comments, cron
---


title: How do I create a front page?

text:
# Question
Title: How do I create a front page?
I am developing new website in D7 and I have installed bootstrap theme on the of it.

So, now I want to create home page/front page for my website and for that I have created a basic page, but I am not able to add CSS and JS in that basic page.

What approach should I use to create a front page in Drupal 7?

# Answer
> 3 votes
Depends on what your needs are. One approach is to go with panels. It gives you a nice UI for including blocks, nodes and other pieces of content.

> The Panels module allows a site administrator to create customized layouts for multiple uses. At its core it is a drag and drop content manager that lets you visually design a layout and place content within that layout. Integration with other systems allows you to create nodes that use this, landing pages that use this, and even override system pages such as taxonomy and the node page so that you can customize the layout of your site with very fine grained permissions.

The second approach, which has become my preferable, is to create your frontpage as a node and add the necessary views or blocks on it.

Regardless of your approach, if you are in need to add js and css files in the frontpage you can add the following in you template.php file(source):

```
function yourtheme_preprocess_page(&$vars) {
  if(drupal_is_front_page()) {
    drupal_add_js(drupal_get_path('theme', 'yourtheme') . '/js/your-front-script.js');
    drupal_add_css(drupal_get_path('module', 'example') . '/example.css');
  }
}

```

# Answer
> 4 votes
There are two option:

1. Use a different template for the front page you have to name your template page--front.tpl.php and clear the theme registry. Please check Theming Guide for more details.
2. There's also the Front Page module: http://drupal.org/project/front

# Answer
> 0 votes
If you look at the frontpage's source code you'll find something like this:

```
<body style="padding-top: 65px;" class="html front logged-in no-sidebars page-node toolbar toolbar-drawer i18n-es disqus-processed">

```

so you may want to create a css rule that applies to `.front` class.

# Answer
> 0 votes
create page--front.tpl.php template file inside your theme tpl folder.

It will work

---
Tags: 7, theming
---


# Question
Title: Customizable combo select multiple and autocomplete
My client wants an input element for a custom form to behave like this:

* Dropdown checkbox multiple
* Autosuggest field

So if we have a list of countries (Spain, UK, USA), it can display all the elements, and allows to select several of them. And if it is a long list of countries, you could search by entering the few letters, and only those items which match the entered letters would appear.

As for the first behaviour, I have found the following module "Dropdwon checkboxes". As for the second one, I haven't found any module so far, but in the wild there is this example (see example: *Filtering mode: (filter existing list)* ).

Any idea on how could I get the result? Maybe injecting some custom Javascript (jQuery) code into the multiple checkbox customized with the first module, to add the autocomplete capabilities?

# Answer
> 3 votes
As you suggest you have achieved the first one so supposing you have a dropdown with values then you can use the jQuery plugin / javascript to make the select an Autocomplete field. You can use select2

Thanks

# Answer
> 1 votes
There a quite a few for that but my favorites are:

1. Chosen
2. select2 (as suggested by Mohit)

---
Tags: 7
---


title: create a custom node token

text:
# Question
Title: create a custom node token
I want to create a new token form the selected item in the list box of currently submited node and set it as url alias of the node.

unfortunately, I need keys of select box as token but default tokens do not have this item(it just has labels of listboxes). so I decided to create it's token programmatically.

this is the code but I do not know how to set selected item of list box in `$value`

```
function cool_token_token_info() {

  $info['tokens']['node']['key1'] = array(
    'name' => t('My cool token'),
    'description' => t('A token I use to show that I am cool.'),
  );
  return $info;
}

function cool_token_tokens($type, $tokens, array $data = array(), array $options = array(),$node=array()) {
  $replacements = array();
  $sanitize = !empty($options['sanitize']);
  if ($type == 'node') {
    // Loop through the available tokens.
    foreach ($tokens as $name => $original) {
      // Find our custom tokens by name.
      switch ($name) {
        case 'key1':
          // Work out the value of our token.
          if (isset($node)){
                $value= "here I want to have key of the selected item in the listbox of current node";
          }else{
              $value="not working";
          }
          // Give our token it's value!
          $replacements[$original] = $value;
          break;
      }
    }
  }

  return $replacements;
}

```

I tried

```
field_get_items('node', $node, 'field_parent')

```

and many many other ways but it does not print anything

# Answer
> 2 votes
Check this example code:

```
/**
* Implements hook_token_info().
*/
function yourmodulename_token_info() {
  $info['tokens']['node']['city'] = array(
    'name' => t('Venue City'),
    'description' => t('Returns the Venue city (Location)'),
  );
  return

$info;
}

/**
* Implements hook_tokens().
*/
function yourmodulename_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();

  if ($type == 'node' && !empty($data['node'])) {
    $node = $data['node'];
    if (isset(

$tokens['city'])) {
      $replacements[$tokens['city']] = pathauto_cleanstring($node->field_location['und'][0]['city']);//here I retrieve the value of the city in the location field.
    }
  }

  return $replacements;
}

```

# Answer
> 1 votes
Try using the Computed field or Token Field to achieve this.

---
Tags: entities, uri, tokens
---


title: Theme search-result pages individually?

text:
# Question
Title: Theme search-result pages individually?
We can theme the search-result pages within `search-results.tpl.php` and `search-result.tpl.php`. But as far at it is possible to create multiple search pages(e.g. in apache solr module), is it possible to theme each page individually?

Example:

```
search-results--page1.tpl.php
search-results--page2.tpl.php

```

# Answer
It is possible.

Apache solr search module introduced tpl files for each search page.

If your custom search page's machine name is simple search, the search results tpl for that page will be named as

```
    search-results--apachesolr-search--simple-search.tpl.php

```

Replace *simple-search* with the machine name of your search page, with underscores converted to hyphens.
> 1 votes

---
Tags: search
---


title: Commerce Analytics not working

text:
# Question
Title: Commerce Analytics not working
On my website we don't get any e-commerce tracking in Google Analytics. Usual analytics works fine. How do I troubleshoot?

Have sold around 200 products since installing & configuring the Google Analytics and Commerce Analytics modules.

The module maintainers haven't replied on the same request on drupal.org https://www.drupal.org/node/2612390

Cheers,

**EDIT**: I updated from Commerce Analytics from 7.x-1.1 to 7.x-2.0-beta2. Still nothing in Google Analytics, but now ga\_push appears in source code.

# Answer
What method are you using to Push? Configuring the rule, you can select it at the bottom of the edit page:

I just tried it with Analytics.js support and the checkout page appears to display the Analytics code:

```
<!--//--><![CDATA[//><!--
var ga = ga || [];
ga('require', 'ecommerce', 'ecommerce.js');
ga('ecommerce:addTransaction', {"id":"5","affiliation":"Commerce Kickstart","revenue":16,"currency":"USD","tax":0,"shipping":8,"city":"Austin","region":"Texas","country":"United States"});
ga('ecommerce:addItem', {"id":"5","sku":"MG2-YLW-OS","name":"Coffee Mug 2","category":"Product: drinks","price":8,"currency":"USD","quantity":1});
ga('ecommerce:addItem', {"id":"5","sku":"shipping","name":"Standard shipping: 3 - 5 business days","category":"Shipping","price":8,"currency":"USD","quantity":1});
ga('ecommerce:send');

//--><!]]>

```

This appears to be correct. One of the difficulties with testing GA for Commerce is that they do not show up in realtime.

So, I'd try it with Analytics.js if you aren't currently using that method and ensure that something like what you see above is being included on the page. If it isn't, then something isn't working on the site side. If it displayed, then check your JS console for errors to see if something else happened. You can also open up the Network tab and ensure that you're seeing the calls to "collect":
> 3 votes

---
Tags: commerce, google-analytics
---


# Question
Title: How can I detect what control caused AJAX callback?
I have a form containing a table, which displays rows from a database table, and has a couple of editable fields, which is all working fine.

I now want to make one of fields trigger an AJAX callback when changed, and the callback to update another field in the same row.

Can the callback function check which instance of the changed field triggered the callback, so it knows which row to update?

Thanks for your help, and happy new year!

James

# Answer
> 2 votes
I use this code since drupal 7, only changed the first line for drupal 8:

```
$triggering_element = $form_state->getTriggeringElement();
if ( isset($triggering_element) ) {
  $trigger = $triggering_element['#name'];
  if ( $trigger == 'op' ) {
    $trigger = $triggering_element['#parents']['0'];
  }
}
else {
  $trigger = '';
};

```

If trigger is 'op', then it is a button and i get the name from the parent.

And see comment of Ivan Jaros, make the names unique.

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


title: Linking one view to another

text:
# Question
Title: Linking one view to another
Here is my scenario - I have populated my content in a panel which consists of 3 views. Each view has a set of documents. At the bottom of the page (panel page), I want to add a link which when clicked will take me to another view page populated with all documents from the caller node. I'm very new to drupal and not able to figure out how to do it.

Please put in your suggestions on how I can do this. Thank you

# Answer
What controls the documents shown in the initial caller views? Is it a list of IDs, certain Taxonomy, some custom field, etc?

This is important as it will control how the view page lists the documents you want from the caller view.

If the initial view was displaying documents based on any option that was not ID, then you could easily create a link in the footer and include a parameter. The link should go to the URL of the View Page and include the arguments needed to filter the results shown on the page. It would look something like this:

http://www.example.com/documents/all?argumentname\_here=\[thiswouldbeatoken\]

The token would be the value of the category, taxonomy, etc. that you used in the initial view.

The view page would need to be setup to not use AJAX, so it can use the URL arguments, and should have an exposed filter matching the filter of the caller view (you could then hide this with CSS so it can't be changed later, but let's leave it alone for now).

If you need help figuring out what the URL should look like, try filtering the View Page and clicking Apply and looking at the structure in the URL then mimic this in your initial caller view.

Hope this helps!
> 0 votes

---
Tags: views, panels
---


# Question
Title: How do I update the URL after changing the hosting of a website?
Our website recently changed hosts. After updating the named servers the home page shows but all links in the page take you to 404 error. The new host advises that the URL links need to be refreshed.

# Answer
There are a couple of possibilities when this happens. The first is to make sure that you still have an .htaccess file, as moving between hosts sometimes doesn't include the hidden files.

If you do have it, depending on the server, the Symlinks may need to be changed. For instance my Ubuntu server needs the .htaccess file to be changed to this in order for it to work

```
#Options +FollowSymLinks // Commented out
Options +SymLinksIfOwnerMatch

```

The next possibility is that the DNS propagation hasn't finished yet. It can take up to 72 hours with some hosts before everything is fully refreshed and pointing the right location.
> 0 votes

---
Tags: uri
---


title: How do I upgrade using GIT?

text:
# Question
Title: How do I upgrade using GIT?
From time to time, there will be minor and major updates to Drupal core. If the release is designated as a security update, we should apply the update as soon as we can. Otherwise, we may choose to apply the update at any time to receive the bug fixes it contains. There are also major release upgrades; we may want to apply these, so we have all the new and powerful features.

How do I upgrade using GIT?

# Answer
I'd recommend installing and using Drush with GIT instead of only GIT when it comes to security or any other updates. It's really easy to update with drush.

```
drush up

```

will update everything

```
drush up modulename

```

will only update a module of your choosing

```
drush up drupal

```

will only update drupal core.
> 1 votes

---
Tags: version-control
---


# Question
Title: Entity reference field changes not shown in diff?
I installed the Diff module so see the changes to node revisions. Works fine, but when I change an entity reference field the diff of that field is not shown. What could I be missing? From everything I've see the modules should integrate with each other. Diff 7.x-3.2 and Entityreference 7.x-1.1.

# Answer
Problem was that the fields were set to hidden in Mange Display *default* display setting. Set to Label and it works.
> 0 votes

---
Tags: entities, nodes
---


title: Get latest revision vid in views

text:
# Question
Title: Get latest revision vid in views
I'm using the revisioning module to handle the status of nodes. As far as the nodes go, they've been working perfect and the work flow is exactly what I want. However, I'm running into an issue when trying to construct a view.

What I'm able to do so far:

* Create the view
* Set the node type
* Limit it to only nodes that have pending revisions
    + (I get the two nodes with pending revisions (an unpublished rev)
* Get the nid of the node

Where I'm having issues:

* I try to select the vid of the pending revision, but instead I get the vid of the currently published revision.

I'm not sure where to go. I've tried using "Type: Content" and "Type: Content revision" and get the exact same behavior. I've tried playing with Relationships and still get the same behavior, but I don't think a relationship touches what I need.

... This is incredibly irritating because I'm obviously getting the pending nodes that I want, I'm just not getting the vid for what's pending (which is what my filter uses to get those nodes in the first place) and instead getting it for what's published.

I can imagine there might be some headache because it's possible to have multiple pending revisions, in that case, I should see two lines for that one nid since nid and vid /should/ be unique.

# Answer
What I needed doesn't exist. I had to write something with views\_php to get what I needed. What worked was heavily influenced by https://drupal.org/node/1081804.
> -1 votes

# Answer
Instead of views\_php use something like this. Add it as a field - you just need a custom handler to call the revisioning function that returns the latest vid.

```
/*
* Implements hook_views_data_alter().
*/
function MYMODULE_views_data_alter(&$data) {
  $data['node_revision']['latest_revision'] = array(
    'title' => t('Latest revision'),
    'help' => t('Get the latest vid.'),
    'group' => t('Content revision'),
    'real field' => 'nid',
    'field' => array(
      'handler' => 'MYMODULE_field_handler_latest_revision',
      'click sortable' => TRUE,
    ),
  );
}

```

And the handler:

```
/**
 * Provide the latest revision number from the nid field.
 */
class MYMODULE_field_handler_latest_revision extends views_handler_field {

  // Return latest vid as the field value.
  public function render($values) {
    $value = $this->get_value($values);
    return revisioning_get_latest_revision_id($value);
  }
}

```
> 1 votes

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


# Question
Title: Jump to a heading in a view from outside the view on the same page
I have a page with an introductory area and then a view that contains a large number of items grouped by a series of known headings. Kind of like this:

```
_________________________________
Welcome Message and list of headings:
  - Heading 1
  - Heading 2
  - Heading 3
_________________________________
View:
Heading 1:
   - item 1
   - item 2
   ...
Heading 2:
   - item 3
Heading 3:
   - item 4
   - item 5
   - ....

```

and etc.

The page is put together using Panels; there is a custom content pane with the welcome message and list of links and the lower content is a view inside a pane.

I want the user to be able to click on a link in the top panel and be taken to a particular heading in the view below. I can't seem to think of a sensible way to do this without reworking how I do the entire view/page.

Any suggestions?

# Answer
You should be able to do this using standard HTML anchors, just rewrite the output of the Headings to include a simple anchor tag and in your top panel (aka table of contents) make the links go to their corresponding anchor tags.
> 1 votes

---
Tags: 7, views, panels
---


# Question
Title: How to expand/collapse text in WYSIWYG w/CKEditor
In full nodes of a certain content type (using panels), I would like to display a text summary with a read more link to display full text, then a show less link to collapse. I had smart trim enabled which allowed a read more link, but the page simply reloaded to the trimmed summary after clicking the link. I am using WYSIWYG with CKEditor.

So far I have tried jquery expander and expanding formatter. Jquery expander didn't have any affect on the full text, expanding formatter displayed an ellipsis at the designated trim spot, followed by the full text, and a read more button after the full text. So, essentially neither worked.

I tried js injector, plus this code and the full text showed -- no effect.

Is there something about WYSIWYG or CKeditor that prevents this function? Suggestions?

# Answer
This worked for me

### JS Injector

```
(function ($) {

$(document).ready(function() {
    // Configure/customize these variables.
    var showChar = 100; // How many characters are shown by default
    var ellipsestext = "...";
    var moretext = "Show more >";
    var lesstext = "Show less";

    $('.more').each(function() {
        var content = $(this).html();

        if(content.length > showChar) {

            var c = content.substr(0, showChar);
            var h = content.substr(showChar, content.length - showChar);

            var html = c + '<span class="moreellipses">' + ellipsestext+ ' </span><span class="morecontent"><span>' + h + '</span>  <a href="" class="morelink">' + moretext + '</a></span>';

            $(this).html(html);
        }

    });

    $(".morelink").click(function(){
        if($(this).hasClass("less")) {
            $(this).removeClass("less");
            $(this).html(moretext);
        } else {
            $(this).addClass("less");
            $(this).html(lesstext);
        }
        $(this).parent().prev().toggle();
        $(this).prev().toggle();
        return false;
    });
$(".morecontent span").css("display", "none");
$(".morelink").css("display", "block");
})
})(jQuery);

```

## CKeditor

```
    <span class="more">
      Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
    </span>
    <br><br>
    <div class="more">
      Morbi placerat imperdiet risus quis blandit. Ut lobortis elit luctus, feugiat erat vitae, interdum diam. Nam sit amet arcu vitae justo lacinia ultricies nec eget tellus. Curabitur id sapien massa. In hac <a href="#">habitasse</a> platea dictumst. Integer tristique leo consectetur libero pretium pretium. Nunc sed mauris magna. Praesent varius purus id turpis iaculis iaculis. Nulla <em>convallis magna nunc</em>, id rhoncus massa ornare in. Donec et feugiat sem, ac rhoncus mauris. Quisque eget tempor massa.
    </div>

```
> 2 votes

---
Tags: wysiwyg
---


# Question
Title: How to pass custom values from buildForm() to submitForm()
My `buildForm()` method queries the database and returns data which is used to calculate default values for the form. How can I use these values in `submitForm()` without querying the database again?

# Answer
> 5 votes
Typically, the `$form_state` object can be used to stash that data. `$form_state->getStorage()` references a simple array that you can put whatever you like inside, which you can then retrieve in `submitForm()` the same way.

You can store values in `buildForm` function as follows

```
$form_state->set('variable_name', $value);

```

Inside `submitForm` function, you can retrieve this as

```
$value = $form_state->get('variable_name');

```

`variable_name` can be any name

---
Tags: 8, forms
---


title: Template for Views PDF

text:
# Question
Title: Template for Views PDF
I want to build a PDF with fields of a node. I installed Views PDF. Now I try to create a node tpl file. But Views PDF doesn't use my template.

How can I create a template, that is used by Views PDF?

thanks :)

# Answer
You don't need any template files. All you need to do is to create a pdf document with d design u want, then include it in the template section in your views setup
> 1 votes

---
Tags: files
---


title: user-register.tpl.php javascript errors

text:
# Question
Title: user-register.tpl.php javascript errors
I've got a custom register template working by adding this in my template:

```
// Customize User Login
function THEME_theme(&$existing, $type, $theme, $path){
$hooks = array();
// Make user-register.tpl.php available
 $hooks['user_register_form'] = array (
 'render element' => 'form',
 'path' => drupal_get_path('theme','THEME') .'/templates/user',
 'template' => 'user-register',
 'preprocess functions' => array('THEME_preprocess_user_register_form'),
);
return $hooks;
}
function THEME_preprocess_user_register_form(&$vars) {
$args = func_get_args();
array_shift($args);
$form_state['build_info']['args'] = $args;
$vars['form'] = drupal_build_form('user_register_form', $form_state['build_info']['args']);
}

```

The page works, but returns a javascript error.

Uncaught TypeError: Cannot read property 'confirmTitle' of undefined (user.js line 19)

Also, no validation errors are displayed if I try and submit the form with errors.

The template itself looks like this:

```
<fieldset>
<div class="left">
    <?php print render($form['field_first_name']); ?>
    <?php print render($form['field_last_name']); ?>
    <?php print render($form['field_chinese_name']); ?>
</div>
<div class="right">
    <?php print render($form['account']['mail']); ?>
    <?php print render($form['field_position']); ?>
    <?php print render($form['field_company']); ?>
</div>
</fieldset>

<fieldset>
    <?php print render($form['account']['pass']['pass1']); ?>
    <?php print render($form['account']['pass']['pass2']); ?>
</fieldset>

<fieldset class="last">
    <?php print render($form['field_keep_me_updated_with_news_']); ?>
    <?php print render($form['field_i_have_read_and_agree_to_t']); ?>
</fieldset>

<?php
    print drupal_render($form['actions']);
    print drupal_render($form['form_build_id']);
    print drupal_render($form['form_id']);
    print drupal_render_children($form);

```

What am I missing?

EDIT:

line 9 of user.js: var translate = settings.password;

settings.password is undefined. Any ideas?

---

I removed these sections and it works:

```
$args = func_get_args();
array_shift($args);
$form_state['build_info']['args'] = $args;
$vars['form'] = drupal_build_form('user_register_form', $form_state['build_info']['args']);

```

Any idea what these parts were supposed to do anyway?

# Answer
this worked for me - modifying line 9 of user.js to add a fallback assignment.

```
var translate = settings.password || [];

```
> 0 votes

# Answer
Use this patch to handle it #patch\_link
> 0 votes

---
Tags: theming, users
---


# Question
Title: Is there any way to sort by Image Quality?
The idea is to sort Images in views from lowest to the highest quality (not only size).

**Ex:**

Image A = 640x480 100ko (blurred darkened)

Image B = 480x320 50ko (detailed)

Sort

1 - Image B

2 - Image A

# Answer
> 2 votes
The only way that I see is calculate image quality when it's saving and use it later. How to do it:

1. Extend your file entity via module File entity
2. Add special field to store value for image quality.
3. Save value of quality into this field each time when file is saving. For example via hook\_entity\_presave
4. Sort by this field in your views

How to calculate image quality? Here is good example but you can use your own approach to do it.

P.S. Yes it looks a little tricky but I don't think that it's possible to do it easier. But if it's possible I'll be happy to hear it.

# Answer
> 1 votes
The easiest, but most time consuming, would be to create tags via taxonomy.

1. Create a taxonomy reference field on your image entity using the File entity module
2. Create taxonomies that contain the standardized image quality tags you would like to be able to sort by ex. blurred, darkened, detailed, etc
3. When uploading the file, tag it with the selected taxonomy
4. To simplify the tagging process use the Chosen module for selection.

Views supports taxonomy filtering and sorting really well. The reason this is a lot of work is it will require manual tagging.

---
Tags: 7, views, media
---


# Question
Title: Trigger table update when changes are made inside of baseFieldDefinitions
I have a entity that has allready been enabled and the baseFieldDefinitions have created the fields in the database. But now i want to add a single field, and the obvious solution in dev is just to uninstall --\> reinstall. But if the site is in production there must be a way to run a retrigger of that method? I have tried to clear the cache and updateing via the update.php file, but to no prevail. Ive allso tried to just create a entity with the new field in it, to see if it behaved like a ordinary ORM system where the initial creation of a entity has update triggers tied to it, but that allso did not work.

So im at a lost, i read through the drupal entity api, and a guy asked the exact same question but with no answer, so im thinking that it would be nice to put the answer here whatever it might be :)

My entity declaration(with the new field "processed" added):

```
 @ContentEntityType(
 *   id = "person",
 *   label = @Translation("A entity to contain contact information for future customers"),
 *   handlers = {
 *     "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
 *     "list_builder" = "Drupal\person\PersonListBuilder",
 *     "views_data" = "Drupal\person\Entity\PersonViewsData",
 *     "form" = {
 *       "default" = "Drupal\person\Form\PersonForm",
 *       "add" = "Drupal\person\Form\PersonForm",
 *       "edit" = "Drupal\person\Form\PersonForm",
 *       "delete" = "Drupal\person\Form\PersonDeleteForm",
 *     },
 *     "access" = "Drupal\person\PersonAccessControlHandler",
 *   },
 *   base_table = "person",
 *   admin_permission = "administer Person entities",
 *   entity_keys = {
 *     "id" = "id",
 *     "label" = "name",
 *     "uuid" = "uuid",
 *     "uid" = "user_id",
 *     "email" = "email",
 *     "phone" = "phone",
 *     "description" = "description",
 *     "langcode" = "langcode",
 *     "processed" = "processed"
 *   },
 *   links = {
 *     "canonical" = "/admin/person/{person}",
 *     "edit-form" = "/admin/person/{person}/edit",
 *     "delete-form" = "/admin/person/{person}/delete"
 *   },
 *   field_ui_base_route = "person.settings"
 * )
 */
class Person extends ContentEntityBase implements PersonInterface
{

```

My baseFieldDefinitions method inside the entity looks like this:

```
 /**
     * {@inheritdoc}
     */
    public static function baseFieldDefinitions(EntityTypeInterface $entity_type)
    {
        $fields['id'] = BaseFieldDefinition::create('integer')
            ->setLabel(t('ID'))
            ->setDescription(t('The ID of the A entity to contain contact information for future customers entity.'))
            ->setReadOnly(TRUE);
        $fields['uuid'] = BaseFieldDefinition::create('uuid')
            ->setLabel(t('UUID'))
            ->setDescription(t('The UUID of the A entity to contain contact information for future customers entity.'))
            ->setReadOnly(TRUE);

        $fields['user_id'] = BaseFieldDefinition::create('entity_reference')
            ->setLabel(t('Authored by'))
            ->setDescription(t('The user ID of author of the A entity to contain contact information for future customers entity.'))
            ->setRevisionable(TRUE)
            ->setSetting('target_type', 'user')
            ->setSetting('handler', 'default')
            ->setDefaultValueCallback('Drupal\node\Entity\Node::getCurrentUserId')
            ->setTranslatable(TRUE)
            ->setDisplayOptions('view', array(
                'label' => 'hidden',
                'type' => 'author',
                'weight' => 0,
            ))
            ->setDisplayOptions('form', array(
                'type' => 'entity_reference_autocomplete',
                'weight' => 5,
                'settings' => array(
                    'match_operator' => 'CONTAINS',
                    'size' => '60',
                    'autocomplete_type' => 'tags',
                    'placeholder' => '',
                ),
            ))
            ->setDisplayConfigurable('form', TRUE)
            ->setDisplayConfigurable('view', TRUE);

        $fields['name'] = BaseFieldDefinition::create('string')
            ->setLabel(t('Name'))
            ->setDescription(t('The name of the A entity to contain contact information for future customers entity.'))
            ->setSettings(array(
                'max_length' => 50,
                'text_processing' => 0,
            ))
            ->setDefaultValue('')
            ->setDisplayOptions('view', array(
                'label' => 'above',
                'type' => 'string',
                'weight' => -4,
            ))
            ->setDisplayOptions('form', array(
                'type' => 'string_textfield',
                'weight' => -4,
            ))
            ->setDisplayConfigurable('form', TRUE)
            ->setDisplayConfigurable('view', TRUE);

        $fields['status'] = BaseFieldDefinition::create('boolean')
            ->setLabel(t('Publishing status'))
            ->setDescription(t('A boolean indicating whether the A entity to contain contact information for future customers is published.'))
            ->setDefaultValue(TRUE);

        $fields['processed'] = BaseFieldDefinition::create('boolean')
            ->setLabel(t('Processed'))
            ->setDescription(t('A boolean describeing if a customer has been contacted or not.'))
            ->setDefaultValue(FALSE);

        $fields['langcode'] = BaseFieldDefinition::create('language')
            ->setLabel(t('Language code'))
            ->setDescription(t('The language code for the A entity to contain contact information for future customers entity.'));

        $fields['created'] = BaseFieldDefinition::create('created')
            ->setLabel(t('Created'))
            ->setDescription(t('The time that the entity was created.'));

        $fields['changed'] = BaseFieldDefinition::create('changed')
            ->setLabel(t('Changed'))
            ->setDescription(t('The time that the entity was last edited.'));

        $fields['phone'] = BaseFieldDefinition::create('string')
            ->setLabel(t('Phone'))
            ->setDescription(t('The phonenumber of future customers'))
            ->setDefaultValue('');

        $fields['email'] = BaseFieldDefinition::create('string')
            ->setLabel(t('Email'))
            ->setDescription(t('The email of future customers'))
            ->setDefaultValue('');

        $fields['description'] = BaseFieldDefinition::create('string')
            ->setLabel(t('Description'))
            ->setDescription(t('A description of whatever task the future customer wants to be contacted about'))
            ->setDefaultValue('');
        return $fields;
    }

```

# Answer
See node\_update\_8001():

```
/**
 * Add 'revision_translation_affected' field to 'node' entities.
 */
function node_update_8001() {
  // Install the definition that this field had in
  // \Drupal\node\Entity\Node::baseFieldDefinitions()
  // at the time that this update function was written. If/when code is
  // deployed that changes that definition, the corresponding module must
  // implement an update function that invokes
  // \Drupal::entityDefinitionUpdateManager()->updateFieldStorageDefinition()
  // with the new definition.
  $storage_definition = BaseFieldDefinition::create('boolean')
      ->setLabel(t('Revision translation affected'))
      ->setDescription(t('Indicates if the last edit of a translation belongs to current revision.'))
      ->setReadOnly(TRUE)
      ->setRevisionable(TRUE)
      ->setTranslatable(TRUE);

  \Drupal::entityDefinitionUpdateManager()
    ->installFieldStorageDefinition('revision_translation_affected', 'node', 'node', $storage_definition);
}

```
> 2 votes

---
Tags: entities, 8
---


title: Where are the DB settings located?

text:
# Question
Title: Where are the DB settings located?
i've been learning Drupal 7 using Acquia DevDesktop and i have several sandbox type website running on my laptop but now i'm trying to access the databases from the command line. but in the settings.php almost the only that's not comment out are at the bottom, where it makes reference to inc.'s like this.

```
if (isset($_SERVER['DEVDESKTOP_DRUPAL_SETTINGS_DIR']) &&
file_exists($_SERVER['DEVDESKTOP_DRUPAL_SETTINGS_DIR'] .          '/loc_rmywebsite_local.inc'))
  require($_SERVER['DEVDESKTOP_DRUPAL_SETTINGS_DIR'] .     '/loc_mywebsite_local.inc');

```

but then when i do a search for these inc files locally on my laptop, nothing comes up, as if they don't exist. so One, where are these files? and two, find where the DB settings are for these local sites so i can start learning how use the command line, or maybe Drush.

yes, i should probably have written down these setting but didn't.

# Answer
> 4 votes
You can find DB Settings of Acquia DevDesktop locally at following location

> C:\Users\YOUR\_USER\_NAME\\.acquia\DevDesktop\DrupalSettings\loc\_mywebsite\_local.inc

In above path Replace YOUR\_USER\_NAME with apropriate user name that you login on system. This path for Windows 7.

# Answer
> 4 votes
For Mac, open Terminal. By default it opens in your user home directory (/Users/"username").

The settings you are looking for are on a file in a hidden ".acquia" folder inside your user home directory.

On a freshly open Terminal window (meaning, from your user home directory, unless you changed its settings), just do the following to list the settings files for the Acquia Dev Desktop environments on your local computer:

```
ls .acquia/DevDesktop/DrupalSettings

```

Once you see the one you want, you can display its content using the cat command, for example if the file is named cld\_devcloud\_myveryownshinydrupal\_dev\_default.inc, then just type:

```
cat .acquia/DevDesktop/DrupalSettings/cld_devcloud_civila7_dev_default.inc

```

In any case, the full path you are looking for is:

```
/Users/your-own-mac-username/.acquia/DevDesktop/DrupalSettings/

```

Hope this helps. It took me a while to find it too and Acquia documentation makes no mention at all (or at least none that I could find).

# Answer
> 2 votes
Couple of things.

For Windows, the DB settings are in the dir Rupesh listed. Very similar on a Mac as well:

/Users/YOUR\_USER\_NAME/.acquia/DevDesktop/DrupalSettings

There is a file in this directory for each site you have installed on Dev Desktop. Do not edit this file! However you can use this file to figure out where you database is, the name, etc.

While you can use drush to do a database backup, you can also use Dev Desktop to export a site archive which includes a sql file.

---
Tags: database, acquia-dev-desktop
---


# Question
Title: How do I find "where-used" / many-to-one related entities?
A field in my *Content Type A* references a *Content Type B*.

I'd like to find, in each instance of *Content Type B*, a list of all the *A*s that reference it at a particular point in time.

\[Update\]: I made the question less ambiguous in the light of the answer I found with help from others here.

# Answer
> 0 votes
This code is in my `agenda.module`. The *where-used* relation is used as follows in the form validation handler that is called when the user clicks the *Delete* button on the delete confirmation form:

The *Agenda* Node cannot be deleted if there are any *Meeting* Nodes that refer to it.

```
use Drupal\Core\Form\FormStateInterface;

function agenda_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  switch ($form_id) {
    // ...
    case "node_agenda_delete_form":
      $form['#validate'][] = '_agenda_delete_validation';
      break;
    // ...
  }
}

function _agenda_delete_validation(&$form, FormStateInterface $form_state) {
  $agenda_node = $form_state->getFormObject()->getEntity();
  $agenda_name = $agenda_node->getTitle();
  $agenda_node_id = $agenda_node->id();
  $query = \Drupal::entityQuery('node')
    ->condition('type', 'meeting')
    ->condition('field_agenda', $agenda_node_id);
  $nids = $query->execute();
  $count_nids = count($nids);
  if ($count_nids > 0) {
    $msg_stem = ($count_nids == 1) ? 'There is one Meeting that references "' : 'There are '.$count_nids.' Meetings that reference "';
    $form_state->setError($form, $msg_stem.$agenda_name.'". It cannot be deleted yet.' );
  }
}

```

# Answer
> 1 votes
If you want a quick solution in code, you can use the same way as in drupal 7:

Add a field (configurable in view modes):

hook\_entity\_extra\_field\_info

Put the code for the field in here:

hook\_ENTITY\_TYPE\_view

Use this code:

How to check if an article is referenced from a collection?

# Answer
> 1 votes
In D7, Entity Views Attachment was the most popular solution for this. It has no D8 port yet however.

D8 modules which offer this functionality include:

* Display Suite. It enables you to add a view as a dynamic field; that view could use a contextual filter to focus its content on the current node URL.
* Viewfield, as you suggested. You use a token to specify a default view, and choose to "force the default" to prevent content editors from changing the selected view.
* Display fields, an interesting new D8 module. It allows you to place views as fields on a node, and is meant to allow contextual arguments, but I've not been able to set this up properly (see the issue)

---
Tags: 8, entities
---


title: Multi-site clear cache

text:
# Question
Title: Multi-site clear cache
We want to clear the multiple sites cache from one site, currently we have multi-site configuration. Is there any module?

# Answer
> 3 votes
You can easily configure drush aliases for this.

Having properly configured drush brings so many benefits, especially if you work with multiple environnements for your sites.

As an example, say you have aliases defined for example.com as follows:,

@example.local, @example.staging, @example.prod

See a status of all 3 sites:

```
drush @example st

```

Clear the cache on local env:

```
drush @example.local cc all

```

Dump production database and load it into local:

```
drush @example.prod sqldump | drush @example.dev sqlc

```

Anyways, you get the idea. Packing your drush.rc file with your project in git (shove it in /sites/all/drush/drushrc.php ) will allow anyone working on those projects to have those aliases fully defined on every code checkout. Happy codings, cheers!

---
Tags: multi-sites
---


# Question
Title: How to extends %module_x/templates/xyz.html.twig?
My module has a template which would like to extend another module's template. Is there any shortcut like we have in Symfony2?

```
{% extends 'path_to_module_x:templates/template-x.html.twig' %}

```

# Answer
> 1 votes
An updated version of @Cottser answers is going to be like this....

```
 {% extends "node.html.twig" %}

```

This is been supported since this issue is been solve - https://www.drupal.org/node/2291449

# Answer
> 4 votes
As of https://drupal.org/node/2143557 (committed January 24, 2014) you can now do this:

```
{% extends "@node/node.html.twig" %}

```

Note that the 'templates' directory is automatically included.

---
Tags: 8, theming
---


# Question
Title: Turn off Drupal caching without Access to admin panel
I'm using Drupal 7 on WAMPP , Windows 7

Background: Drupal on my local box is copy of working project, but this local version I can not login like admin , because it doesn't store session. It doesn't give out any PHP Error.

So I guess I have to turn off cache to find out , is there any PHP Error appearing.

Read that there is such thing as `drush` , but is it possible to use from Windows ?

But the main question , is how to stop caching on Windows 7 without Admin access !?

# Answer
Yes, you can run Drush under Microsoft Windows if you use the Drush Windows Installer. Drush will allow you to turn of caching with the command:

```
drush en cache_disable --yes

```

It is not *easy* to set up the Drush Windows Installer. As an alternative, you may consider explicitly set variables in your `settings.php` to turn of various caches. Note that when set, these values will be locked to whatever is set in the file, and cannot be changed through the admin interface (so remove them when you're done debugging).

To disable page, JS, and CSS caching, set cache, preprocess\_js, and preprocess\_css all to '0' in the `$conf` array:

```
$conf = array(
  'cache' => '0',
  'preprocess_css' => '0',
  'preprocess_js' => '0',
);

```

If you set other values by means of the `$conf` array, add these fields, do that, rather than replacing the entire array.
> 5 votes

# Answer
If you look at this link you can see disable cache by puting below line in `settings.php` files

```
  $conf['display_cache_disable'] = TRUE;

```
> 0 votes

---
Tags: drush, caching
---


# Question
Title: Is there a drush script to disable all caches?
I mean all of the caching options under admin/settings/performance. I frequently use drush sql-sync to keep my development copy up-to-date with the server. However, the server must have all of the caches turned on, obviously.

So I wonder: must I visit admin/settings/performance every time I update my db? Or is there a Drush script for that?

# Answer
> 6 votes
https://drupal.org/node/797346 for D7. For D6, https://drupal.org/project/cache\_disable but it breaks the form cache. One needs to patch it to fall to DB cache for form caching. And probably update status cache too.

# Answer
> 18 votes
You need to set several variables to turn off caching on your dev site...

```
 drush vset cache 0
 drush vset preprocess_css 0
 drush vset preprocess_js 0
 drush vset page_cache_maximum_age 0
 drush vset views_skip_cache TRUE

```

It's even easier if you have conditional config in your settings.php file. Then you can refresh the DB and the changes will stick!

`$conf['cache'] = 0; // Page cache
$conf['page_cache_maximum_age'] = 0; // External cache TTL
$conf['preprocess_css'] = FALSE; // Optimize css
$conf['preprocess_js'] = FALSE; // Optimize javascript
$conf['views_skip_cache'] = TRUE; // Views caching`

... though if you just turn off various caching through the admin UI and clear cache once then you can theme away without turning off the rest... since script it less likely to change.

# Answer
> 11 votes
You can use your settings.php file to explicitly set variables to override your database settings. The values will be locked to whatever is set in the file, and cannot be changed through the admin interface.
At the end of the default file is a section which starts:

```
/**
 * Variable overrides:
 *
 * To override specific entries in the 'variable' table for this site,
 * set them here. You usually don't need to use this feature. This is
 * useful in a configuration file for a vhost or directory, rather than
 * the default settings.php. Any configuration setting from the 'variable'
 * table can be given a new value. Note that any values you provide in
 * these variable overrides will not be modifiable from the Drupal
 * administration interface.
 *
 * Remove the leading hash signs to enable.
 */
# $conf = array(
#   'site_name' => 'My Drupal site',
#   'theme_default' => 'minnelli',
#   'anonymous' => 'Visitor',

```

So to disable page, JS, and CSS caching, set `cache`, `preprocess_js`, and `preprocess_css` all to `'0'`

```
$conf = array(
  'cache' => '0',
  'preprocess_css' => '0',
  'preprocess_js' => '0',
);

```

The closing parenthesis for the array declaration is the last line of the default file, after a few more comment blocks, so make sure to uncomment it there rather than adding a new one. Also make sure that you don't have another `$conf` declaration that will conflict.

# Answer
> 2 votes
You could always use a drush aliases file on your dev server and set it up to skip the cache tables when you run sql-sync. The following would create aliases for your local dev server and your remote live server:

```
$aliases['dev'] = array(
    'root' => '/var/www/devroot',
);

$aliases['live'] = array(
    'root' => '/var/www/liveroot',
    'remote-host' => 'www.mysite.com',
    'remote-user' => 'exampleuser',
    'command-specific' => array (
       'sql-sync' => array (
         'skip-tables-list' => 'cache,cache_menu',
       ),
    ),
);

```

If you saved that under your home directory at:

```
~/.drush/mysite.aliases.drushrc.php

```

then you can call your sql-sync command like so:

```
drush sql-sync @mysite.live @mysite.dev

```

and it should skip the cache tables (obviously I only listed 2 there, but you could put anything in there, I even add watchdog in).

For more info on aliases and all the various options, check out the example file in your drush install at drush/examples/example.aliases.drushrc.php

As a last note for anyone who trys to use sql-sync, I had authentication issues when I first ran it, so if someone attempts this and gets errors about public/private keys then do the following:

```
drush dl drush_extras
drush pushkey @mysite.live
drush @mysite.live status

```

The pushkey command from drush\_extras creates a private/public key pair and pushes the public key to the live server. The last command is just to check that it worked.

# Answer
> 1 votes
I have written a drush command which enables / disables all the following options:

```
cache
cache_lifetime
page_cache_maximum_age
preprocess_css
preprocess_js

```

Examples and code can be found here: http://ourlife01.blogspot.gr/2015/05/drush-command-to-enabledisable-cache.html

So in order to disable all of the above options, you just have to run:

```
drush cache-disable

```

The command:

```
drush cache-enable

```

is the same as setting the variables to the values:

```
cache: TRUE
cache_lifetime: 1 minute
page_cache_maximum_age: 1 hour
preprocess_css: TRUE
preprocess_js: TRUE

```

# Answer
> 1 votes
Also you can disable cache by below line, put it in `settings.php` files

```
$conf['display_cache_disable'] = TRUE;

```

---
Tags: drush
---


# Question
Title: how to set cron correctly on a shared server
I set the following command for cron on a shared server.

```
/usr/bin/php5.3 home/public_html/cron.php

```

(All the Drupal files are under /public\_html)

This commend seems to be working but I get the following error

```
PHP Warning:  Cannot modify header information - headers already sent by (output started at /home/public_html/sites/default/settings.php:1) in /home/public_html/includes/bootstrap.inc on line 1163
Sorry,  has been banned.

```

Am I missing something?

# Answer
Looks like perhaps you settings.php file has some extra characters outside of the
> 0 votes

---
Tags: 6, cron
---


# Question
Title: How to auto-assign a term based on a combination of terms from three other vocabularies?
This is a very odd scenario, so bear with me:

I'm importing data from a CSV file via the Feeds module to create product reference nodes. There are 3 columns that contain a term (let's call the columns "Code Types"), so naturally, I set up 3 vocabularies for the product reference nodes to use and mapped/imported the Code Type's terms into each. The client had determined long ago that the terms would not make much sense to the customers, so being able to search for products by selecting a combination of terms would not be helpful. To combat this, new user-friendly keywords were added on the client's old site by assigning each a combination of the 3 terms. I'm trying to replicate this for the new site, and it's driving me insane.

I first began by adding the same 3 Code Type vocabularies to a new 4th "Product Keywords" vocabulary (Yes, terms within terms). After no luck with term or entity reference fiddling, EVA, etc., I decided referencing would go smoother if I made the Keywords a content type with the 3 Code Type term reference fields instead of its own vocabulary. I'm still open to either option, though.

What has to happen is that a product reference node is automatically assigned the Keyword term that exactly matches its 3 Code Type term reference fields, and not all Code Type term reference fields have to have a value. Here are some examples:

Product #42 has: CodeType1 = "Red" CodeType2 = "Wheel" CodeType3 = "Hot Dog"

Product #216 has: CodeType1 = \[empty\] CodeType2 = \[empty\] CodeType3 = "Hot Dog"

---

Keyword "Sloth" has: CodeType1 = "Red" CodeType2 = "Wheel" CodeType3 = "Hot Dog"

Keyword "Muffin" has: CodeType1 = \[empty\] CodeType2 = \[empty\] CodeType3 = "Hot Dog"

---

Product #42 needs to have the keyword "Sloth" automatically assigned to it.

Product #216 needs to have the keyword "Muffin" automatically assigned to it.

Sorry for the longwindedness. It's urgent, and I'm edging toward panic mode. Any ideas? Please?

# Answer
> 1 votes
These are some ideas to accomplish this through Drupal (rather than Excel).

You could do this with a combination of custom modules and Rules, or solely with Rules (which might be a bit more laborious). I'm focusing on the version only with Rules. I haven't tested this, so there may be some adjustments needed.

## 1. Create a "Catalog" content type that catalogs all combinations of codetypes

Create a content type that will act as a "catalog of codetypes", containing all possible combinations of codetypes and their unique keyword assigned to each combination. This would take an initial investment of time for someone to enter all combinations. Be sure to enter a special code (like the string "empty") when a codetype is not present in a specific combination.

## 2. Create a View of the "Catalog" content type with three Contextual Filters that filter for a specific combination of the 3 codetypes

(This step needs to be tested and possible tweaked quite a bit). You would need to define the path as `/catalog/%/%/%` to create placeholders for empty codetypes. There would be 3 Contextual Filters for each of the 3 codetype fields in the catalog. Be sure to provide the fixed default value "empty" in the configuration of *When the filter value is not in the URL*. The result of this View would be a single record that contains the specific combination of codetypes.

## 3. Install *View Bulk Operations* and add it to the View

After enabling it, add a VBO field to the View created in step 2. There is no need to select a specific operation. This field will be used to load the single catalog record into Rules later on.

## 4. Create a Rule that reacts to new (imported) Product nodes being saved

This Rule will react to the Products being created through the use of Feeds. Basically it needs to load a list of entity objects from the VBO you created above. Pass the three codetypes as arguments the the View.

## 5. Use the Rule to *Set data value* of the Keyword field in each of the imported Products.

This step may require some tweaking. You will need to bring into scope the Keyword field of the Catalog record provided by the View. That may involve creating a separate Component that has a condition that brings it to scope, or installing Conditional Rules to create an if statement that brings it to scope. Once the Keyword field of the Catalog node is brought into scope, you use its value to assign it to the Keyword field of the imported Product

So, that's it in a nutshell. You could replace several of the steps with code in a custom module, and avoid using VBO and Rules altogether - you would use EntityFieldQuery to load the Catalog node with the three codetypes, and hook\_node\_insert() to react to the Product node being imported/created. There may be alternative hooks in the Feeds API that may make this possible too.

I hope this helps... Let me know if you have questions.

# Answer
> 0 votes
OK, this is what I would do (hoping that I'm understanding the question!). I assume the keywords need to be hard-coded to the product, and not assigned dynamically. Is that right? If so:

I would not bother doing these combinations with Drupal. I would do the combinations with Excel, then import the resulting CSV sheet with Feeds to Drupal.

For example, in the same excel sheet I would have:

1. An area that defines the keywords in rows, each with 5 columns: 1. Codetype1, 2. Codetype2, 3. Codetype3, 4. a **string concatenation** of the 3 codes, and 5. the keyword itself, and then
2. An area with the a row for each product with at least 4 columns each, containing the 3 codetypes, and a concatenation of the 3. Then a formula column for each row that uses =vlookup() to look up the concatenation in the Keyword area, and to insert the appropriate Keyword

See image for clarification. The formula I used is in the Keyword column in the Product area: `=VLOOKUP(E3,$K$3:$L$5, 2,0)` in cell \[F3\] for example.

Once keywords are calculated this way you can copy and paste the Keyword column into a new CVS and import with Feeds. Good luck!

---
Tags: feeds, taxonomy-terms
---


# Question
Title: Strange log message and node not found for anonymous
I have a node found at the teaser of front-end for both admin and anonymous users. However, going to the node details page using anonymous user leads to 404 error while it works fine with admin.

The log message details is strange as shown in the following screen shot:

What is `custom_404_page`? I'm afraid of it is a hacking against the website.

I tried to clear all cache, I disabled XMLsitemap module. I could not able to determine where is the origin of `custom_404_page`.

Also in the log and after clearing it, and the trying to visit this node's details, this is the only log message available. i.e there is no other messages or warnings.

# Answer
Check your custom 404 configuration at `admin/config/system/site-information`.

Also check if this custom configuration is directing users to a Panels page (check `Structure > Panels` or `Structure > Pages` if you have Panels and Page Manager installed). They may be handling different custom 404 pages for different roles. Perhaps the Panel variant that handles the 404 page for anonymous is missing or redirecting to a non-existing page.
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: Add slideshow option to 'link image to' in Views
I have created a View that displays images uploaded on my website as thumbnails and in a grid style. However when I click on an image I would like some slideshow function to show so the user can click 'left' and 'right' to scroll through the images. How can I add this functionality to 'the Link Image to' setting?

# Answer
I assume you already have a Gallery or Slideshow working (otherwise check other modules, e.g. Juicebox). If you want the image to link to a specific path you need to choose the option **Rewrite Results** \> **Output this field as a link**. You can use tokens if you want to change this path dynamically according to other fields in the View.
> 0 votes

---
Tags: 7, media, views
---


# Question
Title: During database updates the schema of any module could be out of date
I try to well understand Update versions API functions. I globally understand the concept, but I have some doubt.

In fact Drupal makes no verification about the N version number use in the name of a simplified function ***\_update\_N\_mymodule\_my\_function()***. N can be what ever we want (even a string) ? More, even the whole name of function can be named in fact e.g "toto()" ? Drupal makes no verification, and names used for functions simplified are just for convenience. Correct ?

# Answer
> 1 votes
No, that is not correct. You cannot use a string as update version for a update hook, or Drupal will not recognize it as update hook.
For the other functions that aren't hook, Drupal doesn't check their name follow a schema, since Drupal is not going to call them. The only non-hook functions Drupal calls are those functions referred in some data structure returned to Drupal, or those functions whose names match a form ID followed by *\_validate* or *\_submit*, which could be used as form validation or submission handlers.

See the code executed from `drupal_get_schema_versions()`, in particular the following one.

```
// Prepare regular expression to match all possible defined hook_update_N().
$regexp = '/^(?P<module>.+)_update_(?P<version>\d+)$/';
$functions = get_defined_functions();
// Narrow this down to functions ending with an integer, since all
// hook_update_N() functions end this way, and there are other
// possible functions which match '_update_'. We use preg_grep() here
// instead of foreaching through all defined functions, since the loop
// through all PHP functions can take significant page execution time
// and this function is called on every administrative page via
// system_requirements().
foreach (preg_grep('/_\d+$/', $functions['user']) as $function) {
  // If this function is a module update function, add it to the list of
  // module updates.
  if (preg_match($regexp, $function, $matches)) {
    $updates[$matches['module']][] = $matches['version'];
  }
}

```

A function name like `mymodule_update_toto()` would not match `/_\d+$/`, so it would be discarded immediately; a function name like `mymodule_test_001()` would not match `/^(?P<module>.+)_update_(?P<version>\d+)$/`, so it would be discarded on the second round.
The same is true for a function name like `_update_N_mymodule_my_function()`: Since it doesn't end with a number, it would be discarded at the first round. `_update_mymodule_my_function_N()` would be discarded on the second round, since `_update_` is no after the module name (so it doesn't match `/^(?P<module>.+)_update_(?P<version>\d+)$/`).

---
Tags: 7, updating
---


# Question
Title: Display particular Image Style for image based on Role of User?
Using ImageCache Actions there are 2 different Image Styles - e.g. S1 and S2.

What needs to happen:

* User A has Role Y and when s/he views a node/user profile should always be presented with S1 images.
* User B has Role Z and when s/he views a node/user profile should always be presented with S2 images.

What are the different ways this can be achieved? All suggestions very welcome.

# Answer
You can use a hook\_preprocess\_image\_style to alter the style name to use:

```
/**
 * Implements hook_preprocess_HOOK for theme image_style.
 */
 function mymodule_preprocess_image_style(&$variables) {
   $style = mymodule_determine_style_to_use($variables);
   $variables['style_name'] = $style;
 }

```

Take care that you do not alter all image styles, but only those you want/need to change, so mymodule\_determine\_style\_to\_use() should e.g have a check on $variables\['style\_name'\] being S1 or S2.
> 1 votes

# Answer
Install and configure Image Style Access module.

> Allows granular access control to images and image style derivatives.This module provides access control for image files. Each access configuration can be set to allow or deny access to images and their derivatives by:
>
> File source (scheme), Base image file location and Image style.
> 0 votes

# Answer
I have learnt that this can be accomplished without code using https://www.drupal.org/project/ffc

Thank you to those who posted answers.
> 0 votes

---
Tags: 7, users, media
---


# Question
Title: How to perform action from form opened in modal?
I have a form where I have a link that opens a modal window with another form(*something like adding a block to a region*).

I would like to perform the action on the `opened/second/modal` form during submission as usual but I also want to tell the current window to close the modal and to hit a specific button(which is ajaxified and it will rebuild the form so the changes made via the second form would be visible in the main form - they are based on the same data source).

Is there a way to achieve this with **ajax command** from the second form?

A good example is View form. When a new window is opened(adding a field, or configuring some part of the View), actions in that window are reflected in the form itself after the window is closed.

# Answer
I recently had to do something similar, and I took a good amount of time to understand how Drupal 8 ajax works. Here are the steps:

**Step 1**: Ajaxify the link to open the modal, this is easy and you've probably done it already.

```
$form['ajaxed_link'] = [
  '#type' => 'link',
  '#title' => $this->t('Click to open the modal'),
  '#url' => Url::fromRoute('route_name', ['route_parameters']),
  '#attributes' => [
    'class' => ['use-ajax'],
    'data-dialog-type' => 'modal',
    'data-dialog-options' => Json::encode([
      'height' => 400,
      'width' => 700
    ]),
  ],

```

**Step 2**: Create the form that will open when the #url is called and create a route for it as well. Remember to make the submit button there ajax too, and specify an ajax submit handler using the `callback` key.

```
$form['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Ajaxed submit button'),
  '#ajax' => [
    'callback' => [$this, 'ajaxSubmit'],
  ]
);

```

**Step 3**: Define a function for the callback and make sure it returns an ajax response with the right commands. The first command closes the modal and the second command invokes the click on the desired button (use the correct jquery-selector).

```
public function ajaxSubmit(array &$form, FormStateInterface $form_state, Request $request) {
  $response = new AjaxResponse();
  $response->addCommand(new CloseModalDialogCommand());
  $response->addCommand(new InvokeCommand('#jquery-selector', 'click'));
  return $response;
}

```

**Take note** that it's a good idea to provide a non-ajax fallback return value from the `ajaxSubmit` callback for clients where JS is disabled. Do this by setting a form redirect in the regular form submit handler.

```
public function submitForm(array &$form, FormStateInterface $form_state) {
  ...
  $form_state->setRedirect('route_to_previous_form');
}

```
> 2 votes

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


# Question
Title: How to change Solution Name display on authorize.net under Transaction Source useing Drupal commerce
I am using Drupal commerce Authorize.Net module for transaction.

When I review Transaction Detail on https://sandbox.authorize.net/ site, it display **Solution Name: Commerce Guys** under **Transaction Source**.

How can I change it with my custom one?

# Answer
> 2 votes
It's unfortunate that Authorize.Net identifies it as "Commerce Guys". It should be identifying the request as coming from "Drupal Commerce", which allows them to monitor adoption by users of the module overall (and justifies their continued investment in our community). I'll follow-up with them immediately to change this so it's actually identifying the solution and not the creator of the solution instead (i.e. Commerce Guys). Changing what appears there is only possible from their end, but I have a contact who should be able to get it done.

---
Tags: commerce, payment-gateways
---


title: Display product variations in table

text:
# Question
Title: Display product variations in table
There is currently a "product page" that contains combobox with the different variation values for that product category, but I'm curious if it's possible to add a table display to the product page to show all variations of that category within a table so a user can see what's available instead of manually drilling into every combobox?

# Answer
> 2 votes
Yes. Use Commerce Add to Cart Extras for this. It gives you the ability to add an add-to-cart checkbox on a Product view so that you can add one or more products to the cart. You can see a demo of that functionality.

# Answer
> 2 votes
1. Create a view with base table "Commerce product. "

1. Add necessary fields. Title, Price, Add to cart form, etc will be essential.
    2. Add Relationship "Commerce Product: Referencing Node".
    3. Add Contextual filter "Content: Nid". This view will list the products referenced by a product display node.
2. Install module Viewfield.
3. Add a view field to the product display content type, and set the view created in the first step as default value. Give `[node:nid]` as argument.
4. Configure the node display as you please.

---
Tags: commerce
---


# Question
Title: change entityform value via function before save
I have an entityform with a field call "IP" (field\_ip is its machine name). Now I need to set a value before that the entityform is saved. I have thinked to use hook\_entity\_presave() in this way:

```
function mymodule_entity_presave($entity, $type) {
      if ($type == 'entityform') {
        if ($entity->is_new === true || 1==1) {
          $entity->field_ip = array('LANGUAGE_NONE' => array(0 => array('value' => $_SERVER["REMOTE_ADDR"],'format' => '','safe_value' => $_SERVER["REMOTE_ADDR"])));
          $entity->original->field_ip = $entity->field_ip;   //Try this, too.
        };
      }
    }

```

(1==1 is only for test/debug).

Via "devel" module I can see that the new value of field\_ip is correctly set, but when I see the new version of the entityform entry (after the save action) I see the default value of that field and not my new value. And infact if I re-edit the same entyform (id) I see the old value and not the new one. Where is my error ?

# Answer
OK I now see what the problem is. LANGUAGE\_NONE should not have quotes around it. It's a constant. Been there, done that. :)
> 1 votes

---
Tags: entities
---


title: How to change front page title?

text:
# Question
Title: How to change front page title?
The front page title in the menu is Home or Startseite in german. I would like to give it another name. How can I do this?

The question is asked multiple times over the internet (fore example here) but no clear answer... Thank you

# Answer
Just deactivate the predefined menu link and add a new one - use

```
<front>

```

as path.

In Drupal 7 and 8 go to

```
Home > Administration > Structure > Menus > Main menu > Add link

```

Your German version will say something like

```
Startseite > Verwaltung > Struktur > Menüs > Hauptmenü > Hinzufügen

```

Drupal 7

See tooltip for details (using Rubik Theme)

Drupal 8 (German version)
> 2 votes

---
Tags: 7
---


# Question
Title: Why can't I find any pages after migrating a site?
I need to migrate a drupal site from one host to another. I didn't create the original. I tried using "Backup & Migrate", and I also tried to export the sql database in phpmyadmin from old site, import into new site, and move the file manually with ftp. My new host is GoDaddy. I can change that if GoDaddy causes issues!

Here is the problem, The theme used in the old site appears as an option, I can choose it, and the site works, but no content is there at all. All the modules show up in the new environment, still no content. I go to search for content, still no content. I can't find any pages anywhere!!!

Any help?

# Answer
So, the usual way to do this is like this.

1. dump all caches and back up the database
2. clean drupal install on your new server
3. move the db to your new server
4. configure proper db user on new server
5. copy the sites folder to the new server
6. make sure settings.php is correct for new server config
7. run update.php

It's not clear from your description exactly what's happened, but I would try it again. From what you describe, it doesn't sound like you followed all the steps for a normal site migration, so you need to make sure all the stuff drupal needs is there. I've also had some issues with folder permissions when moving stuff to Godaddy, so you can look at that too.
> 2 votes

# Answer
OK, I fixed it!!!! I'm really hoping this helps someone else at some point.

Detailed problem:

I was migrating a drupal site from a private host to GoDaddy subdomain host to test the files and sql db before going to live environment.

Drupal site migrated and everything looks right but no content is listed. No pages, no media, nothing. The proper theme was available as an option, but not selected.

in the settings.php file, the prefix that godaddy installed for me was "drup\_", but my imported database tables didn't have "drup\_" as a prefix.

Fix:

nizz0k was very helpful in pointing out that I need to run update.php. I had already tried that, but his comment about godaddy not allowing enough ram gave me the idea to increase the ammount of ram from godaddy. The error I was getting before increasing the ram, had to do with "not enough ram or exceeding available ram" something like that. As soon as i increased the resource level with godaddy, the update script worked.

So, to wrap it up, if you are hosting with godaddy, beware of the prefix.

1. I had godaddy install the drupal app for me in the subdomain
2. imported the sql db from my old host
3. imported the files using ftp
4. edited the settings.php file to get rid of the "drup\_" prefix that godaddy had
5. go to site.com/q=user to log into the site and have permissions
6. go to site.com/update.php to update things

That's what worked for me. I'm really hoping this helps someone out. I was looking for something about this for more than 5 days before I posted the question.

Again, thank you so much for this website for hosting the forum, and most certainly thanks to nizz0k for the prompt response and excellent idea's!!
> 1 votes

---
Tags: backups, migrations
---


# Question
Title: Adding custom form to form_alter -- help please
I've been trying for awhile to add a custom form to a custom module so as to make it show in drupal profile Edit page. Using the normal $form\['submit'\] messes up the other forms in the page, so tried to use $form\['#submit'\]\[\] and append the second submit handler, but still no luck. Hoping someone can see what i am doing wrong.

Here is the code i have so far:

```
function custom_module_form_alter(&$form, &$form_state, $form_id) {
 if ($form_id == 'user_profile_form' && user_access('delete mods', $form['#user'])) {

$modlist = getcurrentmods(); // this function returns an array of usernames

$form['modlist']['mods'] = array(
'#type'=>'select',
'#options' => $modlist,
'#multiple' => false,
'#weight' => 30,
'#size' => 10,
'#id' => 'modlist',
'#prefix' => '<div id="dropdown-modlist">',
'#suffix' => '</div>',
 );

$form['#submit'][] = array(
'#type' => 'submit',
'#value' => t('Delete'),
'#submit' => array('_modlist_delete_callback'),
'#weight' => 32,
'#attributes' => array(
    'class' => array('submit-inline'),
),
'#ajax' => array('callback' => '_modlist_delete_callback',
'wrapper' => 'dropdown-modlist',
'effect' => 'fade',
'method' => 'replace',
  ),
 );

  }
}

```

The dropdown with the user list shows up fine, however the submit button doesn't.

# Answer
> 0 votes
Anything with a # preceding it isn't an element, it's a property. Properties are not rendered.

To fix, just give your submit button a unique key without the #, e.g.

```
$form['foo_submit'] = array(
  '#type' => 'submit',
  ...
);

```

---
Tags: forms
---


# Question
Title: Author Fields into a content type template
I'm trying to load some of the information from the author into a **node--article.html.twig**. So I can provide some information like bio, social media,etc.

Similar to this...

I can easily get the `author_name` and the `author_picture` because these two are given by the template. I added extra field at `admin/config/people/accounts/fields` in this case the only extra field is `field_bio`

I try to use the **include** to add this user field into.

**node--article.html.twig**

```
<h4>{{ author_name }}</h4>
<p>{% include('field--user--field-bio--user.html.twig') %}</p>

```

This what I have on the field template - **field--user--field-bio--user.html.twig**

```
<span{{ attributes }}>
  {%- for item in items -%}
      {{ item.content }}
  {%- endfor -%}
</span>

<p>Hello</p>

```

The word "Hello" is been display on the **node--article.html.twig**; however, the `item.content` which is my field information is not been load. =(

I also try to dig up into the user variables by using `{{ kint() }}` to see if there is this information and I did not find it either.

I have seen some example with a module, which I have avoid them because this is for a contrib theme and I do not want to have any module dependency. I have done this many times with DS but I do not want to use any extra module.

So I have couple questions...

* Should I use **include** for this use case or not ?
    + If I have too, what I'm doing wrong ? Why the `item.content` is not been load ?
    + If I should not use it in this use case, what should I do instead ?

# Answer
> Should I use include for this use case or not ?

This is not possible, you can't mix different templates like node and field because they have different variables.

> If I have too, what I'm doing wrong ? Why the item.content is not been load ?

item.content is only loaded in field, not in node template.

> If I should not use it in this use case, what should I do instead ?

You should define the user field you need in preprocess, examples for the two fields already defined:

```
function template_preprocess_node(&$variables) {
  $variables['author_name'] = drupal_render($variables['elements']['uid']);
  $variables['author_picture'] = user_view($node->getOwner(), 'compact');

```

A basic example to use this in your own hook:

```
function mytheme_preprocess_node(&$variables) {
  $node = $variables['node'];
  $variables['user_field1'] = $node->getOwner()->field_field1->value;

```

And in twig

```
{{ user_field1 }}

```
> 2 votes

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


title: Prevent form rebuild on image upload

text:
# Question
Title: Prevent form rebuild on image upload
I have content type Gellery with two fields. Image (Multiple) Game Name (Entity Reference)

I am setting Game Name in hook\_form\_alter. Lets say it is set to "Game 001". When image is uploaded, it actually resets the form, so the changes made to field "Game Name" donot apply when submit the form.

How to prevent form to be rebuilt on uploading image. I guess something do to with $form\_state

```
if ($form_id == 'game_gallery_node_form') {
  $form['field_boardgame']['und'][0]['target_id']['#default_value'] = 'game (41)';
}

```

# Answer
I've done some tests using an Entity Reference field, and setting its default value in a hook\_form\_alter implementation. Everything is working fine - when I upload a single or multiple image files, the default value that I set in the hook for the Entity Reference field is preserved, and is saved fine when I press Save.

Please notice the way I'm setting the default value in my implementation of hook\_form\_alter(). This is different from what you have:

`$form['field_reference_to_page'][LANGUAGE_NONE]['#default_value'] = 'trip (189)';`

(My field is called `field_reference_to_page`. In your case, you 'll need to replace with `field_boardgame`). **Notice that the arrays are different from what you have.** Basically there is no `[0]` or `['target_id']`. The value `'trip (189)` is the title of the node and the node ID that this field is referencing. I made sure that the node really existed, and the node ID was correct.

I put together a short video proving that it really works.

By the way, Image fields cause an AJAX call when an image is uploaded - the form is rebuilt but not reloaded. But as I said, the default\_value is preserved if you implemented the form alter correctly.
> 1 votes

---
Tags: forms, media
---


title: Custom form validation

text:
# Question
Title: Custom form validation
I've created a custom module for populating a database and now I need to apply form validation to this form.

I want a few different validation things to happen.

1. I want to limit specific entries on the client side IE: only allowing 6 characters being entered etc.
2. On submit I want to run through validation rules to make sure what was entered is correct. IE: only positive #s etc.

Are there any drupal 7 FAPI fields to validate specifics like this?

I found something like `'#element_validate' => array('element_validate_integer_positive'),`

Is there a list anywhere of element validations like this? I'm unable to find documentation anywhere :(

# Answer
I assume you are using Drupal's Form API.

> 1. I want to limit specific entries on the client side IE: only allowing 6 characters being entered etc.

In your element definition, you need to add the HTML attribute `maxlength`. For example:

`$form['your_field_name']['#attributes'] = array('maxlength' => array('6'));`

Regarding:

> 2. On submit I want to run through validation rules to make sure what was entered is correct. IE: only positive #s etc.

You can create your own validation function for the form or the element. For example, in your form definition, in the element you want to validate, you need to enter:

`$form['your_field_name']['#element_validate'] = array('your_field_name_validate');`

In this case, `your_field_name_validate` is the name of the function that will be invoked when the form is submitted. The function needs to be in the same module as the form definition, or in an include file. See an example here. Pasting:

```
function my_field_name_validate($element, &$form_state, $form) {
   if (empty($element['#value'])) {
     form_error($element, t('This field is required.'));
   }
}

```
> 0 votes

---
Tags: 7, forms
---


# Question
Title: Views filterable by current logged in user that equals Entity Reference field?
I have nodes that have a user assigned to them as a responsible party via Entity Reference. I would like to have a View display all the nodes that the current logged in user has they that they are the responsible party of.

Would a filter that looks something like this `Content: Responsible Party (Current User)` be do able?

I have gotten this far using the Entity Reference Filter for Views, but it doesn't give me a "Current User" option.

# Answer
> 2 votes
Add your entity reference field as Contextual filter in your View advanced settings and then in the section "when the filter value is not in the url" set the "Provide the default value" to "User ID from logged in user".

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


# Question
Title: How to add custom operation to commerce/orders list?
In Drupal 7 I want to add couple of custom operations in the Drupal Commerce's orders list (see picture below) after "delete" e.g. "Shipping List" and "Invoice" which would open external URLs in a new window. How can I achieve this? I tried to modify some files under sites\all\modules\commerce\modules\order\includes\views but I didn't see any change in the view. Why?

# Answer
The proper way to add new operations is to define them as menu items. Here is a snippet from the payment module, responsible for the **payment** operation listed in the screenshot:

```
  // Payment tab on orders.
  $items['admin/commerce/orders/%commerce_order/payment'] = array(
    'title' => 'Payment',
    'page callback' => 'commerce_payment_ui_order_tab',
    'page arguments' => array(3),
    'access callback' => 'commerce_payment_transaction_order_access',
    'access arguments' => array('view', 3),
    'type' => MENU_LOCAL_TASK,
    'weight' => 10,
    'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
    'file' => 'includes/commerce_payment_ui.admin.inc',
  );

```

The key part being this line right here:

```
'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,

```

In fact, in most (maybe all?) places where you see this list of operations or tasks in Drupal Commerce 1.x, they will be defined this way. Another example of this being the transaction listing screen. Payment modules can add new contextual menu items for things like credits, captures, etc:
> 5 votes

# Answer
To expand @nvahalik's answer a bit, you should implement `hook_menu()` in a custom module and include something like this:

```
function your_module_menu(){
  $items['admin/commerce/orders/%commerce_order/your_new_operation'] = array(
    'title' => 'Link title',
    'page callback' => 'your_callback_for_the_operation',
    'page arguments' => array(3),
    'access callback' => TRUE,
    'type' => MENU_LOCAL_TASK,
    'weight' => 5,
    'context' => MENU_CONTEXT_INLINE,
);

  return $items;
}

```

You can add some custom `'access callback'` to limit access to this link. If you do, the link will not be shown for users who don't fulfill the access callback.
> 2 votes

# Answer
You should look into implementing `hook_views_pre_render()` in a custom module.

> This hook is called right before the render process. The query has been executed, and the pre\_render() phase has already happened for handlers, so all data should be available.
>
> Adding output to the view can be accomplished by placing text on $view-\>attachment\_before and $view-\>attachment\_after. Altering the content can be achieved by editing the items of $view-\>result.

There are many examples of this hook online.

By the way, you should avoid changing the Drupal core (the first maxim you learn in Drupal is "do not hack core"). One of the problem of hacking the core is that any Drupal or module update will delete your hack.
> 0 votes

---
Tags: views, commerce
---


# Question
Title: Adding a new NOT NULL field to a table causes an error
When attempting to add a new column to a table within an update hook, the error `Null value not allowed: 1138 Invalid use of NULL value` occurred, the definition was changed to allow NULL, and the value for existing rows was set to NULL.

```
function MYMODULE_update_8101() {
  Drupal::database()->schema()->addField(
    'MYMODULE_table',
    'created',
    [
      'type' => 'int',
      'unsigned' => TRUE,
      'not null' => TRUE,
    ]
  );
}

```

When adding the column to the database with an SQL query, using the `NOT NULL` restriction causes the field to have a default value of 0, and no error happens.

How can the error be fixed, and the proper schema set?

# Answer
If the field spec sets `'not null' => TRUE` but does not define a default value, the column is created allowing null values and later altered to disallow them (see the mysql driver Schema::addField(), and the `$fixnull` variable). The second query attempting add the restriction fails, causing the error.

To fix the error, either

* An `'initial'` value needs to be added to the spec provided to `addField()`

```
Drupal::database()->schema()->addField(
  'MYMODULE_table',
  'created',
  [
    'type' => 'int',
    'unsigned' => TRUE,
    'not null' => TRUE,
    'initial' => 0,
  ]
)

```
* Or a `'default'` value needs to be added to the spec provided to `addField()`.
When providing a default value, the spec in `hook_schema()` should also be changed to match.
> 2 votes

---
Tags: 8, database
---


# Question
Title: Exporting comments only from one drupal site to another
How can i export only comments from a Drupal Site (Live) to a Drupal site (Dev).

The content of both sites is same. The live site only has new users and comments. I already exported the users and imported into Dev Site.

I looked into many modules but non on them only allow comments to be exported. Can i simply copy some MySql tables ?

thanks

# Answer
> 2 votes
Assuming you are using Drupal 7.

Use the Views module and create a table view of node comments.

Add fields: Node ID (nid), Comment ID (cid), Comment Title, Comment Body, Commment Author, Created Date.

For export, use Views Data Export and export the CSV file.

For import, use the Feeds module + Feeds Comment Processor and import your CSV.

Checkout this Feeds Video Tutorial (this is for nodes, not comments, but it will give you an idea on how feeds with the CSV import works).

--

Exporting MySQL tables approach:

Never done it like this, but if I were you, I would look for all the tables that have the name comment, export those and import.

Note sure if it will work as simply as that, but worth a try.

---
Tags: migrations, comments, importing-exporting, backups
---


# Question
Title: Is it possible to remove classes from a field that uses the Rendered entity format?
I have an entity reference field that is being handled by Display Suite. Even when setting the field template to expert, I can't completely strip away the default classes. The markup still has a div wrapper like so:

```
<span class="field-content">
  <div about="/products/chicken-breast-tenderloins" typeof="sioc:Item foaf:Document" class="ds-1col node node-product node-promoted node-teaser contextual-links-region view-mode-teaser clearfix">
    <div class="contextual-links-wrapper contextual-links-processed">
      <a class="contextual-links-trigger" href="#">Configure</a>
      <ul class="contextual-links">
        <li class="node-edit first"><a href="/node/37/edit?destination=node/23">Edit</a></li>
        <li class="node-delete"><a href="/node/37/delete?destination=node/23">Delete</a></li>
        <li class="manage-display last"><a href="/admin/structure/types/manage/product/display/teaser?destination=node/23">Manage display</a></li>
      </ul>
    </div>
    <a href="/products/chicken-breast-tenderloins">Chicken Breast Tenderloins</a>
  </div>
</span>

```

Is there any way to remove those classes? Like maybe using a preprocess function or something?

# Answer
> 1 votes
Generally: You could modify the display of the content type referenced by the Entity reference field. There you can use Display suite again for formatting the fields of the referenced content type and have it styled your way.

Especially, regarding this:

```
<div class="contextual-links-wrapper contextual-links-processed">
  <a class="contextual-links-trigger" href="#">Configure</a>
  <ul class="contextual-links">
    <li class="node-edit first"><a href="/node/37/edit?destination=node/23">Edit</a></li>
    <li class="node-delete"><a href="/node/37/delete?destination=node/23">Delete</a></li>
    <li class="manage-display last"><a href="/admin/structure/types/manage/product/display/teaser?destination=node/23">Manage display</a></li>
  </ul>
</div>

```

There is an option "Display Links" on the Rendered Entity. If you uncheck this, you can get rid of this code. This is done in the content type where the Entity Reference field is included, not in the referenced conten type.

If you want to change this:

```
<div about="/products/chicken-breast-tenderloins" typeof="sioc:Item foaf:Document" class="ds-1col node node-product node-promoted node-teaser contextual-links-region view-mode-teaser clearfix">

```

Go to the content type you are referencing and check the display. It seems you are using the 1 Col Display, so you can use ds-1col.tpl.php template. There you can change the classes.

---
Tags: entities, theming
---


title: Edit user profile template with module

text:
# Question
Title: Edit user profile template with module
How can I edit the user profile template in Drupal 7?

I've created a module called sporthron in my project.

sporthron.module contains :

```
/**
 * Implements hook_theme().
 */
function sporthron_theme($existing, $type, $theme, $path) {
  $theme = array();
  $theme['user_profile'] = array(
    'template' => 'user-profile',
    'path' => drupal_get_path('module', 'sporthron') . '/templates',
   );
  return $theme;
}

```

And here is the path to the template : /sites/all/modules/sporthron/templates/user-profile.tpl.php which contains :

```
<div class="profile"<?php print $attributes; ?>>
  <?php print render($user_profile); ?>
</div>

TEST

```

But this template is never used. Whatever edit I made is not applied.

And yes my module is enabled. Do you know how can I apply this template

# Answer
> 1 votes
Try to implement the hook\_theme\_registry\_alter()

```
/**
 * Implements hook_theme_registry_alter().
 */
function sporthron_theme_registry_alter(&$theme_registry) {

  $module_path = drupal_get_path('module', 'sporthron');

  // Find all .tpl.php files in this module's folder recursively.
  $template_file_objects = drupal_find_theme_templates($theme_registry, '.tpl.php', $module_path);
  // Iterate through all found template file objects.
  foreach ($template_file_objects as $key => $template_file_object) {
    // If the template has not already been overridden by a theme.
    if (!isset($theme_registry[$key]['theme path']) || !preg_match('#/themes/#', $theme_registry[$key]['theme path'])) {
      // Alter the theme path and template elements.
      $theme_registry[$key]['theme path'] = $module_path;
      $theme_registry[$key] = array_merge($theme_registry[$key], $template_file_object);
      $theme_registry[$key]['type'] = 'module';
    }
  }
}

```

---
Tags: 7, theming, users
---


# Question
Title: How to implement hook_views_query_alter?
I used this topic before asking question but even if the problem is very very closed, the answers given did not work for me.

So I need to alter the query of one of my views in drupal 7. I created a new module called for example 'mymodule'. This module contains

* .info file.
* .module file.
* .views.inc file.

My **.module file** contains the following. Note that my **.views.inc** file is located at the root of the module directory. I also checked that my views api version is 3 :

```
function modulename_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'modulename'),
  );
}

```

My **.views.inc file**, which is at the root of the module directory contains the following :

```
function modulename_views_query_alter(&$view, &$query) {
dpm($view);
watchdog('error title', 'error message');
echo 'TEST TEST';
die('test');
if ($view->name == 'my_view_name' && $view->current_display == 'my_display_name') {
    unset($query->where[1]['conditions'][0]);
    unset($query->where[1]['conditions'][1]);
 }
}

```

I can't see what I am missing trying to implement this hook but it never go into the views\_query\_alter function (I cleared the cache before trying). I think I've followed all advices given in the link provided above.

Any help would be appreciated.

# Answer
> 0 votes
.views.inc file is to separate the views alter logic.

hook\_views\_api to add the mymodule.views.inc file which can be with path your-module/includes/views or at the root of your module.

You also can use mymodule\_views\_query\_alter at mymodule.module file which should work fine.

Please remove the cache after applying the changes.

---
Tags: hooks, views
---


# Question
Title: How to cancel added product to cart if previous order has same commerce-product creator id
I need this rule on before add product to cart react event, not after save commerce order.

I need when user (buyer) klick second button add to cart (for multi order), system check the product creator id first, if the product creator id for the second order clicked is same with previous (where is actually on cart) system cancel the previous clicked order.

With this scenario I want to limit order only from same product creator for one times order. So if buyer want to continue order from different product creator they have to do after first order completed.

Any suggest how to solve this using rule??

# Answer
> 1 votes
tl;dr - Rules is really the place to handle this. You need to hook into the add to cart form's validate/submit handlers and take care of it in there.

The best way to handle this is to look into the answer provided here: How do I prevent a product from being added to the cart?

This answer was originally written to do that very thing: to prevent a product from being added to an order if some criteria were met (and the context was a marketplace multi-cart as well).

---
Tags: commerce
---