Profile pictures not displaying in forum I am making my first forum using Drupal and have very little web development experience.  My forum is very basic so far, mostly using core modules.

I tried adding a profile picture for my admin account (and also a picture for a test user account), but the image doesn't show anywhere.  I only get the thumbnail that indicates a missing file or broken link.  I have tried reloading the page, clearing the cache, and installing the profile2 module, but of course I still do not see images.  I have since uninstalled profile2 just because I want to keep the forum as simple as possible until I learn more.

I'm working in version 7.39 and the site is hosted on my university account.

Thanks in advance for any suggestions.

Eric

I had also posted my question to my university drupal help list and managed to find an answer.  I don't know how much of this applies to the general community (it may only apply to my specific Drupal install at my university because they include automated configuration adjustments), but here is the solution that worked for me:

My main folder is called simply drupal.  In the file

/drupal/.htaccess

I had changed the line

Options +FollowSymLinks

to instead read

Options +SymLinksIfOwnerMatch

The problem was that I had not changed a second copy of this file in another location:

/drupal/sites/default/files/.htaccess

I made the same changes to this file and now the images show.  I did not simple copy one file to the other location, because the files contain different options and only the one line needed a change.  Again, my drupal install might be unique to my university, but these edits are so minor that I think someone else could try them without getting into too much trouble.  Maybe someone else could lend more insight if needed.


How do I get drush to run remote drush not in a path? A remote server doesn't have drush, so I put it in my ~.

Adding a $PATH works fine for myself being logged in, but since ssh [command] wont open a shell, $PATH is never picked up when I use drush @remote-alias status.

The alias setting %drush-script is used to solve this.

$aliases['alias'] = [
  'path-aliases' => [
    '%drush-script' => '/home/[user]/bin/drush',
  ],
];


Best way to migrate Content from drupal 6 to 7? Becoming more familiar with Drupal by doing a drupal 6 to 7 upgrade along with switching Ubercart to Commerce.  But the site just doesnt seem to work right.

I followed the upgrade procedure suggested by drupal but something is off

Having random errors all over the place, admins running into php memory limit errors(ex. people > permissions), missing fields, unable to add criteria to views.

Is there a better way to do this. Should I start with a fresh install and import programatically someway or with a a module?

Its a fair amount of content i have to import but would it be better just to do it manually?

Im just wondering how others go about doing this because there seem to be mixed opinions

Migrate might be the module you need:

  The migrate module provides a flexible framework for migrating content into Drupal from other sources (e.g., when converting a web site from another CMS to Drupal). Out-of-the-box, support for creating core Drupal objects such as nodes, users, files, terms, and comments are included - it can easily be extended for migrating other kinds of content. Content is imported and rolled back using a bundled web interface (Migrate UI module) or included Drush commands (strongly recommended).

There is specialized Drupal-to-Drupal data migration for just the task you need:

  migrate_d2d provides a framework based on the Migrate API for migrating content from Drupal 5, Drupal 6, or Drupal 7 sites into the Drupal 7 site where it is installed. As of the 2.1 release, It requires Migrate 2.6 or later. Besides addressing contemporary needs to migrate to Drupal 7, it has helped serve as a proof-of-concept for incorporating the migration approach into core as an upgrade path (https://groups.drupal.org/imp).

It's far from perfect, all right, but it's good and well tested - in my experience it is most solid way unless you want to write custom one just for your case.


In a view how to replace the date of creation of the comment by the date of the flag? I created a "like" flag on the nodes.

I created a view that displays the comments.

I want my view to show only comments posted since the flag date.

The solution will be to create a filter criteria with the filter "Comment: Publication date" (Is greater than or equal to) and replace the value with the date of the flag.

The problem is that there are no tokens for the filter criteria.

There is a tutorial here :

https://www.webomelette.com/creating-custom-views-filter-drupal-8

But I failed to create the criteria filter. This is the first time I've created code for a view.

Can you explain to me in an answer how to do this step by step ?

thank you in advance

I created a folder :

notify_node_new_comment

And a file notify_node_new_comment.yml that I placed inside :

name: Notify node new comment
description: Notification of new comments.
type: module
core: 8.x

I created an empty file notify_node_new_comment.views.ink in my folder (I do not know what to put as code).

I also added the following folders :

/scr/Plugin/views

Views filters have nothing to do with tokens. What you need to do is build the necessary query for this, which is something that tutorial ignores completely as it is a pretty simple condition.

A bit of searching pointed me to \Drupal\taxonomy\Plugin\views\filter\TaxonomyIndexTidDepth::query as an example that builds a complex subquery condition in a filter.

I don't know your level of expertise with PHP/Drupal/SQL, so I would recommend you start by building the SQL that is needed for this by hand. In the views settings, enable to show the SQL query on the preview. Then copy that query, remove the {/} execute it by hand and try to adjust it to contain the filter you need. You probably want to add a relationship to flaggging already.

Once you have that, implement that in PHP in the query method of your filter.


define custom jquery event to use in ajax form How can I create custom jquery event to use in event:

$form['submitted']['subject']['#ajax'] = array(
  'callback' => 'suggest_ajax_callback',
  'effect' => 'fade',
  'event' => 'change',
);

for example I want execute suggest_ajax_callback each time user enter Space while filling text-field. so "How Can I Pay?" will cause 3 time execution...

The solution for your question is not handled compelety by back-end of drupal.

By default drupal ajax not support customized event
You can acheive your means by jquery and ajax(non-drupal ajax)
Something like this

For using get data by jquery ajax you need first seta menu link for listen to your ajax requst, and in callback of your menu you passed back a block or any data you want.

function yourmodule_menu () {
   $items=array();
   $items['youruniqepath'] =array(
        'title' => 'my menu',
        'description' => 'A menu link to handle ajax request',
        'page callback' => 'yourhandlerfunction',
        'acess callback' => TURE, //you can set it with your permission
      );
  return $items;
   }

and in yourhalderjust need pass a block

function yourhandlerfunction () {
  //with any method you want get your block,
  // I suggest something like this
    $block = module_invoke('module_name', 'block_view', 'block_delta');
    print render($block);

}

and in your clientside get it with something like this

  $('#yourelement').change(function() {
    if( checkfor your means) {
         $.ajax({
                       type: "POST",
                       url: 'youruniqepath',
                       //data: {}, you can also pass block name and act more dynamicly
                      success: function (data){
                          $('#yourplace').html(data);
                      },});
         }

});


What causes EntityMetadataWrapperException: Unknown data property? I have added new field to my bundle in one of entity type. I used the Group audience as field type and Group Audience as widget type.
This is to make the field to select multiple records.

While adding the new record with all the values it gives following error:

  EntityMetadataWrapperException: Unknown data property og_membership.
  in EntityStructureWrapper->getPropertyInfo() (line 354 of
  /var/www/vhosts/test1.3blmedia.com/httpdocs/sites/all/modules/entity/includes/entity.wrapper.inc).

I am not getting where it is wrong. Any hints?

Please login to admin and go to following page. You need to add field for your bundle. It will resolve above error.

Home » Administration » Configuration » Group
Organic groups field settings

For more details please visit following link.
https://www.drupal.org/node/2023721


How to list categories dynamically Is there a way of creating lists of categories dynamically?

For instance, say I currently have 2 TVs on the site. If I then add a DVD player product, is it possible to automatically generate a DVD player link (in a block etc)?

I've been playing with Views as I thought it may have done the trick, but I've had no success. Any pointers would be great.

It sounds like a View of Taxonomy terms would meet your needs.

If I wanted to create a block with a list of items tagged with term in the category "Electronics" then I would do something like this:

Create a View with the following options:

Show Taxonomy Terms
of type Electronics
sorted by [unsorted]

Check the "created a block" box.
Add terms "DVD player", "DSLR camera", and "LCD monitor" to my "Electronics" vocabulary.
Add the relevant terms to the relevant product pages
Enable the block

Now, if I start selling Zunes next month (hah) then I can add term "mp3 player" to the "electronics" vocabulary and it will show up in the list of electronics-related terms in my block.


Adding background color to table rows I was wondering if it is possible to change the background color of a table row.

I want to display certificate files, and if that certificate is going to expire in longer than 30 days the color green would be good. If it is less then 30 days color orange and if it's expired color red.

I tried finding it on the internet but I can't find anything like this.

This is how my current column data looks like.

'c3' => array(
        'data' => array('#type' => 'item', '#markup' => t('@uploaded', array('@uploaded' => date('d-m-Y', $val->upload_date)))),
    ),

I already tried adding '#class' => array('bgcolor' => '#ffffff'), or just 'bgcolor' but that doesn't work.

Thanks in advance!

Complete code

$qry = db_select('push_notifications_api', 'n');
$qry->join('push_notifications_certificates', 'u', 'n.ios = u.cert_id');
$cert_table = $qry
->fields('n', array('app_name', 'ios'))
->fields('u', array('cert_id', 'cert_name', 'upload_date', 'expiration_date'))
->OrderBy('u.expiration_date', 'ASC')
->execute();

$form['certificates']['table'] = array(
 '#theme' => 'table',
 '#header' => array(t('Application'), t('Certificate'), t('Uploaded'), t('Expiry Date')),
 'rows' => array(),
 '#weight' => 30,
);

foreach($cert_table as $key => $val) {

$form['certificates']['table']["#rows"]["'r$key'"] = array(
    'c1' => array(
        'data' => array('#type' => 'item', '#markup' => t('@app_name', array('@app_name' => $val->app_name))),
    ),
    'c2' => array(
        'data' => array('#type' => 'item', '#markup' => t('@cert', array('@cert' => $val->cert_name))),
    ),
    'c3' => array(
        'data' => array('#type' => 'item', '#markup' => t('@uploaded', array('@uploaded' => date('d-m-Y', $val->upload_date)))),
    ),
    'c4' => array(
        'data' => array('#type' => 'item', '#markup' => t('@expiry', array('@expiry' => date('d-m-Y', strtotime($val->expiration_date))))),
    ),
);
}

You can add class for the row and add background for this class via the css

$row = array(
  array(
    'data' => array(
      array( 'data' => 'cell1'),
      array( 'data' => 'cell2'),
      array( 'data' => 'cell3' ),
    ),
    'class' => array('my-class'),
  )
);

print theme('table', array('rows' => $row));


Custom panels-pane tpl based on some identifier Is it possible to create a pane template based on some kind of identifier? Just Like you can create a page--node--123.tpl.php file to render a different page for a node with nid 123, i'd like to make a panels-pane--pid--123.tpl.php to render a specific pane with pid 123 I have tried looking on google but i have found nothing about this possibility.

After a lot of working around & trial & error methods, I got this.

Copy your "panels-pane.tpl.php" in your current theme's template directory.
include dpm($pane); in a php tag. This will give u the list of all the panes on ur current panel page.
Note down the pid ($pane->pid) here.

If you are looking for a particular page the unqiue identifier for that whole page would be did ($pane->did) which is the display id.
Basically, every panel page has a unique did (display id) & different pid (pane Id) for all the panes on that particular page.

Now in your "panels-pane.tpl.php" in the div code block with class="pane-content" you could write a php code like

if($pane->pid=='some id' & $pane->did=='some id') {
//modify your pane data from the variables at $pane->configuration & store in $content.
   $content = your modified data;
   print render($content); // render this pane with my modified data
else
print render($content); // (and) render other panes as normal
}


How to always show Save as ... when download a image file in Webform result? If the upload file is an image in a Webform's result, clicking the link will show the image in the browser.

Is it possible to force to popup a Save as... dialog? Such the user downloads the file instead of viewing it?

This is technically not a drupal specific issue it is just how browsers deal with certain file types on the web in general.

Also note that you can right click a link to save the file always, so if this is an admin only feature then maybe that is sufficient?

If you are using Drupal's public file system for the images then it is possible to change your .htaccess file to change the behaviour of certain file types.

For more info on that see: Force files to download instead of showing up in the browser.

The .htaccess method should be the best performing and most reliable method, however if there is any reason you don't want to do it the .htaccess way there are a couple of drupal module that can help.

The File Force and Download File modules will allow you to configure file downloading however if you are making custom links to your files (for example if you are entering links directly into a text field or in custom code) you have to use a different url for the images to make sure that the links use the module's functionality, so be sure to read the documentation for whichever module you are using.

The modules are quite similar so use whichever you prefer.

[Edit]
I just remembered you are interested in webform related links.
Unfortunately since the current version of webform doesn't use Drupal's normal fields it won't work properly with these file downloading modules out of the box.
A feature request for the modules will be needed to add webform support.

Alternatively you could modify your webform links to use the special formatting the download module you are using supports.

For example, overriding the themeing of the webform file display like this would work if you are using the file force module:

/**
 * Format the output of text data for this component
 */
function THEMENAME_webform_display_file($variables) {
  $element = $variables['element'];

  $file = $element['#value'];
  $url = (!empty($file) && !empty($file->uri)) ? webform_file_url($file->uri) : t('no upload');
  return (!empty($file) && !empty($file->uri)) ? ($element['#format'] == 'text' ? $url : l($file->filename, $url, array('query' => array('download' => '1')))) : ' ';
}

It would be a similar process with the download file module.


Memory-saving cache-clearing strategies for large sites? One of my Drupal 7 sites has thousands of fields, a bunch of content types, more than 25 views, and hundreds (soon to be thousands) of profile types. Because of this, I'm using a core patch that better caches entity field info (http://drupal.org/node/1040790), and the -dev version of Views which better caches views by display (instead of having one HUGE views cache row with all views data in it).

This has helped most pages on the site to load with 20-30MB of RAM used, rather than 160MB+ (instead of pulling up cache_* table rows for fields and views that were 10MB+, the patches help keep cache_* data much more efficient).

This introduces a problem, however, in that cache rebuilds take a really long time. Usually more than a minute or two. And during this time, Drupal simply won't load any pages (since the caches that it's trying to read from are not yet built, other requests have to wait).

During low-traffic cycles, this isn't a big deal; a hundred or so users will simply have to wait a minute before the page loads. But during high-traffic cycles, the Apache server starts going crazy, with 40+ CPU load, and the memory quickly fills up because all the worker threads sit waiting, and max out their memory, causing swapping. It's kind of a death spiral. A restart of httpd will clear things up, but it takes 5-10 minutes for things to get back to normal.

My goal is to make it so cache clears don't bring the site to its knees. For one, if I use admin_menu's individual cache clearing functions (like "CSS and JS", then "Menu", then "Theme registry", etc.), things go smoothly until I hit the "Page and else" option. That's when views' cache is reset (a very CPU and database-intense operation with the number of views that need to be cached), and when the field info cache is reset (which is also CPU and database-intense on this site).

So... my questions/ideas:

Using drush and/or other shell scripting, is it possible for me to clear caches in a more intelligent way than "blast all caches at once, and hope for a clean rebuild"?
Can I block http requests while the cache clearing is happening so apache doesn't get clogged with a bunch of cache-stampeding requests?
If I can clear caches outside of Drupal/normal httpd request, I could presumably set a higher PHP memory_limit for the cache clear operation, and back off my universal memory_limit (right now set to 256MB, in case any individual httpd thread needs to clear caches...).

Basically: Is there any intelligent and graceful way to clear all caches with Drupal besides simply clicking the button in the UI, or using drush cc all?

[Edit for clarification: The main problem I have is cache rebuilds, which (a) take a while, and (b) block all other requests until the rebuilds are complete. I would like to find a way to make it so the rebuilds aren't quite as deadly during high-traffic times.]

Is there any intelligent and graceful way to clear all caches with Drupal besides simply clicking the button in the UI, or using drush cc all?

The cache actions module does that. It depends on rule. For exampple, you can setup a rule to clear a specific view when a node of type "x" has been added or updated. Checkout the docs for more details.

Also take a look at the cache graceful module - haven't tried it yet but looks interesting.


Relationship between content types I have two content types: Region and City. Region nodes include City nodes; every City node is related to some Region node.

How I can create a relationship for this situation? When I create a Region node and refer a City node in a field, all City nodes have its Region referencing field set to this Region node and vice versa.

You can use Corresponding Entity References to achieve this.

Follow these steps:

Create two content types: Region and City.
Insert entity reference field: Cities in Region and Region in City.
Now enable Corresponding Entity References and update its configuration by going on your site: Configuration >> System >> Corresponding entity references.
Check this configuration: Correspond Region on node(s) of type city with Cities on node(s) of type region.

Now in next tab Updating existing entities of entity type: node.


HTML in table cell being escaped I'm programmatically creating a table in Drupal 8, using #type => 'table'. I'm adding some HTML to a table cell, however the output is being escaped so that the HTML is rendered as plain text, rather than as HTML.

From everything I read, it sounds like all output in twig templates are escaped by default.

I'm guessing I can override table.html.twig, but I'm guessing (hoping) there is a way to do it when defining the table, rather than overriding the template each time I want to create a new table that has HTML.

Does anyone know how to use HTML in a table cell in D8?

The answer (that worked for me) is to use FormattableMarkup:

use Drupal\Component\Render\FormattableMarkup;

$row[] = new FormattableMarkup('<span>@somevalue</span>', ['@somevalue' => 'some value']);


Confirmation pop up on login submit I have built a site using drupal 7.41. I have added the login form by adding this line in my page.tpl.php "print render($page['login_container']);".

When user click on the login button I want to show a popup with options "yes" and "no". only when the user choose "yes" he/she should be logged in. I need change the style of this pop up, that's why I cannot use jquery window.confirm function.

I went through drupal documentations and found about the function confirm_form.
this is what I am trying to do, but not able to.

I created a hook menu and then called the confirm_form fucntion.
But I am not able to call this from the login submit button.

Sounds like some simple Javascript. E.g. by the help of JQuery you could bind a click/submit function on the login-form, show a confirm-window ("Would you really like to log in?") and if this is confirmed, submit login-data (or not).

Such a function could(!) look similar to this:

$('#user-login-form').submit(function(){
 var r = confirm("Would you really like to login?");

 if (r == true) {
    return true; // submit form-data
 } else {
    return false; // stay on page
 }
});


Best way to deal with long list I've an entity called "guy" with a field "location" and i've 9-10.000 location that i want to reference. I must use a simple list (1|bla, 2|blabla) or an entity reference field that target the location entity? I need the autocomplete function but drupal is very slow with a great number of location. But i don't know if i can load a list of 9-10k lines.
I don't wont to use taxonomy.
To speed up the autocomplete, how i can create a list of frequently selected location?

I dont think there is a module you can use.

The form will contain an element such as

<?php
  $form['city'] = array(
    '#type' => 'textfield',
    '#title' => 'City',
    '#maxlength' => 128,
    '#autocomplete_path' => 'cities/autocomplete',
  );
?>

Addition to hook_menu

You must add #autocomplete_path to your hook_menu function.

<?php
    function cities_menu(){
    ...
    // path with autocomplete function for cities
    $items['cities/autocomplete'] = array(
      'title' => 'Autocomplete for cities',
      'page callback' => '_cities_autocomplete',
      'access arguments' => array('use autocomplete'),  //or whatever permission makes sense
      'type' => MENU_CALLBACK
    );
    return $items;
?>

Make a call to the Database.

<?php
/**
 * autocomplete helper
 * $string = string for search
 */
function _cities_autocomplete($string) {
  // Fetch most used cities.
  $matches = array();
  $result = db_select('cities', 'c')
    ->fields('c', array('city'))
    ->condition('city', '%' . db_like($string) . '%', 'LIKE')
    ->execute();

  // save the query to matches
  foreach ($result as $row) {
    $matches[$row->city] = check_plain($row->city);
  }

  // Return the result to the form in json
  drupal_json_output($matches);
}
?>

Make sure your autocomplete handler has appropriate menu permissions set on it,

From : Textfield that uses autocomplete


How to Center Image in View Slideshow I can't get the views slideshow to center in the div. I tried the following code but with issue:

#views_slideshow_cycle_main_content_slideshow-block {
  width: 100%;
  text-align: center;
}
#views_slideshow_cycle_teaser_section_content_slideshow-block {
  display: inline-block;
}

The image display in few seconds but disappear afterwards.

Can anybody please help me how to solve this problem?

You have to use image styles to get all the images the same size.

Goto Admin -> Configuration -> Media -> Image styles

Create new image style & enter style name with a scale and crop with exact dimensions for your slideshow.

Then go back to your views slideshow setting and select your style name as image style.


Why can't I add a product? I need to add product via services, but I have strange issue with a price field.

The case is that all fields saved correctly except price field amount and it returns:

  The requested URL returned error: 500 Internal Server Error : An error occurred (0): Unable to get the data property amount as the parent data structure is not set.

The url which is used: endpoint/product.

Here is the code:

fields `$node_data = array(
  'sku' => 'sku1',
  'title' => 'product title',
  'type' => 'product',
//  'commerce_price_amount' => array('amount' => 122.000, 'currency_code' => 'KWD'),
  'commerce_price_amount' => 12.000,
  'commerce_price_currency_code' => 'KWD'
); 12.000,
  'commerce_price_currency_code' => 'KWD'`

which successfully added all fields except price.

I think it relate to price field format.

It works with me after disable some modules related to commerce like payment, order, cart, tax and then clear cache products saved.

I still didn't know the reason for that error


Is it possible to get relation in Views to Commerce products? I made View by Taxonomy term.
Using Relations I got Content which has this Taxonomy term.

Now I want to see couple of Commerce fields (SKU and Price) which are referenced from Content type.
Is it possible from Taxonomy View go to Content (I have already done it) and then to Commerce fields from Content?

Make the relationship with commerce product then you will see the related fields in fields list.


Programmatically manipulate content type select list I have a content type called Car which have several field two of them are select lists which I want to make some operations on them. When the user select a value form the first select list a bulk of values should be populated in the other select list, my question is WHERE to do this programmatically and some tips for HOW doing this? I hope my question is clear

best

You need to use hook_form_alter to add AHAH/AJAX to your field. The hook should be placed in either a custom module or in your theme's settings.php file.

Drupal has many examples about this. Here's for Drupal 6 and here's for Drupal 7.

This specific example from the links above seems to be what you are looking for.


Is Settings::set() a valid function? Can I set value like Settings::set('some-variable','hello')?

As if we can get value using Settings::get('some-variable') then why the 'set' method is not working?

No, you can not call Settings::set. You should get an

Error: Call to undefined method Drupal\Core\Site\Settings::set() in ...

Maybe there's something wrong with your error reporting or you imported any other Settings class (check your namespace). Check your php.ini for this. The Settings Class is for read-only access to the settings in settings.php.

If you need to set some system settings do it like this:

// themes
\Drupal::configFactory()->getEditable('system.theme')
->set('admin', 'bartik')
->save();


How do the variables in .twig files work? I am using a theme based off awesome zymphonies theme.
I'm trying to use the site_logo variable from page.html.twig, but it doesn't have access to it, instead I have to use the page.header region, which somehow (I need clarification as to how) calls upon the code in block--system-branding-block.html.twig and there I can use site_logo.
So my question is why site_logo can only be accessed from that twig, and what would I need to do in order to use site_logo, or any other variable in any other twig file?

The site_logo block is available in the page.header region because that logo block itself is placed into that region using Drupal's block layout: mydrupalsite.com/admin/structure/block
Drupal's template/twig system is a set in parent and children type templates. So the page.header region/template may print {{ site_logo }} - but the contents of {{ site_logo }} are outputted in block--system-branding-block.html.twig
Blocks are placed in regions so you can't really access a block directly in page.html.twig unless you add it programmatically.
Probably what you are looking to do is place the site_logo block into the region which approximates the position you want it to be displayed. Then if you want to "fine tune" it you can override that regions template using the following naming convention:
my_drupal_theme/templates/region--[region].html.twig

E.g.
my_drupal_theme/templates/region--header.html.twig

Then maybe your region--header.html.twig file looks like:
<div class="my-custom-wrapper-class">
  {{ site_logo }}
</div>

What can be really helpful here is knowing the basics of twig template naming conventions - and also turning on "twig template debugging" which gives you template names you can use to override.
https://www.drupal.org/docs/theming-drupal/twig-in-drupal/twig-template-naming-conventions
https://www.drupal.org/docs/theming-drupal/twig-in-drupal/debugging-twig-templates#s-enable-debugging
Just for completeness: if you did want to load the logo directly in your page.html.twig you could add it via a hook_preprocess_HOOK
@file my_drupal_theme/my_drupal_theme.theme

/**
 * Implements hook_preprocess_page().
 */
function my_drupal_theme_preprocess_page(&$variables) {
  $block_manager = \Drupal::service('plugin.manager.block');
  $plugin_block = $block_manager->createInstance('system_branding_block', []);
  $variables['site_logo'] = $plugin_block->build();
}


Aggregating Views and conditional field I have created a views for label printing;

1st item in the row is name,

2nd item in the row is address,

3rd row is city,

4th row is state,

5th row is Country.

All of them are fields of type contact.

Now I want two things;

If country is India, then it should not be displayed.
If two records has same Address & city & State & Country they should be aggregated.

Using Views Conditional Module you can set conditions for fields . The other module which may become useful is Views Field View.

Here are some description about Views Conditional Module :

  Views Conditional is a simple module that allows you to define conditionals (if xxx then yyy)
  with fields in views. Conditions include:

  Equal To
  Not Equal To
  Greater Than
  Less Than
  Empty
  Not Empty

  Views conditional allows you to output text based on the result of the condition.


Show node's content moderation state in a view How can I display the current moderation state for the node in a view and filter on it?

In Drupal 8.5 this has gotten a lot easier.

Pre-requesities:

1) Enable content_moderation (which enables workflows).

2) Set up a workflow with content moderation states.

3) Create a new view with the base table "Content Revisions".  This is important, as the main content out of the box is based on "Content" which refers to the default revision.  We want to see the latest revision.  I made this mistake at first where I took the default content view and added a relationship to Content: Moderation State.  This is the moderation state of the default revision, which is not what we want to see.  We want to see the moderation state of the latest revision.

4a) Under "Filter Criteria" add filter "Is Latest Revision".

5) To display the moderation state, under "Fields" select "Content Revision: Moderation state".

6) To filter by moderation state, under "Filter Criteria" add filter "Content Revision: Moderation state" and expose it.

7) Save your view.

8) You'll need to update your content so that it has moderation states.  This can be done by resaving it.

For example you could run:

  $article_nids = \Drupal::entityQuery('node')
    ->condition('type', 'article')
    ->execute();

  $articles = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($article_nids);
  foreach ($articles as $article) {
    $article->save();
  }

Now your view should show moderation states.

It looks like Drupal 8.5 also adds a subtask on the system.admin_content route that shows a link to a page that displays moderated content.

If you'd like to turn off these subtasks:

/**
 * Implements hook_menu_local_tasks_alter().
 */
function mymodule_menu_local_tasks_alter(&$data, $route_name) {
  if ($route_name == 'system.admin_content') {
    if (!empty($data['tabs'][1]['content_moderation.content'])) {
      unset($data['tabs'][1]['content_moderation.content']);
    }
    if (!empty($data['tabs'][1]['content_moderation.moderated_content'])) {
      unset($data['tabs'][1]['content_moderation.moderated_content']);
    }
  }
}


What (basically) does views/includes/plugins.inc line 9 views_include('base') actually do? I ran into an issue today where I started getting the following white screen of death error:

  PHP Fatal error:  Call to undefined function views_include() in /*/sites/all/modules/views/includes/plugins.inc on line 9

I found several various bug reports and questions with similar errors. Some said it was a bug in views, some said it was a bug in VBO, and some reported it being issues with a specific module (like finder) none of which am I really concerned about.

My question is, since most of the solutions had to do with either commenting or uncommenting a particular line. Line 9 in views/views/includes/plugins.inc views_include('base'), what does this line actually do? Furthermore, what is the harm/benefit of having it commented or uncommented?

For my personal part, I was able to comment out the line (which cleared the error) then clear my cache and uncomment the line without the error returning, which seems awfully bizarre.

I the code is generally something with including (libraries/functions?) for views plugins, but further explanation would be much appreciated.

From views.module:

/**
 * Include views .inc files as necessary.
 */
function views_include($file) {
  static $used = array();
  if (!isset($used[$file])) {
    require_once './' . drupal_get_path('module', 'views') . "/includes/$file.inc";
  }

  $used[$file] = TRUE;
}

so to your question, it is trying to load up base.inc out of the Views module includes directory.  Unfortunately, for whatever reason, the views module itself doesn't appear to be loading up (and thus defining the function to begin with).


Emails are not sent to outside domains I deployed a Drupal 8 website, on a hosting service with cPanel, with domain mydomain.com.

If I set this email address on the user profile: john.smith@example.com, that is an email address with a domain different from mydomain.com, then I go to:

mydomain.com/user/password

and I click to "Send" trying to receive the "reset password" email, it give me the error below and I don't receive the email:

  Unable to send e-mail. Contact the site administrator if the problem
  persists.

Same problem on contact forms.

If I set an email address within my domain, for example john.smith@mydomain.com, all works and the email is correctly sent.

Any idea why this is happening and how to solve this problem?

NOTE

I tried to create this php script inside the server in order to check if there is some issue on the server configuration:

<?php

$to = "john.smith@example.com";
$subject = "Test mail";
$message = "This is a test message.";

$headers = [];

$headers[] = "From: noreply@example.com";
$headers[] = "MIME-Version: 1.0";
$headers[] = "Content-type: text/plain; charset=UTF-8; format=flowed; delsp=yes";
$headers[] = "Content-Transfer-Encoding: 8Bit";
$headers[] = "X-Mailer: Drupal";
$headers[] = "Reply-To: noreply@example.com";

$res = mail($to, $subject, $message, implode("\n", $headers));

echo "Mail Sent.
\n";
echo "Res: " . $res . "
\n";

When I run this script it correctly works and sends the email, either if the $to property is from my domain or if it is from an external domain.

So I excluded it is a server configuration issue.

I solved the problem.

Taking inspiration from this thread, I figured out that, for some obscure reason, I need to set the email setting under "Administration > Configuration > System > Basic site settings > E-mail address" to an existing email address on my hosting service.

So, I created a new email with cPanel, noreply@mydomain.com, then I setted this email address in the above configuration.

Now seems that all is working perfectly.


How to access values in node object? Hi i am unable to access values from a node object inside a preprocess_views_view . Below is a screenshot of my object and i want to access the value highlighted. How can i do that?

There are several options:

You can use the getter method for the node id (available for all entities):

$node->id()

You can use magic methods to access any field of any content entity:

$node->nid->value

The above code will actually trigger the below:

$node->get('nid')->get(0)->get('value')->getValue()


CDN and Boost - not working properly I have a drupal 6 site. Recently I've set up a CDN (not using the module. manually, and more specifically Google PageSpeed Service) to serve my content which is cached by boost. What I've noticed that when cron is run, the boost cache files are not deleted. This happens probably because my real domain name - www.example.com points to the cdn, which internally uses a different cname to reach my server (origin.example.com). Unlike other CDNs, PageSpeed doesn't request pages from my server using the internal cname, but rather uses www.example.com.

So anyway, to make a long story short: when cron runs, it clears origin.example.com cache files and not www.example.com (and these are the files my visitors get). I should say also that this CDN doesn't support https, so I access the admin using origin.example.com.

So, any ideas....

I have a similar setup using Pressflow, changing

$base_url='http://www.yourdomain.com';
$cookie_domain = 'yourdomain.com';

in sites/default/settings.php seems to get boost cache cleared.


Why I not get value from $form_state['values']['field_form_name'] I created module_templat with code:

<?php

 function module_template_menu(){
    $items = array();
    $items['them-noi-dung'] = array(
        'title' => t('Khai báo hóa chất'),
        'page callback' => 'drupal_get_form',
        'page arguments' => array('module_template_select_form',2),
        'access callback' => true,
    );
    return $items;
    }

function module_template_select_form($form, &$form_state){
    $form = array();
    $form['select'] = array(
        '#type' => 'radios',
        '#title' =>'Lựa chọn hình thức khai báo',
        '#options' => array('0'=>t('Khai báo lần đầu'), '1'=>t('Đã từng khai báo')),
        '#default_value' => '0',
    );
    $form['ma_so_thue'] = array(
    '#type' => 'textfield',
    '#size' => '20',
    '#title' => 'Vui lòng nhập vào Mã Số Thuế',
    '#states' => array(
        'visible' => array(':radio[name="select"]' => array('value'=>'1'),
                    ),
            ),
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Tiếp tục'),
    );
    return $form;
    }

function module_template_select_form_submit($form, &$form_state) {
    $select = $form_state['values']['select'];
    $masothue = $form_state['values']['ma_so_thue'];
    if(isset($select)){
        $masothue = $form_state['values']['ma_so_thue'];
        $form_state['redirect'] = 'node/add/khai-bao-hoa-chat';
        }
    }

function module_template_form_alter( &$form, &$form_state, $form_id ){
    $masothue = $form_state['values']['ma_so_thue'];
    if ($form_id == 'khai_bao_hoa_chat_node_form') {
        $form['field_ten_to_chuc']['und'][0]['value']['#default_value']= $masothue;
        }
    }
function module_template_theme($existing, $type, $theme, $path) {
    $items = array();
    $items['khai_bao_hoa_chat_node_form'] = array(
        'render element' => 'form',
        'template' => 'khai-bao-hoa-chat',
        'path' => drupal_get_path('module', 'module_template'),
        );
    return $items;
    }

Why I  can not get value of $form_state['value']['ma_so_thue'] in module_template_form_alter(&$form, &$form_state, $form_id) when form submited?

The code you are showing is wrong for two reasons:

hook_form_alter() is invoked for every form Drupal is showing; this includes Drupal core forms, as well as forms implemented by third-party modules. It is not invoked for the forms of your own module. So, you first need to check for which form the hook is being invoked, then you can access the form fields the form of your module is using.
hook_form_alter() is not invoked when the form is submitted, but before the form is rendered. So you cannot use $masothue = $form_state['values']['ma_so_thue']; there. You need to add a new submission handler from hook_form_alter(), and in that submission handler you can get the submitted values, but then you cannot alter the default value for a form field in a submission handler.


How to change search placeholder? So far I have tried this code in mytheme.theme:

function mytheme_form_search_block_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
    $form['keys']['#attributes']['placeholder'] = t('Custom wording');
}

And this one:

function mytheme_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id == 'search_block_form') {
    $form['keys']['#attributes']['placeholder'] = t('Custom wording');
  }
}

Also this one:

function mytheme_form_search_block_form_alter(&$form, $form_state) {
    $form['keys']['#attributes']['placeholder'] = t('Custom wording');
}

Site is not crashing, but nothing happens on the placeholder.

I have based these 3 snippets on these pages:

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Form%21form.api.php/function/hook_form_FORM_ID_alter/8.5.x
How to replace the search submit button with a Font Awesome character?

This code should create the placeholder:

function mytheme_form_search_block_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form['keys']['#attributes']['placeholder'] = t('The new placeholder');
}

So if that does not work for you, it might be because you need to clear the cache.


Count everytime a node it shown in view I have a view that show content of a specific content type, based on some exposed filters.

Each node is "owned" by a user, and i want to provide statistics for how many times their node have been shown in a view (not hov many times the node have been viewed fully).

Then i want to provide the owner of the node with statistics like:

Views today, X
Views last 7 days, X.
Views last 30 days, X.

Any smart ideas?

there is a module for that node view count, from module page:

  Node View Count module allows to count node views. Unlike statistics module, this module records each view of node with user uid and timestamp. So now you can know how many times a user viewed node by day, week, month and etc.

This module is integrated with Views module. You can use it to create different statistics pages, output new not viewed nodes for user and many more.


How do I create a time range form field? Is there any way to add time range input fields in a form, for example using code similar to the following one?

$form['notification_hours'] = array(
  '#type' => 'time_range', // type time_range doesn't work
  '#title' => $this->t('Notification hours:'),
  '#default_value' => $config->get('ecc_general.notification_hours'),
  '#description' => $this->t('what are the hours that messages should not be sent?'),
);

I have tried the Time Range and and Time Field modules. I'm able to add the time range field, but I failed to programmatically create it.

Haven't tested this but if you install time field module you then could do this to simulate a range:

$form['from'] = [
  '#type' => 'time',
  '#title' => 'from',
];
$form['to'] = [
  '#type' => 'time',
  '#title' => 'to',
];


Where can I find an exhaustive reference of the Views module I am new to the views module and am trying to get my head around how it works and what the possibilities are with it. Is there a resource, book, video tutorial, or site somewhere that does a good job of explaining the whole module from beginning to end?

This is an excellent tutorial: http://nodeone.se/blogg/taming-the-beast-learn-views-with-nodeone-0


Where does PEAR install Drush? I installed Drush using the PEAR option mentioned on the Drush project page, but I can't find the location of where it was installed.

Does anybody know the default installation location?

Specifically, I can't find the location of the drush.rc.php file to edit and add multiple sites to.

On Unix or OS X, you can use which drush to learn the location. On Windows, it is where drush from the command line.


Best way to log clicks on a link of a custom content type I have a custom content type (bundle, drupal 7) which has a link (rules link module) and I want to log the number of clicks on this link. At the moment I've an integer field in the bundle and I use rules to increment it and save the node every time the link is clicked.
I think this method is not efficient and has also security implications so I ask you suggestions on how to do it better.
I considered writing a small custom rule (module) which increment the value directly in the field table which probably would have less overhead but I think it would still not be very secure as I don't know how to handle a large number of clicks in a short time.
Thanks for any help.

A possible alternative to "record the clicking of such link" is to use the Message module to create a message like so:

Date = date the link was clicked.
User target = the user who clicked the link.
Message type = something like "Link of custom content type clicked".
Message text = whatever you want and possibly using "Replacement tokens" to have any of the tokens that you have available in your rule also included in your message text (should you have any such need).

Since messages are entities, you could add any additional fields you may need to complete such custom logging.

With this approach, you've reduced your question to (eg) creating an appropriate view (and/or chart?) of all such messages that got created.


How to force entity translations to load in a certain language with user_view() or entity_view() I have a custom view mode that uses a template to print out user profiles.

I am saving the HTML from this view mode in the Solr search index using Search API Solr.

In user--my-view-mode.tpl.php, I print out the various fields of the user profile, including one that is a taxonomy term that has been translated by the Entity Reference and Title modules:

  $agegroup = $user_profile['field_acc_age_group'][1]['#markup'];

In the Search API callback, I call this view mode like this:

$render = user_view($item, 'my-view-mode', 'ja');

Here's the problem-- the profile is rendered in Japanese except the taxonomy term, which has been translated by Entity Reference/Title.

When I make a view that shows output of Rendered User and set the view mode to my-view-mode, and access the view with a user who has the language set to Japanese, then the taxonomy term is translated correctly.

So how do I get user_view() or entity_view() to show translated entity translations along with the rest of the translated output?

So one workaround is to force it manually like this:

$agegroup = $user_profile['field_acc_age_group']['#items'][1]['taxonomy_term']->name_field[$lang][0]['value'];


Drupal substracts 2 hours from the CCK date field when saving. Why? I have defined a CCK field of the date type with an Hour granularity
it looks like this:

When I save it, it subtracts 2 hours from each one.

I think it is caused from the set timezone.

My current timezone is "Europe/Madrid."

  Mac-Pro:~ usuario1$ date
     martes, 13 de diciembre de 2011, 17:33:23 CET

The server's timezone is the same.

  Server:~ root$ date
     mar dic 13 17:32:43 CET 2011

Why is Drupal doing this?

The dates have to be the same just as I type them.

In Drupal 6 at least, you would go to admin/settings/date-time to check the default timezone of Drupal. I'd check to see if that's set correctly.  If it is, then you have to check if user configurable timezones are enabled, and if so, check what you or the logged in user has set in his/her account against all of the above.


local language variables to use in code for queries(NOT GLOBAL LANGUAGE) I'm building a site in multiple languages (Italian and English) and I would like to ask you to intervene on the code to add selections 'if' to my queries to the user's local language.
At first I place conditions using as a reference global $ language but I understand that it is wrong as it does for the whole site and not a single user.
I saw on the internet that you can use sessions but how do they do? I would also switch to change languages. I have no idea how to do.
I went in configurations -> REGIONAL AND LANGUAGE -> languages -> detection and selection .. here that I have to give exactly?
How should I do help me please!

If the user is logged in, you can the global $user variable. The language object is then $user->language. For an anonymous user, you can use a session variable or a cookie. There's a module to use cookies: Language Cookie

To use a session variable:
On the "Detection and Selection" configuration page, set "Session" as the first detection method. To set up the variable, click the "Configure" link on that page. You should see

Then you just need links to set the user's language. Something like

http://yoursite.com/?language=en and http://yoursite.com/it?language=it
at the top of the page.


How to add module to admin/config page? I'm working on a module in Drupal 7. I've added a hook_menu implementation:

$items['admin/config/content/mymodule'] = [
  'title'            => 'MyModule',
  'description'      => 'Configure MyModule settings.',
  'page callback'    => 'mymodule_get_form',
  'page arguments'   => ['mymodule_admin_settings'],
  'file'             => 'mymodule.admin.inc',
  'access arguments' => ['administer mymodule'],
  'menu_name'        => 'mymodule',
];

...and a configure line to mymodule.info:

configure = admin/config/content/mymodule

A Configure link for MyModule now appears the admin/modules page, but how can I also have the module listed on the admin/config page? Or is the admin/config page reserved for only core modules?

If you do it like this, with the system.module callback for the parent item, you get the nice listing page when you visit 'admin/config/mymodule'

/**
 * Implements hook_menu().
 */
function MYMODULE_menu() {

  $items = [];

  $items['admin/config/mymodule'] = [
    'title'            => 'My configuration section',
    'description'      => 'This is the parent item',
    'position'         => 'left',
    'weight'           => -100,
    'page callback'    => 'system_admin_menu_block_page',
    'access arguments' => ['administer site configuration'],
    'file'             => 'system.admin.inc',
    'file path'        => drupal_get_path('module', 'system'),
  ];

  // Need at least one child item before your section will appear.
  $items['admin/config/mymodule/item'] = [
    'title'            => 'First item',
    'description'      => 'This is the first child item in the section',
    'page callback'    => 'mymodule_item_callback',
    'access arguments' => ['administer site configuration'],
  ];

  return $items;
}


Does removing fields also removes submitted values? I just removed each fields of a form in order to update them. Sadly, I'm afraid it also removes all the associated values submitted, because when I navigate to the 'Result' tab, values are missing.
Is there any way to recover this?
How could I fetch the whole submissions despite the fact that some fields does not exists anymore?
EDIT: I've root access to the MySQL database (currently searching inside it)
Some unsuccessful attempts:
-- Enable to fetch submitted data associated to a submission identified by its node id

SELECT * FROM webform_submissions
JOIN webform_submissions.nid = webform_submitted_data.nid
WHERE webform_submissions.nid = 42;

> Empty set (0.00 sec)

-- Verify that node id actually exists: it does

SELECT * FROM webform_submissions WHERE nid = 42 LIMIT 1;

> +------+--------+-------+----------+------------+---------------+
> | sid  | nid    | uid   | is_draft | submitted  | remote_addr   |
> +------+--------+-------+----------+------------+---------------+
> | 2538 | 42     | 26261 |        0 | 1613557280 | IP.ADD.RE.SS  |
> +------+--------+-------+----------+------------+---------------+

-- Verify that some submitted data related to this node id are present

SELECT * FROM webform_submitted_data
WHERE nid = 42;

> Empty set (0.00 sec)
-- Has it been deleted ?

Assumption: it has been deleted and I'm in a bad trouble !

As webform elements are deleted, all related submission data is deleted.


How to transfer data from views-view-fields.tpl to views-view-unformatted.tpl in D7? I need to collect some data within views-view-fields.tpl, and then transfer it to  views-view-unformatted.tpl to do some magic to the whole data-object. How could I do that? Thnx!

You should use $view->result variable.

do dsm($view->result) and see if you find what you where looking for.


How to filter an already rendered calendar view of a specific date with categories (taxonomy terms)? I'm using the latest dev-versions of date/views/calendar/ctools to create an event calendar to display a variety of different events. These events are created with a content-type "event" and classified by a vocabulary (e.g. "movie" or "sport").

I have an already working block of the calendar (showing the current month by default and linking to the corresponding date). If i click on a date i have a list of every event on that date.

How can i reduce the results of that list through the taxonomy terms (movie, sport)?

Any hint or solution is very appreciated...

If your "list of every event on that date" is generated by Views, you can add a Filter to Views based on Taxonomy Term.  This can then either be exposed to the user so they can pick Movie or Sport - or you can select which one you want explicitly for them.

See selection options below - you'd likely want "Taxonomy: Term" (and you'd be doing this in the Filter - not Contextual Filter).


View mode theme name priority I have a theme set for view mode 'Teaser'. The theme name for this is named like this: node--teaser.tpl.php. So far so good.

Then I created content type 'something' and I would like to create a Teaser theme specific for my new content type 'something'. I have thus named my custom Teaser theme as node--something--teaser.tpl.php. I was expecting this more specific theme name to override theme node--teaser.tpl.php (broader, less specific), but it doesn't work that way. node--teaser.tpl.php has priority over node--something--teaser.tpl.php. Is this really the expected behavior for theme names priority? I would expect the more specific to 'beat' the less specific broader name.

Is it possible to force the more specific theme in template.php function theme_preprocess_node?

This page Drupal 7 Template (Theme Hook) Suggestions explains the topic.

To investigate for yourself:

Install Devel module. Add this bit of code to your theme's template.php file (check if the function does not already exist):

function MYTHEME_preprocess_node(&$variables) {
  dpm($variables);
}

Then inspect the theme_hook_suggestions key. It will look something like this:

This show the suggestions available. To convert it to a tpl.php file just convert underscores to hyphens and add the extension tpl.php.

You can also create your own suggestions by adding this code into preprocess_node:

if ($variables['type'] == 'article' && $variables['view_mode'] == 'teaser') {
  $variables['theme_hook_suggestions'][] = 'node__article__teaser";
}

Here I am checking for the view mode teaser and adding a theme suggestions based on that. You can check for other conditions as well and add your own suggestions as you please.

Some themes add their own suggestions so always inspect it with dpm() first.


How can I create a view page that takes taxonomy machine name and has depth? This question is a followup to How to load nodes that are associated with the child of a taxonomy term and refers to this answer in particular, but is standalone, so you need only visit those if you want more background.

I want to create a view that functions like the Taxonomy term view that comes with views with depth turned on in the contextual filter, but taking the term's machine name instead of tid as the contextual argument.

I have pathauto set up to alias /taxonomy/term/tid to /vocabulary/term, and I would like to override the page there with views to make it show nodes associated with the children of the term as well as the parent.

So if I had the following Taxonomy:

Vocabulary 1 (vocab_1)

Term 1 (term_1)

Term 2 (term_2)
Term 3 (term_3)

Term 4 (term_4)

Term 5 (term_5)

and nodes as follows:

Node 1 - Term 2, Term 5
Node 2 - Term 5
Node 3 - Term 3

A visitor to /vocab_1/term_1 should get a list that contains nodes 1 and 3 because they are associate with children of Term 1.

I haven't been able to figure out how to do that with the term machine_name as the contextual filter instead of the tid.

You can use the contextual filter Content: Has taxonomy term ID (with depth) without adding a Relationship.  Use this settings for the contextual filter:

When the filter value is NOT available: Provide default value
Type: Taxonomy Term ID from URL
Make sure Load default filter from term page is checked.

Please note: When you visit a pathauto destination path, in this case with a source of /taxonomy/term/% pointing at /vocabulary_name/term_name, drupal passes the source path as a query variable, and your view still uses the source path to gather information.  This means your path in the view should not change, it should stay as taxonomy/term/%


Is it ok to move the page-title outside of the content div? Or is there a better way? I've got a couple of blocks which I would like to appear above the main content area on one particular page...
These two blocks are sitting above 'Main page content' blocks in admin/structure/block.

After enabling the page titles to be displayed, I realised that this isn't going to work, because I still want the page title to be displayed ABOVE these two blocks. So in between these two blocks and the main page content.

Is it ok for me to modify the template so that the page-title is outside of the content div? Or is there a better way to solve this problem?

Use the Blockify module. It will create block for a lot of common drupal elements (including page title), so you can easily place them on a page with a UI, rather than hacking templates.


Display Entity Reference field twice, with different display modes I have a content type (Type A) that has an Entity Reference field to another content type (Type B).

Type B has 3 fields and 2 display modes. Display A shows two of the fields, Display B shows the other field.

In the display settings for Type A, the display mode for the Type B entity is set to Display 1.

On the template for Type A, I can use {{ content.field_type_b }} and the two fields are shown.

Now, I want to be able to output the field again, but as Display 2, in a different part of the template.

In a pseudo twig code way, I'd imagine something like {{ content.field_type_b|display_mode('display_2') }}

I have heard suggestions for Display Suite, but I tried this and it seems whilst you can clone a field, there is no option to render it as an entity with a display mode.

I also found Twig Tweak, which I think might work, however, the documentation is beyond terrible and I cannot see how I'd actually use it (the cheat sheet lacks all manner of help).

If this is not possible in Twig, could this be achieved in a hook? Bearing in mind, the field I want to render in Display 2, is a nicely rendered map, so I don't want to simply get the field value, it has to be using the display mode.

How to display a reference field twice with the help of EVA:

Install EVA.
Add a new View.
Add a display "EVA".
Add the Entity Reference field to FIELDS and configure the Formatter to "Rendered entity" and set the view mode Display 2.
The EVA display includes the section ENTITY CONTENT SETTINGS, choose the entity type Content and bundle Type A.
In the ADVANCED section add a contextual filter for Content: ID.
Save the View.
Now the new field is visible in the field UI of the content type Type A and you can drag'n'drop it to the final position.


Core Updates after install with composer create-project drupal/drupal So I installed Drupal with
composer create-project drupal/drupal <...>

It works fine, but now I'm trying to update core from 8.4.1 to 8.4.4
What's the right way to do that? composer update only updates the modules, not core.
How do I update core? I don't know that much about composer, but if I edit the composer.json and remove

"replace": {
    "drupal/core": "^8.4"
},

and add

"require": {
    "drupal/core": "^8.4",
    ...
 }

it seems to work.
Is this the right way to do this? If so, why is this not in the default composer.json, that comes with the project?

You do in fact want to remove the drupal/core declaration (as it exists) in the replace section of composer.json, and then add the entry as you noted to the require section.  Then run composer update drupal/core --with-dependencies.

You can find Drupal's official process for a Core upgrade with composer here: https://www.drupal.org/docs/8/update/update-core-via-composer-option-4


How to show drupal menu in drop down? I am trying this code

   echo "<select>" .$main_nav = menu_tree('secondary-links');

            print"<option>"     .    $main_nav   . " </option></select>";<br>

but it display all menu at ones

It looks like you're building a so-called "jump menu", is that correct?

It's not considered good practice to code a menu into a template like you're doing in your example. Try to build the functionality of your site with modules (existing ones, or custom) and use the theme (template.php, CSS files, template files) for appearance only.

If you need a jump menu, have a look at the Jump module. It provides a block for every top-level menu and every vocabulary, so it could get you exactly what you need without writing one line of code.


Different in theme as table and page I am studying the pager_example in example module.

When creating an render array, it first assign #theme as 'table'. But it assign the #theme as 'pager' just before returning.
What is the purpose of attach the pager theme ?
pager_example.module:

// Create a render array ($build) which will be themed as a table with a
// pager.
$build['pager_table'] = array(
  '#theme' => 'table',
  '#header' => $header,
  '#rows' => $rows,
  '#empty' => t('There are no date formats found in the db'),
);

// attach the pager theme
$build['pager_pager'] = array('#theme' => 'pager');  <---- why need this ?
return $build[];

Then I remove the coding "$build['pager_pager'] = array('#theme' => 'pager');". The result is the same.
When compare to tablesort_example.module, it don't have attach the pager theme before the return.
tablesort_example.module:

// build the table for the nice output.
$build['tablesort_table'] = array(
  '#theme' => 'table',
  '#header' => $header,
  '#rows' => $rows,
);

return $build;

The code $build['pager_pager'] = array('#theme' => 'pager'); returns the pager for the table.

The example module output with that line of code:

The example module output without that line of code:

If you are not seeing the same difference I am, it might be a cache issue, try clearing your cache between changes.


How long will the previous core version supported? I want to start a new project at the beginning of 2018 but I don't know if it is better to start this project with Drupal 7 or Drupal 8. Actually, I am not familiar with Drupal 8 coding and template engine.

Even though there are lots of modules that aren't available in Drupal 8 right now, such as admin menu, Date Converting module and others, I finally decided to start my project with Drupal 7, but the point that disturbs me is not knowing how long Drupal 7 will be supported. Is it 2020, 2021, or later?

Drupal 7 is currently on LTS.
  Drupal 7 LTS will end when Drupal 8 enters LTS, at which point Drupal 7 enters security fixes only mode.
  Drupal 7 security fixes only mode ends when Drupal 8 enters security fixes only mode, and Drupal 9 enters LTS.
  Essentially: Drupal 7 won't be EOL before development has started on Drupal 10.

Source: Has the EOL (end of life) for Drupal 7 been announced?

The simple answer is: We don't know, yet, exactly.

Check out the following articles:

When is Drupal 7 End-of-Life?
Understanding the Drupal 8 and 9 Release Cycle.

  Drupal 7 will likely get bug-fixes until October 2017, and official
  security support until 2019 or 2020 at least.


When to create a new content type? This question always comes up when I need to design a structure for data. When should I create distinct content types and when should I differentiate between nodes based on custom fields.

For example, say I have a gallery of people and a gallery of places. they differ only by one field that i use in the people gallery and not in the places gallery. in code i can easily know when it's people or places based on this field.

this is just one example from the top of my head. i'm asking for general guidelines, and not a solution to this specific problem.

these are the points i've come up with to help decide between different content types or different fields:

what are the chances one node will need to change type (people gallery suddenly becoming places gallery)?
how much do the fields differ?
how much you will need to create view with both types or with a single one?

any more thoughts?

It's a really open question, but I'll try to help you a bit.

Basic example is : I have to create "vehicules", some "cars" and some "motos". Should I create one content type (CT) with one field "type" (with "cars" and "motos" as available values") or 2 CTs "cars" and "motos".

Here is the points I look into before choosing:

fields: if the fields are the same between content types, just create one CT, if they're really different, then create 2 CTs.
display: if the display is the same, then chose 1 CT, if not, create 2 CTs.
views: will I make list of both CTs, or will they always be separated?
cross content: is it possible that a node is part of both CTs? For example, is a "can-am spyder" a moto, a car or both of them? If you have cross content, then I would suggest to have only one CT, which a multiple select for the "Type" attribute. So people searching for cars or for motos will find the spyder anyway.
how "smart"/involved are you Back-Office users? Usually when you choose to keep only one content type, you end up having a lot of extra fields to configure the theming, the little differences between your different types, etc. So the edit form can be really long and confusing. If you're the one configuring everything, that's fine. But if you need to explain the form to a lot of editors/contributors, this can be painful.

After counting the pro and cons, you can make your decision.
Usually, I give 2 points for "fields" and "display", one point for "views", "cross content" and BO users... Make the sum and decide :)


How to filter entities in View by all of their taxonomy term reference fields? Let's say I have a custom entity that has two taxonomy reference fields: categories and tags. And I want to display all entities that have taxonomy term with id 1. The term is a dynamic value(contextual filter) so it can be either the category or tag.

How can I do that in Views? Right now I can filter categories or tags separately but I need to filter both of them.

If I use two filters they will cancel each other because each of them have, in my case, "Display contents of "No results found"" set.

You can get an argument from url with views.

Use Provide default value in the contextual filter.

Another way (in drupal 7)would be to use this module: https://drupal.org/project/views_url_path_arguments


Rendering node contents only For the purposes of the Cycle plugin I need to render a node without any external buildup, just the $content. Is that possible?

In Drupal 7, node_build_content() governs the generation of the render array for the node's content:

$node = node_load(1);
$content = node_build_content($node);

If you take a look at the source for it, you can see how the final render array is built and you can pick and choose what you want in the render array by copying the relevant parts from node_build_content().

For example, if you wanted to just render the node's fields, you might do:

$view_mode = 'full';
$langcode = LANGUAGE_NONE;

$node->content = array();

field_attach_prepare_view('node', array($node->nid => $node), $view_mode, $langcode);
entity_prepare_view('node', array($node->nid => $node), $langcode);
$node->content += field_attach_view('node', $node, $view_mode, $langcode);

If you did that, $node->content would then contain the render array for just the fields without all the extraneous stuff like links or other stuff third-party modules might add.


How do I format the display and submission format of a datetime field in a custom composite? on a Drupal 8 webform, I have a datetime entry which works fine and I can format it in settings. When I create a custom composite with a datetime in it, I don't have the same formatting options as before. For example, I cannot pick a display or submit format for the date.

I could create a module to hook onto the submission and alter it that way or, presumably, I could do this in the email submission with tokens. (I have not tried that yet.) That would only affect the submission and not the display, though.

How do I format the display and submission format of a datetime field in a custom composite?

For defining the format of the DateTime field you can use CUSTOM COMPOSITE SETTINGS.

Example: To set the format to datepicker like a normal date field, set datepicker: true
inside the custom text field for the respective composite DateTime element. All other properties can be added here.

You can checkout the JSON representation of the respective property from the source option of the webform. Copy-pasting the properties inside the custom composite setting is all needed.

To set the submission format:

Go to Advance option of the composite element > Under submission display fieldset select the way you want to display the items.


Test a settings form that displays a queue I'm trying to write a test on a settings form. The module uses a queue, and the settings form displays the items in the queue like so:

When I extend the test class from WebTestBase I get:

Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'mskcc_local_d8.test73723996queue' doesn't exist: SELECT COUNT(*) AS expression FROM (SELECT 1 AS expression FROM {queue} q WHERE name = :db_condition_placeholder_0) subquery; Array ( [:db_condition_placeholder_0] => google_analytics_counter_worker ) in Drupal\google_analytics_counter\GoogleAnalyticsCounterManager->getCount() (line 635 of modules/contrib/google_analytics_counter/src/GoogleAnalyticsCounterManager.php).
Drupal\Core\Database\Statement->execute(Array, Array) (Line: 625)
Drupal\Core\Database\Connection->query('SELECT COUNT(*) AS expression
FROM
(SELECT 1 AS expression
FROM
{queue} q
WHERE name = :db_condition_placeholder_0) subquery', Array, Array) (Line: 87)
Drupal\Core\Database\Driver\mysql\Connection->query('SELECT COUNT(*) AS expression
FROM
(SELECT 1 AS expression
FROM
{queue} q
WHERE name = :db_condition_placeholder_0) subquery', Array, Array) (Line: 510)
Drupal\Core\Database\Query\Select->execute() (Line: 635)
Drupal\google_analytics_counter\GoogleAnalyticsCounterManager->getCount('queue') (Line: 134)
Drupal\google_analytics_counter\Form\GoogleAnalyticsCounterSettingsForm->buildForm(Array, Object)
call_user_func_array(Array, Array) (Line: 514)
Drupal\Core\Form\FormBuilder->retrieveForm('google_analytics_counter_admin_settings', Object) (Line: 271)
Drupal\Core\Form\FormBuilder->buildForm('google_analytics_counter_admin_settings', Object) (Line: 74)
Drupal\Core\Controller\FormController->getContentResult(Object, Object)
call_user_func_array(Array, Array) (Line: 123)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}() (Line: 582)
Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) (Line: 124)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext(Array, Array) (Line: 97)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}() (Line: 151)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 68)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 57)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 99)
Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 78)
Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 50)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 664)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

which tells me that the queue table is missing from the automated test environment.

But when I extend the test class from KernelTestBase and add

// These additional tables are necessary because $this->cron->run() calls
// system_cron().
$this->installSchema('system', ['key_value_expire']);

$this->connection = Database::getConnection();
$this->cron = \Drupal::service('cron');

to setup(), I assume my automated testing environment will contain a queue table (still to be determined). But the methods I regularly use to test a form, like $this->drupalGet and $this->assertResponse will now be not found.

How can I test a settings form that displays the contents of the queue table?

Thanks

A functional test satisfies both requirements.

<?php

namespace Drupal\Tests\google_analytics_counter\Functional;

use Drupal\Component\Utility\SafeMarkup;
use Drupal\Tests\BrowserTestBase;

/**
 * Tests the google analytics counter settings form.
 *
 * @group statistics
 */
class GoogleAnalyticsCounterSettingsTest extends BrowserTestBase {
  const ADMIN_SETTINGS_PATH = 'admin/config/system/google-analytics-counter';

  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = ['google_analytics_counter'];

  /**
   * A test user with administrative privileges.
   *
   * @var \Drupal\user\UserInterface
   */
  protected $adminUser;

  /**
   * Verifies that the google analytics counter settings page works.
   *
   * @see MediaSourceTest for good example code.
   */
  public function testForm() {
    $admin_user = $this->drupalCreateUser(array(
      'administer site configuration',
      'administer google analytics counter',
    ));
    $this->drupalLogin($admin_user);

    // Create item(s) in the queue.
    $queue_name = 'google_analytics_counter_worker';
    $queue = \Drupal::queue($queue_name);

    for ($i = 1; $i <= 5; $i++) {
      $queue->createItem(['type' => 'fetch', 'index' => 'boogie' . $i]);
    }

    $this->drupalGet(self::ADMIN_SETTINGS_PATH);
    $this->assertResponse(200, 'Access granted to settings page.');

    // Assert Fields.
    $settings_fields = $this->getAdminUserSettingsFields();
    foreach ($settings_fields as $field_name) {
      $this->assertField($field_name, SafeMarkup::format('@field_name field exists.', ['@field_name' => $field_name]));
    }

    // Cron Settings.
    $edit = [
      'cron_interval' => 0,
      'chunk_to_fetch' => 5000,
      'api_dayquota' => 10000,
      'cache_length' => 24,
    ];

    // Enable counter on content view.
    $this->drupalPostForm(self::ADMIN_SETTINGS_PATH, $edit, t('Save configuration'));
    $this->assertRaw('The configuration options have been saved.');
  }

  /**
   * Returns a list containing the admin settings fields.
   */
  protected function getAdminUserSettingsFields() {
    return [
      'cron_interval',
      'chunk_to_fetch',
      'api_dayquota',
      'cache_length',
      'queue_time',
      'start_date',
      'advanced_date_checkbox',
      'fixed_start_date',
      'fixed_end_date',
    ];
  }

}


Can I define the minimum php version for my module in my .info.yml file? I need to define the minimum PHP version in my module.info.yml file but I don't know if this is posible using:

php: 5.6

If you search about this in the drupal.org documentation you will only see the reference about this in the theme.info.yml file: Defining a theme with an .info.yml file

  php (optional)

  The minimum version of PHP required. Defaults to value
  of DRUPAL_MINIMUM_PHP constant.

  php: 5.5.9

But in the documentation about the module.info.yml file there is nothing about the php version: Let Drupal 8 know about your module with an .info.yml file.

So, really I can't define the minimum php version in my module.info.yml file?

Sometimes the answer to a question is best found by trying. If you add php: 8.0 to your module.info.yml file you will see this:

So it can still be used. (I have updated the linked documentation as well.)


Enable clean urls drupal 7.56 / nginx - check failed I have an issue with the clean urls check. When I test there is an error in the Nginx log:

2017/10/06 09:49:01 [error] 468#468: *199 open()
"/usr/share/nginx/html/drupal-7/admin/config/search/clean-urls/check" failed
 (2: No such file or directory), client: 192.168.1.254, server: localhost,
 request: "GET /drupal-7/admin/config/search/clean-urls/check HTTP/1.0",
 host: "localhost".

I don't know if it is a nginx problem or a Drupal problem.

update : i change some things in the nginx.conf now i have an error in the log of nginx :
2017/10/14 21:55:08 [error] 4804#4804: *1 directory index of "/usr/share/nginx/html/drupal-7/" is forbidden, client: 192.168.1.254, server: localhost, request: "GET /drupal-7/?q=admin/config/search/clean-urls HTTP/1.1", host: "localhost".
Here is my nginx.conf :

http {
include       mime.types;
default_type  application/octet-stream;

#log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
#                  '$status $body_bytes_sent "$http_referer" '
#                  '"$http_user_agent" "$http_x_forwarded_for"';

#access_log  logs/access.log  main;

sendfile        on;
#tcp_nopush     on;

#keepalive_timeout  0;
keepalive_timeout  65;

#gzip  on;
# set client body size to 200M #
client_max_body_size 200M;

server {
    listen 443 ssl http2;
    server_name toniozz75.fr;
    root /usr/share/nginx/html;
    index index.html index.htm;

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

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

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

location ~ \.(php|html|htm)$ {
         root           /usr/share/nginx/html;
         fastcgi_pass   unix:/run/php-fpm/php-fpm.sock;
         fastcgi_index  index.php;
         try_files $uri $uri/ /index.php?$args;
         include        fastcgi.conf;
    }

You are missing some configuration for clean URLs. Try adding this snippet above the location @rewrite snippet.

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


Problem in sending mail with attachement I'm coding a small module allowing to send mail to new users with an attachement file as pdf. This pdf include all subscription details of the user.

I generated the pdf file using FPDF and I put it (temporary) in DRUPAL_ROOT and I used two ways to send the mail:

1) Using the hook_mail_alter:

function aos_user_pdf_mail_alter(&$message) {
  if($message['id']=='user_register_pending_approval') {
    $attachment = array(
     'filecontent' => file_get_contents(DRUPAL_ROOT . '/' . 'yourfilename.pdf'),
     'filename' => 'yourfilename.pdf',
     'filemime' => 'application/pdf'
    );
    $message['params']['attachments'][] = $attachment;
  }
}

2) Or creating a custom function:

function aos_user_pdf_send_mail ($mail, $uid) {
  $user = user_load($uid);
  $to = $mail;//gets the current user's mail address
  $from = variable_get('site_mail', ''); //admin's mail address
  $body = 'This is a test mail';
  $subject = 'Your pdf';
  $attachment = array(
    'filecontent' => file_get_contents(DRUPAL_ROOT . '/' . 'yourfilename.pdf'),
    'filename' => 'FILE',
    'filemime' => 'application/pdf',
  );
  $message = drupal_mail('aos_user_pdf', 'message_key', $to,
    user_preferred_language($user),
    array(
      'body' => $body,
      'subject' => $subject,
      'attachment' => $attachment),
      $from,
      TRUE
    );
}

Unfortunately the mail is sent, but without the attachement, Please can you show me where's my mistake or an alternative way to do the job.

For sending mail with attachment you should use Mail System and Mime Mail module
Attachment functionality is built into the Mime Mail module.

After that you must set up drupal_mail() to use mime mail as the mail system interface. This is where the mail system module comes into play. The module is pretty straightforward, and lets you set a different mail system per module. There is a straightforward configuration at admin/config/system/mailsystem where you create a new setting for your module, and select mime mail as the mail system.

Assing anttatcment in variable

$message['params']['attachments']

After that you will be able to send mail with attachment.

For more information visit here


CSS not applied on install, but loaded properly I have installed Drupal 8, but the default CSS is not applied (see http://ec2-54-187-215-79.us-west-2.compute.amazonaws.com/user/1 for example).

Chrome's 'inspect' functionality reveals that the CSS is loaded properly from http://ec2-54-187-215-79.us-west-2.compute.amazonaws.com/sites/default/files/css/css_4w6DyMZOD_Fu1oxqpACBFcOPDgVYtgOuayu9S6-8btc.css?0

What is causing this issue? How can I solve it?

When you installed it, for Installation Profile, did you select Standard? or did you select Minimal?

It seems like you selected Minimal, which I highly do not recommend, Standard is the way to go. Delete all the tables in your DataBase and go to http://ec2-54-187-215-79.us-west-2.compute.amazonaws.com/install.php and install again.


Import date to Drupal I am receiving data from a third party company through XML.
I want to add this to my website as drupal nodes, having some information like title, body, summary, image,...

I am able to make a cron job that reads all the data from the XML & write it to a database.

Now I was wondering:

Can I write this to the database directly without creating any inconsistenties?
What tables do I have to write this to? only the node table and the field_data tables? Or do I also have to add it to field_revision tables etc? Am I forgetting any others?
Is there a module that's doing this? I tried the Feeds & the Migrate modules, but I can't seem to find anything to set up XML or SQL Data import on those. Either of the 2 is fine, whether it goes directly from the XML, or if I have to import it from SQL, cause then I can just add them to a temp table first.

Thank you very much

Can I write [the external data] to the database directly without creating any inconsistenties?

Hypothetically, yes. On a practical level, I'd avoid this approach like the plague. For example, in your next question, you ask…

What tables do I have to write this to? only the node table and the field_data tables? Or do I also have to add it to field_revision tables etc? Am I forgetting any others?

Thanks for the segue. Why not use Drupal's Feeds module to consume your data and let Drupal and Feeds manage the consumption process? This will ensure all the data modeling, processing, security and coding best practices inherited by the larger community. Why would you bypass all the work that's gone into this development?

Is there a module that's doing this? I tried the Feeds & the Migrate modules, but I can't seem to find anything to set up XML or SQL Data import on those. Either of the 2 is fine, whether it goes directly from the XML, or if I have to import it from SQL, cause then I can just add them to a temp table first.

As ar7Max indicates, you can use the Feeds and Feeds XPath Parser. It's stable, mature and has a large user base. We rely on this combination heavily (50+ sites, 100's of specific feeds imports) mostly without a hitch. The hitch tends to be poorly formed XML output which can break an import — again, this is rare and addressable at the source OR using Feeds Tamper. where you can rewrite the XML data as needed. If you wish, ask your XPath Parser specific questions here — once you understand it, it's trivial to manage.


Translatable image field gets replaced when adding content I have added an image field with Translatable Content enabled. My content type has enabled translations too. But when I add an image in the translation, the english contents field get replaced with the newly added translated image. (English is my base language, and I have Japanese and Chinese as translations). This happens vise versa too. What could be the issue?

By default only the image alt and title are translatable and the file itself isn't. By the default the file is always the same in all languages. You can simply make the file to be translatable as well under https://example.com/admin/config/regional/content-language.

Note: After you've done this, all your existing translations will need to have the file re-uploaded (or a new file uploaded), as the default only gets added once when translating content through the UI.

Taken the above Hero image field this can be done manually be editing field.field.node.page.field_hero_image.yml (which translates to field.field.ENTITY_TYPE.BUNDLE.FIELD_NAME.yml):

Before file checked:

third_party_settings:
  content_translation:
    translation_sync:
      alt: alt
      title: title
      file: '0'

After file checked (alt and title are mandatory if file is checked, that's why they have '0' now):

third_party_settings:
  content_translation:
    translation_sync:
      file: file
      alt: '0'
      title: '0'


Internet Explorer 7 transparency fix I have a menu that has a transparent background with the following CSS:

background-color: transparent;
background-color: rgba(113,157,174,0.7);
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#99dddddd,endColorstr=#99dddddd);
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#99dddddd,endColorstr=#99dddddd)";

In IE, it doesn't have any color; it is just white. I used an Internet Explorer fix, in which I used the following code:

filter: alpha(Opacity=45);
background-color: #0010A5;
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#99dddddd,endColorstr=#99dddddd);
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#99dddddd,endColorstr=#99dddddd)";

The only thing this did was to make it purple, but it wasn't transparent at all.

![screenshot][1]

I know it is possible because I've seen it done before. What am I doing wrong? How do I fix it?

I found the answer, it was in fact filter: alpha(Opacity=45); inside the IE fix, but apparently it needed to be in the -inner of the class, instead of the regular class.


Reload page after applying commerce coupon I'm quite obsessed on one page checkout using drupal commerce kickstart. I'm using commerce coupon(wonderful module) and we all know that there's a possibility that the order total price could be zero if you we apply a 100% coupon module. I see this post Commerce - how to set no payment for free orders when 100% coupon applied and I guess we are having the same problem. I did not see any way to ajax refresh the payment method pane, and my last work around is to reload the entire page after applying coupons.

Is there a way to reload the entire page after applying coupons?

Thanks.

One solution here is to add a custom JS behavior to your module that looks for the AJAX callback context of applying a coupon. Upon such context, you can refresh the page or update the DOM as you see fit.

(function ($) {
Drupal.behaviors.mymodule = {
  attach: function (context, settings) {

    //Look for the context of a coupon form AJAX callback
    //If there's no error message, assume successful coupon application
    if($(context[0]).attr('id') == 'commerce-checkout-coupon-ajax-wrapper' && !$(context[0]).find('.messages').hasClass('error')) {
      //@TODO: Reload page or other JS to refresh coupon usage
    }
  }
};
}(jQuery));


External URL Redirect Breaking Image Links I was recently hired to manage an existing Drupal 7 site (built with an Omega subtheme) and am doing my best to ramp up quickly. Unfortunately, I do have some fires to put out immediately and could really use some help. The website has redirects coming in from another hosting provider/domain manager. For example, www.oldsite.com is being redirected to www.currentdrupalsite.com (currentdrupalsite.com being the site that I am managing) from a different host than the one that the current Drupal site is being hosted on. This redirect is breaking my image links, specifically the logo.

So, the img src path is http://oldsite.com/sites/all/themes/themename/logo.png instead of http://currentdrupalsite.com/sites/all/themes/themename/logo.png.

Can I fix this through the Drupal interface?

A redirect from the old site to the new should not affect how the page is rendered on the new unless some absolute paths are hardcoded in the template files.

First check the value of $base_url in the settings.php.
If that is correct (or just commented out) check the code of your theme's template files.


.gitignore file setup for Acquia Cloud I want to add .gitignore file to my local repo. My local repo is a clone from my Drupal 8 distro from Acquia Cloud.

What are best practices for my .gitignore file for Acquia Cloud hosted sites? I followed this tutorial.

For example: do i have to ignore settings.php and not settings*.php? Regarding this quote from the tutorial:

  Drupal 8 You can modify .gitignore so that it ignores settings.php
  (not settings*.php). Then, you can update the standard settings.php
  with the Drupal 8 local settings file checker:

Where is settings.local.php for, mentioned in the Quote above from the article?

Currently my .gitignore file looks like this:

# This file contains default .gitignore rules. To use it, copy it to .gitignore,
# and it will cause files like your settings.php and user-uploaded files to be
# excluded from Git version control. This is a common strategy to avoid
# accidentally including private information in public repositories and patch
# files.
#
# Because .gitignore can be specific to your site, this file has a different
# name; updating Drupal core will not override your custom .gitignore file.

# Ignore core and vendor when managing dependencies with Composer.
# core
# vendor

# Ignore configuration files that may contain sensitive information.
sites/*/settings*.php
sites/*/services*.yml

# Ignore paths that contain user-generated content.
sites/*/files
sites/*/private
sites/*/files-private

cache/
files/

# Ignore SimpleTest multi-site environment.
sites/simpletest

# If you prefer to store your .gitignore file in the sites/ folder, comment
# or delete the previous settings and uncomment the following ones, instead.

# Ignore configuration files that may contain sensitive information.
# */settings*.php

# Ignore paths that contain user-generated content.
# */files
# */private

# Ignore SimpleTest multi-site environment.
# simpletest

# Ignore default text files
/CHANGELOG.txt
/COPYRIGHT.txt
/INSTALL*.txt
/LICENSE.txt
/MAINTAINERS.txt
/UPGRADE.txt
/README.txt
sites/all/README.txt
sites/all/modules/README.txt
sites/all/themes/README.txt

# ------------------------------------------------------------------------------
# SublimeText files
# ------------------------------------------------------------------------------

# Workspace settings.
*.sublime-workspace

# Project settings.
*.sublime-project

# ------------------------------------------------------------------------------
# OSX
# ------------------------------------------------------------------------------

# Common OSX files.
.AppleDouble
.DS_Store
.LSOverride

# Thumbnails.
._*

# Files that might appear in the root of a volume.
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns

# Directories potentially created on remote AFP share.
.apdisk
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items

# ------------------------------------------------------------------------------
# Windows
# ------------------------------------------------------------------------------

# Windows image file caches.
ehthumbs.db
Thumbs.db

# Folder config file.
Desktop.ini

# Recycle Bin used on file shares.
$RECYCLE.BIN/

# Windows Installer files.
*.cab
*.msi
*.msm
*.msp

# Windows shortcuts.
*.lnk

# ------------------------------------------------------------------------------
# Linux
# ------------------------------------------------------------------------------

# Tilde files.
*~

# KDE directory preferences.
.directory

# Linux trash folder which might appear on any partition or disk.
.Trash-*

What do i have to change to make it perfect?

Acquia Cloud provides you with a default .gitignore in your repository (as described here):

docroot/files
docroot/sites/*/files
docroot/sites/*/private
acquia-files

It usually is enough for the vast majority. You're however free to add anything you don't wish to keep under version control. There's no perfect setup and it really depends on what you'd like to achieve. I strongly suggest keeping settings.php under version control because it holds critical configuration for your site.


How can I change a field cardinality? I have two content types: Person and Office with existing content. The Person content type has an entity reference field to Office nodes, which only allows a single reference. I need to change this to allow an unlimited number of Office nodes to be selected.

Drupal 8 prevents changing the cardinality of the field, and it gives the following error message.

  There is data for this field in the database. The field settings can no longer be changed.

At first, I thought I needed to write a migration, but they seem to be aimed at bringing data into a Drupal instance. Then, I read about writing update functions (also this documentation).

I discovered a migrate-plus plugin that adds a couple pages me to export the field storage settings, change the cardinality, and re-import the settings.
Given that I'm going from cardinality of 1 to unlimited, I could imagine this change wouldn't destroy data. And my empirical data suggests this is the case. I've now made this change via the migrate-plus screens as well as via configuration export and import and the data is still in the field.

Is this a safe operation, or should I write an update function?

There is data for this field in the database. The field settings can no longer be changed.

That message is misleading, it will actually not limit the ability to increase the cardinality. The only limitation is that it won't allow you to set the cardinality to a value lower than the highest amount of items you currently have.


Insert node title in the message sent by contact form I'am looking for a way to insert a node title to mail message sent by contact form in Drupal 8.

A contact form is inserted into my node as a field. It is used on each node to receive mail from users. But I need to specify what node the email was sent with.

I use MYMODULE_mail_alter to format mail message. How can i insert node title to mail subject and body?

Or is it possible to get node title in MYTHEME_form_alter ?

The current node is available from the route match, \Drupal::routeMatch()->getParameter('node'). Make sure it really is an instance of NodeInterface before you continue or check the route name.

Then it's easy to use $node->getTitle() as the default value for the subject of the contact form. Depending on what you want to do, you can then also hide the subject field.


writing form action path programmatically Here is a custom user login form by Overriding the template. But can't understand how to print the destination/action path on the form. here is my code:

  block--user--login.tpl.php

<form accept-charset="UTF-8" id="user-login-form" method="post" action="/node?destination=node">

  Username *
  <input type="text" class="form-text required" maxlength="60" size="15" value=""     name="name" id="edit-name">

  Password *
  <input type="password" class="form-text required" maxlength="60" size="15" name="pass" id="edit-pass">

  <input type="submit" class="form-submit" value="Log in" name="op" id="edit-submit">

Create new account

Request new password

<input type="hidden" value="<?php print $elements['form_build_id']['#value']; ?> "     name="form_build_id">
    <input type="hidden" value="user_login_block" name="form_id">

</form>

Here we are using a default path like action="/node?destination=node" its really a bad idea..So i want to print the action path programmatically.. Any idea?
This maybe an idea: <?php print $elements['actions']['#the_path']; ?>

The action is stored in the form's #action property, so assuming your form is represented by the $elements variable in the template, something like this should do it:

<form accept-charset="UTF-8" id="user-login-form" method="post" action="<?php echo $elements['#action']; ?>">