How can I count the number of nodes submitted by the current user? I want to expose in a block the number of content type published by the current user.
I know we can write a query, but is there any other method to do it?

You can use the Views module to do this.

Create a new view
Remove sort options, fields and other default settings
Add a field for "Content: Type"
Expand the "advanced" part on the right and set "Use aggregation" to "Yes"
Add yet another field for "Content: Type"
On the second "Content: Type" field, click "Aggregation settings"
Set the aggregation type to "count"
The second "Content: Type" should now look like "COUNT(Content: Type)"

THIS IS NOT MY SOLUTION LOOK HERE: Count of nodes by type


Why am I getting this error? I am getting this error.

  Call to undefined function feeds_node_prepare() in dkan_datastore_node_update() (line 307 of /dkan/dkan/profiles/dkan/modules/dkan/dkan_datastore/dkan_datastore.module).

What could be causing the error? Could it be a module interfering with function?

This issue is referenced in Dkan developpers Google group.

You probably have updated Feeds modules in Dkan profiles folder? Read the above post carefully and consider trying proposed solution :

Keep the Dkan profile original code in place
Download Feeds 7.x-2.0-beta4 to sites/all/modules/contrib
Rebuild registry

EDIT : I browsed both Feeds and Dkan feeds.module history. I couldn't find any implementation of feeds_node_prepare() in Feeds, while Dkan contrib feeds.module does implement it.

Seems that Feeds in DKAN profile contrib modules directory is a fork, not official release.


What could cause remote drush commands to fail with ssh errors when ssh works in all other cases? I have public and private ssh keys on all of my three servers (dev, UAT, & production) so I can log in remotely, or from one to another.  Everything is working perfectly for the ssh and scp commands.

It does not work, however, for Drush.  If I execute drush @dev status from UAT, for example, I get the server's banner saying the system is "to be used by authorized users only blah blah blah", and then I get

  Permission denied (publickey,password,keyboard-interactive).

My ~/.drush/aliases.drushrc.php file contains:

# Development #
$aliases['dev'] = array(
  'uri' => 'http://default',
  'root' => '/var/www/vhosts/dev.www.company.com/current/',
  'remote-host' => 'companya0.company.com',
  'remote-user' => 'myusername'
);

# UAT #
$aliases['uat'] = array(
  'uri' => 'http://default',
  'root' => '/var/www/vhosts/uat.www.company.com/current/',
  'remote-host' => 'companyc6.company.com',
  'remote-user' => 'myusername'
);

# Production #
$aliases['prod'] = array(
  'uri' => 'http://default',
  'root' => '/var/www/vhosts/www.company.com/current/',
  'remote-host' => 'companyc1.company.com',
  'remote-user' => 'myusername'
);

ONLY Drush has any problem using my ssh keys.
What could be preventing it from working?

Put this line in your drushrc.php file:

$options['ssh-options'] = '-o PasswordAuthentication=no -i /home/YOURUSERNAME/.ssh/id_rsa';

This will cause Drush to pass these options along to ssh any time it calls your remote system, so you can continue to call Drush via sudo, and still use your login user credentials.


Active user account after administration's confirmation How to, by using module Profile2 Registration Path, the user's account becomes active after it is activated by the administrator. The administrator should get email when user creates new account.

I don't think you need a contrib module for that. You can set " Visitors, but administrator approval is required" under "Who can create accounts" on admin/config/people/accounts.

As for sending e-mail, create an advanced action at admin/config/system/actions and then set it on admin/structure/trigger/user to be triggered by account creation.

The core Action and Trigger modules are all that are required for that.


How do I install Drupal with a custom language? I know I can install a new Drupal web site with:

drush dl drupal --drupal-project-rename=[project]
cd [project]
drush site-install standard \
    --db-url='mysql://[db_user]:[db_pass]@localhost/[db_name]' \
    --site-name=Example

But how can I install Drupal 8 with some custom language, let's say italian, using Drush?

Seems this works fine:

$ drush si standard \
    --db-url='mysql://[db_user]:[db_pass]@localhost/[db_name]' \
    --account-name=joe --account-pass=mom \
    --site-name=Example \
    --site-mail=noreply@example.com \
    --locale=it


Did I set up memache correctly? I have applied memcache by via instructions from this page to our production server. The difference in numbers don't look stellar.

My question: Did I configure memcache improperly? Can I increase the CACHESIZE to perhaps get a better overall performance?

Settings.php

In settings.php, I've included this bit of text as recommend by the README.txt inside the memcache module.

/**************************************************
 * MEMCACHE
 **************************************************/
$conf['cache_backends'][] = 'sites/all/modules/memcache/memcache.inc';
$conf['lock_inc'] = 'sites/all/modules/memcache/memcache-lock.inc';
$conf['memcache_stampede_protection'] = TRUE;
$conf['cache_default_class'] = 'MemCacheDrupal';

// The 'cache_form' bin must be assigned to non-volatile storage.
$conf['cache_class_cache_form'] = 'DrupalDatabaseCache';

// Don't bootstrap the database when serving pages from the cache.
$conf['page_cache_without_database'] = TRUE;
$conf['page_cache_invoke_hooks'] = FALSE;

$conf['memcache_servers'] = array('server:11211' => 'default');

Memcache Conf

The memcache system conf has been left it's default:

PORT="11211"
USER="memcached"
MAXCONN="1024"
CACHESIZE="64"
OPTIONS=""

Benchmarks

I ran a battery of apache benchmark tests and these are the numbers

With memcache active

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        1    1   0.4      1       4
Processing:     4   50   8.6     52      62
Waiting:        4   50   8.6     52      62
Total:          7   51   8.2     53      63

Without / Before / Baseline

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        1    1   0.5      1       4
Processing:     3   50   8.4     52      61
Waiting:        3   50   8.4     52      60
Total:          7   51   7.9     53      62

I did end up increasing the RAM in the conf file. Since I've noticed no  evictions. In fact the eviction stat is at 0 at the moment.


Omega theme background color problems What would be the best option for achieving following:

I need to have a background color blue under website and the body of the website (including all regions) would be white. Best for demonstrating would be to visit this site

  http://www.prevention.com/health/healthy-living/50-healthiest-eco-spas-america

By default alpha-default-normal-12.css contains rule for body min-width: 960px. I can solve it by changing body width to width:960px and adding margin: 0 auto;.

However after switching to fluid layout, width is taken from my global.css and it of course restricts layout to be fluid.

My question is what would be best way to achieve this without editing other css files. Or is it ok to edit them?

You can edit global.css insted of editing alpha_default_normal.css so that changes will persists even if you changes your browser resolution. And according to me, set the width of the div in percentage... so it will automatically adjust to other screen resolutions.
eg.

width:70%;
margin : 0 auto;


Is it possible to filter by taxonomy field? Is it possible to filter by taxonomy field in a view, using Drupal 7?

I will try to explain the problem with a silly example: let's say I have a list of countries that are a taxonomy term and each country has a field "Language".

I also have a list of items each linked to a specific country.

I would like to be able to filter by language, getting only those items that have a country where e.g Spanish is spoken.

Absolutely. When creating a new View, be sure to show "Taxonomy Terms" rather than Content. Change "of type" to be Countries.

After that, you should be able to add a Filter for the language field.


How to inject code into node body after x paragraph Trying to figure out if there is a way to inject code after the first or second paragraph on a node.

More specifically I am trying to inject an Adsense ad.

So far I haven't been able to find a solution or module that will do this.

Can anyone help?

I am not using paragraphs module. Just looking how to inject code right after the third or fourth  tags on the body of the node.

Well, one way to do this would be to modify the twig template that is outputting the paragraphs (on the node).

You could loop the paragraphs render array {{ content.field_foo }}:

{% for i in content.field_foo %}
  {{ content.field_foo[i] }}

  {% if i == 1 %}
    // print your output
  {% endif %}
{% endfor %}

1 will be your second item, as the count starts at 0. This is just some rough untested pseudocode. But the idea is to loop over and print each item in the render array one by one, and inject the code at certain counts.

edit: This answer is for if you are using the Paragraphs module, which at the time of this answer is not clear from your original question.


Creating specific taxonomy terms the Drush way is there a way to create specific taxonomy terms the drush way?

the docs mention only a number argument to generate dummy terms.

http://www.drushcommands.com/drush-7x/devel-generate/generate-terms

i have around 150 terms (city - country (parent) - region (parent)) in one location taxonomy vocabulary. would be great if i can write the syntax in a text editor and use this to populate the vocabulary.

thx for any suggestions!

Try the taxonomy manager module.

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

It allows for mass insertion of terms.

There's also a taxonomy csv module which allows for import/export of taxonomies to file. That might be worth a try too:
https://www.drupal.org/project/taxonomy_csv

Else you can try and write your own module... But that's a rather tougher route.


Conditional fields for the field type 'managed_file' is not working in Drupal 8 I have two radio buttons

Enter The Text
Upload a Text File

If user select the 1st option, a field of type 'textfield' will appear & if they select the 2nd option, a field of type 'managed_file' will appear.
 But this code with working fine for textfield but not working for managed_file
 Now, how to implement conditional fields in Drupal 8 ?

This is my D8 code.

    $form['field_type'] = array(
    '#type'    => 'radios',
    '#options' => array_combine( array(t('Enter The Text'), t('Upload a Text File'))
                                 array(t('Enter The Text'), t('Upload a Text File'))
                                ),
    '#title'   => t('Choose entry type.')
  );

  $form['imgurl'] = array(
    '#type'          => 'textfield',
    '#title'         => t('Enter the text'),
    '#states'        => array(
      'visible'      => array(
        ':input[name="field_type"]' => array('value' => t('Enter The Text')),
      ),
    ),
  );

  $form['file'] = array(
    '#title'              => t('Choose Text File'),
    '#type'               => 'managed_file',
    '#progress_indicator' => 'throbber',
    '#progress_message'   => NULL,
    '#upload_location'    => 'public://files/',
    '#states'             => array(
      'visible'           => array(
        ':input[name="field_type"]' => array('value' => t('Upload a Text File')),
      ),
    ),
  );

I don't know, if this as anything to do with managed files, but I think #options should look like this:

'#options' => array(
  'text' => t('Enter The Text'),
  'upload' => t('Upload a Text File'),
),

and in #states the options key, not the translatable value:

'#states' => array(
  'visible' => array(
    ':input[name="field_type"]' => array('value' => 'text'),
  ),
),

If it has something to do with managed_file, then this old issue is back:

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

You can check this by changing temporarily managed_file to file.


How to add a META tag in head conditionally to entity content I need to put a meta NOINDEX tag in head conditionally to a CCK field value ("visibility=private") in one specific content type ("projects").

I read about drupal_add_html_head($data = NULL, $key = NULL) but I'm not sure where to put it.

If I could put the tag in body I would just use a computed_field, but as I need it to be in head, should I put it on my own module (but on which hook?) or should I copy/insert it  in html.tpl.php ?

My problems are (a) that if html.tpl.php will change then I'll have to change also the copy I overridden; (b) then I'm also not sure I have access to $entity inside the template (I never used them) and, finally, (c) that being a matter of logic rather than presentation a module maybe is more indicated than a template.
For all this reasons I would prefer a custom module. Would it be possible ?

It's definitely possible, you could do this using hook_entity_view() for example:

function MYMODULE_entity_view($entity, $type, $view_mode, $langcode) {
  if ($type == 'my_entity_type' && $view_mode == 'some_view_mode') {
    // Check the field items.
    if ($items = field_get_items('my_entity_type', $entity, 'field_visibility')) {
      if ($items[0]['value'] == 'private') {
        $element = array(
          '#tag' => 'meta',
          '#attributes' => array(
            'name' => 'robots',
            'content' => 'noindex',
          ),
        );
        drupal_add_html_head($element, 'robots');
      }
    }
  }
}


How to get term alias in twig templates I have created a block to show the sibling terms of the term being viewed. In the twig template I am looping through the terms to display the names linked to their respective pages.

Now I unable to figure out how to get path alias.

Can any one of you please guide me how to get the path alias of a term?

Thanks

A bit late, but just figured this one out in case it helps someone else:

{{ path('entity.taxonomy_term.canonical', {'taxonomy_term': tid}) }}


\Drupal::request() vs $request_stack->getCurrentRequest() These seem to return the same thing:

\Drupal::request()

$request_stack->getCurrentRequest()

Which is the preferred way to get the current request and why? Is one of these to be deprecated? Any other advantages/disadvantages?

Thanks!

How to get the current request object:

Procedural

In procedural code get the request from the static wrapper \Drupal:

$request = \Drupal::request();

Service

In a service get the request from the injected request stack:

$request = $this->requestStack->getCurrentRequest();

Controller

In a controller you can pull the request from the route argument stack by including a typed request parameter. An example from UserController:

use Symfony\Component\HttpFoundation\Request;

  public function resetPass(Request $request, $uid, $timestamp, $hash) {
    // use $request
  }

It's not necessary to define the route parameter in the route definition. The request is always available.

Form

In a form method get the request from getRequest():

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $request = $this->getRequest();
    ...
  }

Don't use the injected requestStack property directly, because it is not available for all Form API callbacks.


feed import module: is it possible to have a feed importer without unique field I'm using Commerce Kickstart 2.

The SKU field of my products is automatically generated in relation with a serial field that I've created (Serial field module). That was done with the appropriate token generated with the serial field attached to automatic SKU generation. So I want to import my products with Feed Import module without to have a unique field configured, because the SKU will be automatically generated.

Is it possible to setup a feed importer without unique field?

Sorry about my bad English.

Check out Feed Tamper module. It allows you to modify the imported data before it is saved. For example, you can specify a token as the default value for the field or add a placeholder which then you can replace when you generate SKU.


Flagging Referenced Entities I have two node types (one is galleries, one is images). The node types are referenced to eachother via entity reference (which is providing a field on the image node which references a gallery).

I want a user to be able to flag one image in a gallery which will become the 'cover' of the gallery. I am attempting to do this from a combination of rules + flags; I have a flag set up which can flag images.

The tricky part here is referencing the image to the gallery entity, and only allowing each gallery to have one flagged image. (i.e. galleries can't have two covers).

The rules part is tricky, and it would be awesome if I could get some assistance.

I am aware that the first step is the 'event'. Once an image is flagged, it should unflag other images that reference that gallery (via trim a flag). Haven't been able to get it set up. Anyone have experience with this? Thanks!

This is not a straight-forward flag trim. Trim works on all content in the set of a content type, and I don't see how you can do it on a subset.

This answer uses Views bulk Operations, so please install that. I also assume the flag is global (or if not then only one user flags)

We will create a view that will get the list of images to unflag. Then we will create a rule component that will unflag the images, and lastly we will create a rule that will initiate all of this when an image is flagged.

Create a view that will fetch the images that belong to a certain gallery and that have been flagged.

To do that, create a view (master display only) on content (node), and filter on content type (image). Add three relationships:

Relationship 1: Add a relationship 'Flags: Node flag', include only flagged content, set the flag to the desired flag, and set it to 'Any User'. This will ensure that only flagged images show up.

Relationship 2: 'A bridge to the Content entity that is referenced via field_gallery'. This will bring in the referenced 'gallery'.

Relationship 3: This one may seem weird, but bear with me. Add 'A bridge to the Content entity that is referencing Content via field_gallery', and set its relationship to the previous one, ie 'Content entity referenced from field_gallery'. This links back to the image type. The reason for this will become apparent in the next step.

Add a contextual filter of 'Content nid' and set its relationship to the third relationship you added above, ie 'Content referencing Content from field_gallery'. We will pass in an image nid, get the associated gallery, and then get all the associated images belonging to that gallery that are flagged. So now we have our list that we will use in rules.

The last step is to add a new field (the only field we need). Add a field 'Bulk operations: Content'. Do not use a relationship. This will allow us to use the view with rules.

Finally, remove the pager as it is not needed.

Now we need to add a rule component and a rule.

Create a rule component.
Add a new rule component called 'Unflag Image'. It is of plugin type 'Rule'. Add two variables.

First variable: Data type -> node, Label -> previously flagged image, Machine name -> prev_image

Second variable: Data type -> node, Label -> newly flagged image, Machine name -> new_image

Now add a condition: Data comparison. Compare 'prev-image:nid' equal 'new-image:nid' and tick 'Negate'. This will check that the previously flagged image does not equal the newly flagged image.

Add an action: Unlag a node, and set the node to flag as 'prev-image'. Set user on whose behalf to flag as 'site:current-user', and select skip permission check: false.

Create a Rule.
Add a rule that has event: 'A node has been flagged' and select your flag.

There is no condition.

Add an action to the rule: Load a list of entity objects from a VBO View. For its value select the view that you added previously. For the argument select the flagged-node:nid. Leave the provide variables as is.

Add a loop, and select 'entity list' (the provided variable from previous step), and leave defaults for current list item.

Inside the loop, add an action: Component: Rule: Unflag image. This is the component we added earlier. For previously added image, select 'list-item' (provided variable of previous step), and for newly flagged image, select 'flagged node'.

And that is it. You should now debug it as I have not checked it, but the logic is more or less there and you can take it further.


Views 2 filter: field x = current user's ID So I have a view and a filter with field x. I want this field x to be equal to the user ID of the current user.

When adding the filter I'm asked to insert a value, if I insert the value by hand, e.g. 1, the right content is displayed for that user.
However, I wanna automate this system for the rest of the users.

I tried things like %uid in the value box but this doesn't seem to work.

any ideas?

I'm using Drupal 6 and Views 2.

There is a filter called User: Current which will "Filter the view to the currently logged in user."


Token for Total Flag Count I have created a flag for my comments named HELPFUL. If users find a comment helpful they vote it as such.

The challenge that I have is how do I show the total votes for the flag next to the button? If a comment was voted as helpful 5 times for example, show that next to the helpful button.

If there are no helpful votes for a particular comment show nothing (do not display 0) but only the HELPFUL rate button (flag)

I have tried to add [flag-action:count] and [flag-helpful-count] as the token under the flag setting (/admin/structure/flags/manage/helpful >>edit>> Flag link text) but it does not work.

Looked at COMMENT tokes and I see this available: [comment:flag-helpful-count]
It still won't work. It shows this text [comment:flag-helpful-count] instead of a total number.

Any help would be greatly appreciated.

You try code:

/**
 * Implements hook_tokens().
 */
function mymodule_tokens($type, $tokens, array $data, array $options, \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata) {
  $replacements = array();
  if($type == 'comment' && !empty($data['comment'])) {

    foreach($tokens as $name => $original) {
      switch($name) {
        case 'flag-helpful-count':
          //$comment = \Drupal\comment\Entity\Comment::load($data['comment']->get('cid')->value);
          //$count_flag = \Drupal::service('flag.count')->getEntityFlagCounts($comment);
          $replacements[$original] = 10;
          break;
      }
    }
  }
  return $replacements;
}

function mymodule_preprocess_comment(&$variables) {
  $token_service = \Drupal::token();
  $token_count_flag = $token_service->replace('[comment:flag-helpful-count]', array('comment' =>
    $variables['elements']['#entity']));

}


Add content type machine name as body class Is there a way to insert a class to the body of the node page? It should be named like the current node type's machine name.

Maybe someone could extend this code below with a content type class:

function marienschule_preprocess_html(&$variables) {

  // Add node ID to the body class.
  $node = \Drupal::routeMatch()->getParameter('node');
  if ($node) {
    $variables['attributes']['class'][] = 'node-' . $node->id();
  }
}

The code sample from your question could be extended to look like that:

function marienschule_preprocess_html(&$variables) {

  $node = \Drupal::routeMatch()->getParameter('node');
  if ($node instanceof \Drupal\node\NodeInterface) {

    // Add node ID body class.
    $variables['attributes']['class'][] = 'node-' . $node->id();

    // Add content type machine name body class.
    $variables['attributes']['class'][] = 'node-type-' . str_replace('_', '-', $node->bundle());
  }
}


Unable to get javascript to make first letter of every word LARGER on my site to load properly I'm trying to use javascript to make the first letter of every word LARGER in titles with the class 'field-name-title' (so basically all nodes).

I found a couple of Javascript-based solutions online, notably here and here. But whenever I try and implement them nothing happens (by which I mean the titles that are supposed to be changed are NOT).

What's I've tried:

1) I replaced the boilerplate class name in the javascript linked to above with my class name (ir. replaced 'title-case' in the one with 'field-name-title', etc.).

2) I've ensured I have a first-letter class in my stylesheet with the following property:

.first-letter {
  font-size: 1.4em; // I also tried % such as 115%
}

3) I put my javascript file in js/first-letter.js. I referenced it in my .info file as 'scripts[] = js/first-letter.js.

4) I've flushed caches repeatedly (and besides aggregation is turned off).

What am I missing?

If Alireza's answer doesn't work, try this one.

js/first-letter.js

(function ($) {
 $( document ).ready(function() {
  $('.field-name-title').html(function(i,el) {
    return el.replace(/\b([A-Z])/g, "$1");
     });
  });
}(jQuery));


Fire javascript on a form submit Even the searching I have done that looks like there may be a solution doesn't really seem to answer this.

I have a form with an input value.  When the user enters a value and clicks submit, I want to call a javascript routine and make that value available to it.

It seems simple enough, but I can't really find a good answer.

You need some jQuery on the page, e.g:

Drupal.behaviors.form_submit_processor = {
  attach: function (context, settings) {
    $("form#my-form").submit(function(e) {
      alert('form submitted');
      alert($('form#my-form #edit-name').val());
    });
  }
}

You could add to your theme script.js, with drupal_add_js or form_alter and $form['#attached'] ( recommended )


Form with manged_file filed is not submitted? I have a form in my drupal module. in my form, I have used manged_file field.
form name is "difference_form" and I have created two functions.
one is "function diffence_form" for form definitions.
here is code:

function difference_form() {
  $validators = [];
  $form['new_image'] = [
    '#type' => 'managed_file',
    '#name' => 'new_personal_image',
    '#title' => 'New Image',
    '#description' => theme('file_upload_help', [
      'description' => 'Please insert your new image.',
      'upload_validators' => $validators,
    ]),
    '#upload_location' => $path,
    '#default_value' => variable_get('new_image', ''),
    '#upload_validators' => $validators,
  ];

  $form['submit'] = [
    '#type' => 'submit',
    '#value' => 'submit',
  ];

  return $form;
}

function difference_form_submit($form, &$form_state) {
  drupal_set_message('test_form_submit called');
}

and also I have created a block for this form in hook_block_view.

function customize_block_view($delta = '') {

  $block = NULL;
  $block['content'] = drupal_get_form('difference_form');
  $block['subject'] = 'Difference Form';
  return $block;
}

Form is rendered correctly, but when I click on submit button, submit function is not called.

I tried to debug my codes. I found if I remove file_managed field from form definition, submit function works.

also if I found if I renamed all difference_form to another name for example "test_form"

drupal_get_form('test_form');
function test_form(){....}
and
function test_form_submit(......

submit function works.
it seems system is sensitive on "difference_form" only

I am thinking might the expression "difference_form" be blocked in database or somewhere else ?

I found the reason of this problem finally.
It was as a result of jQuery code mistakes.

in form submission, I tried to disable submit button immediately after clicking.
I had to change the coding because set button disable causes this problem.


What is the easiest way to get the value of a string field in a twig template? I'm using Drupal 8.5.4 and Bootstrap Paragraphs. I have a custom module foo and a custom paragraph type bar defined within. In the template for bar, I use kint to inspect the content of the variable. It turns out it has 17 properties, and none of them are the value of the field. The first 14 of them are in core/lib/Drupal/Core/Field, L#89-102. The last 3 are 0, #cache, and weight.

Digging into the object, I found the field value in content.bar.0['#context'].value. Obviously using this method to access a simple field value is janky as hell, and I would prefer not to have to do this every time.

Two questions:

Is there a simpler way to access the field value? I don't mind using a twig filter if need be
Is there a way to configure my paragraph types to pass the context to the template, rather than all of the field data?

You are referring to paragraph--bar.html.twig? Then this depends on what you want to do with the value.

Render the field value:

{{ content.field_example }}

Write code with it:

{% if paragraph.field_example.value == 'foo' %}

The field value is "foo".

{% endif %}

See this blog post for node.html.twig, which applies here as well, only that the entity is paragraph. instead of node.: https://www.md-systems.ch/de/blog/techblog/2017/02/20/twig-and-entity-field-api-or-how-to-take-control-of-nodehtmltwig


Pulling Breadcrumb items from the Menu Link text instead of Title field (D7) Some of my pages are pulling text for the last breadcrumb item from the menu link text. The rest of my pages are pulling text for the last breadcrumb item from the Title field. What I want is for all of the breadcrumbs to pull from the menu link text.

I'm using the Menu Breadcrumb module (applied to all of the pages in question) which allows the menu link text of a page to be added to the breadcrumbs, but I do not have this option enabled. My theme (a derivative of Omega) must be what's pulling the text into the breadcrumbs (I hear this is not done by default) because when I do enable the Menu Breadcrumb option I get either the menu link text twice or the menu link text and the Title text (depending on which page I look at).

Those pages pulling the breadcrumb item from the menu link text are of a specific content type which has a panel applied to it. The rest aren't using panels -- this is the main difference I can see which might explain this behavior.

I suppose I could alter the theme to not put the text item in, then enable the feature in Menu Breadcrumb (which behaves correctly), but obviously it is possible to do it the way I want without modifying the theme since it's happening with the panel'd type pages.

Any ideas?

Install Stats:

D7
Derivative of the Omega theme
Context
Panels
Menu Breadcrumb (used on all pages; modified - see post by pschnapp)
Custom Breadcrumb (used only on two types, not the affected types)

It's been a while since we came to a resolution on this issue, so I hope I get everything right.

It seems that I was a bit confused w.r.t. what fields data was being pulled from for these areas (menu item, title, & breadcrumb item). Here's what we found:

Menu item text gets pulled from the "Menu link title" field in the "Menu settings" section of a page's editing interface.
The text in the "Title" field of a type is used for the breadcrumb item text and will be used as the page's title as well (i.e. the title displayed in the browser window's/tab's chrome) if no other title is specified.
The "Page title" field in the "Page title settings" section will override the "Title" field so far as the browser chrome title is concerned, but won't affect the breadcrumb.

IIRC, the "Page title" field was not active for the pages we were having trouble with, which was the cause of the confusion I was having.

It would be nice if instead of defaulting to "Title" for the name of this field, "Name" were used instead, as that's a bit more descriptive and would not lead to the confusion we had. The name of this field is changeable -- I'd recommend changing it to "Name".


how to create a node slideshow with customized fields? I have created a view displaying an image with two other fields, i have created a lightbox slideshow of that image, now i want that the slide show should display other required fields of the content type along with the image. How to achieve this?

thanks in advance

Use Views Slideshow module.
steps :

Enable view slideshow module.
Create a view using existing content type(ex-product).
View format: Slideshow
Add item for slideshow (such as the title, image etc).

Or you can use jCarousel module.


Programmatically log in user not working correctly Here's what I am doing:

global $user;

if (!user_is_logged_in()) {
  $user = user_load(31);
  user_login_finalize();
  echo $user->uid;
}

When a user is not logged in - we have to log in him as user with id 31. I have placed this code at top of page.tpl.php.

I am noticing some strange behavior. If I visit the homepage (http://ggames.kz/), at the top I can see the id 31, that's correct. However, if I visit the user page (http://ggames.kz/user), it shows that I am not logged in. If I refresh the browser or visit another pages, I am logged in. I can't figure out why it won't authenticate user from the first page load?

Template files are not the proper place for your code, since at this level the headers are (probably) already sent. That's why the session cannot be saved on the client browser.

You'd better implement hook_init() in a custom module

function YOURMODULE_init() {
  if (!user_is_logged_in()) {
    global $user;
    $user = user_load(31);
    user_login_finalize();
  }
}

  If I refresh the browser or visit another pages, I am logged in.

You are seeing the correct user ID on your debug output, just because you are printing the user id which you have loaded just 2 lines before. It doesn't mean that the user is successfully logged in.


Change View Mode on Taxonomy Tag Pages I have a field that is linked to a taxonomy vocab called tags when creating my "Article" content. When I show these tags on the node page, it links to: /tags/

I can't seem to find where I can change the view mode for this /tags/ page. Currently its on teaser view mode.

It is not clear what you want to achieve here but I'm making a guess that you want to display the full content. You can either change the "Teaser" display mode for the content type "article" or you can create a template file "taxonomy-term--tags.tpl.php" and customize it.


How to assign twig templates dynamically on basis of field value of custom block? I have a list box in my custom block with different theme options. On basis of the List box field value I would like to assign the specific twig template dynamically. What will be the best approach to do it and how ? If possible please provide a code snippet for the same.

See https://drupal.stackexchange.com/a/211157/31 for an existing related answer.

You implement the theme suggestions hook, the block_content entity is in $variables['elements']['content']['#block_content'] as shown there, then you can access your field values from there and provide any kind of template suggestions that you want.


How do I load taxonomy terms basing on the current language? I am using the following code.

$language =  \Drupal::languageManager()->getCurrentLanguage()->getId();
$terms = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree('category', 0, 1);

How can I change it so it load the taxonomy terms basing on $language?

Use EntityRepositoryInterface::getTranslationFromContext:

$terms_translated = [];
foreach ($terms as $key => $term) {
  $terms_translated[$key] = \Drupal::service('entity.repository')
    ->getTranslationFromContext($term, $language);
}

BTW, you don't need to provide a language code, because the current content language is the default value for the second parameter in getTranslationFromContext() and in a standard multilanguage site this is equal to the current language.


How to install an existing Drupal profile with drush? Seems like searching for the answer on Google just leads me to how to create make files and profiles.

I know how to do that.
I also know how to install Drupal with drush.

But I want to install one of the many existing Drupal profiles, like Drupal Commons, Commerce Kick Start, etc. with drush.

I would have thought it would have been just an easy process to find the profile's makefile and run that. Drush will take care of the rest.
But I can't find the repositories where these makefiles sits.

Some direction would be appreciated.

To build on what Patrick said, if the profile is not already in your profile directory, you can download it with Drush dl:

drush dl drupal --drupal-project-rename=drupal
cd drupal
drush dl commons
drush site-install commons --db-url=mysql://user:pwd@localhost/db_name --site-name=Example --account-name=admin --account-pass=pwd

You do not need to run drush make, because drupal.org runs it prior to making the profile available for download.  Thus, when you run drush dl commons, you get all of the components that the Drupal Commons distribution needs to install.


Background Process Module Limitations and Efficiency? Drupal's Background Process module has been suggested as an alternative to Cron and Batch when heavy lifting is required. The API documentation on background process is good but does not go into details on how it actually works and its' limitations. Can someone explain how Background Process gets around the PHP timeout issue and keeps tasks alive - and whether it operates efficiently (e.g. vs. Batch).

Thank you!

Background Process uses set_time_limit() to control the timeout of the subrequest. It defaults to 0 (php script does not time out, i.e. runs indefinitely).

background_process_start_locked('dontrunconcurrently', 'mymodule_dosomething', $myvar1, $myvar2);

This should be used when you want to ensure that your background process wont run concurrently with itself. In reality the "dontrunconcurrently" is used as a key for a lock.

Background Process has no internal mechanism per se to control serial execution of background processes.

For serial execution of background processes you could take a look at Background Batch, which allows you to run standard Drupal batch jobs as background processes, or you could maintain a state within your background process function.


Drush and web front end reporting strange updates? Is anybody else seeing this:

root@dev:/etc/apache2/htdocs/drupal-7/sites/tpppdonate.org.uk# drush pm-update --pipe
imagecache_token 7.x-1.0-rc2 7.x-1.x-dev Update-available
uuid 7.x-1.0-beta1 7.x-1.x-dev Update-available

The update process is reporting that a dev version is the recommended version over the stable release.  The same story is reported in the front end.

When I take the bait and run the import - all I see is a verison number change in the .info file:

before: version = "7.x-1.0-rc2"
after: version = "7.x-1.0-rc2+0-dev"

Anybody any idea what is going on?

This was reported over at drupal.org - https://www.drupal.org/node/2729789

It is now fixed.


Fatal error: Call to undefined function drupal_array_diff_assoc_recursive() I am getting the below fatal error when i click content type > content x > manage fields > click edit:

"Fatal error: Call to undefined function drupal_array_diff_assoc_recursive() in /home/content/65/11722765/html/sites/all/modules/token/token.pages.inc on line 23"

Please help.

D

drupal_array_diff_assoc_recursive() was added in Drupal 7.23, and you have a lower core version than that.

You could try copy/pasting the function somewhere into your current core as a hack, but don't be surprised if it doesn't work.

Or you could try hacking at the Token module to remove its reliance on that function, or install an older version of Token altogether, which doesn't rely on it.

Basically you're in "no warranty" territory; if you update one part of your codebase, but refuse to update the rest of it, you can't expect it to carry on working.

The proper solution is to upgrade your core version ASAP, not just for this, but mostly for https://www.drupal.org/SA-CORE-2014-005.


Using parameters in routes I am using the pathauto module to create url aliases for all user account url, so:

/user/[uid] will become /u/[user:account-name]-[user:uid]

which means:

/user/36 will become /u/john-smith-36

In my custom module, I have created a route to fire a controller when /u/john-smith-36/settoken?token=123456 url is accessed.

The controller will:

Fetch the account of the current logged in user.
Update the text field field_user_push_token with the query parameter value:
123456
Save the account of the current logged in user.
Redirect the user to the page: /thank-you

I am finding a difficulty on how to use parameters in route for the user account url !

save_push_token.routing

save_push_token.SavePushToken:
  path: '/{user}/settoken'
  defaults:
    _controller: '\Drupal\save_push_token\Controller\SavePushTokenController::SavePushToken'
  requirements:
    _permission: 'access content'

SavePushTokenController.php

<?php

namespace Drupal\save_push_token\Controller;

use Symfony\Component\HttpFoundation;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Session\AccountInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;

class SavePushTokenController extends ControllerBase {

  /**
   * Display the markup.
   *
   * @return array
   */
  public function SavePushToken(AccountInterface $user, Request $request) {

// Get token value from url.
    $request = Request::createFromGlobals();
    $userpushtoken = $request->query->get('token');

// Load the (current logged user) account.
// No need to load the user account because of {user}
    // $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());

// Set the (token).
    $user->set('field_user_push_token', $userpushtoken);

// Save the (current logged user) account.
    $user->save();

// Redirect to "/thank-you" page.
    return new RedirectResponse('/thank-you');

  }
}

But simply the controller is not fired when I access for example /u/john-smith-36/settoken?token=123456 url is accessed.

any help on how to properly use parameters in routes ?

I see two problems. First your routing file has the path set to:

path: '/{user}/settoken'

To do what you're describing I would expect to see:

path: '/u/{user}/settoken'

Second, are you opposed to using a second parameter in the URL instead of the Get Method variable? If not opposed you can add a second parameter that will handle the 'token' variable.

In your routing file you can set up the pareters like this:

path: '/u/{user}/settoken/{token}'

The url would then be (cleaner I think):

/u/john-smith-36/settoken/123456

Lastly, to access the parmeters in your controller you shouldn't need to access the Globals. The parameters get passed to your function directly. Use this as the function declaration to pick up the variables:

public function SavePushToken($user, $token)


Direct link to view unpublished node causes redirect loop When I unpublish a node and have another user without permissions to view unpublished content trying to access that node (through an external link for example) it will generate a redirect loop. It just does a bunch of 302's to the same page, until the browser stops it.

I would expect an "access denied" page. What could cause the redirects to the same page?

Disabling "global redirect" module didn't have an effect. I don't have any rules or module code relating to it either.

Update:

Anonymous visitors get redirected to the /user/login page. Authenticated users don't have "view unpublished nodes" permission.

I guess I can change my 403 page to something other than /user/login to fix the redirect loop.

Question:

How would I create a regular page and show the login form if they are not logged in already, otherwise show a "page has been deleted" error?

I guess I can change my 403 page to something other than /user/login to fix the redirect loop.

Yes, that seems like it would cause the redirect problem.

But it sounds like you want to have a login page when the user gets an access denied message, and there is a module to do exactly that: r4032login

LoginToboggan may provide a similar feature, but I find that r4032login does a very simple thing and it does it well. On the other hand, I've run into several bugs with LoginToboggan.


hook_field_formatter_view not being called I cannot for the life of my figure out why cc_byline_author_field_formatter_view is not being called here. hook_field_formatter_info works as I can select the formatter for my field. Cache clear, module name change, module disable and re-enable have not helped.

Thanks for having a look.

/**
 * Implements hook_field_formatter_info().
 */
function cc_byline_author_field_formatter_info() {
  return array(
    'cc_byline_author_author_replace' => array(
      'label' => t('Byline Author Replacement'),
      'field types' => array('text'),
    ),
  );
}

/**
 * Implements hook_field_formatter_view().
 */
function cc_byline_author_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  die;
  return '';
}

Whelp, there goes an hour.

Turns out I was configuring the "Default" Display rather than the "Full Content" Display.


Strange error in status reports en unable to safe my taxonomy term url-alias When I go to admin/reports/status I see this error (see image).

Also I am unable to safe my taxonomy term url-alias? What does this error mean and how can I fix this?

You can safely ignore this.

See https://www.drupal.org/node/2661178 and the core issue linked there for details.

Nothing is broken, the entity definition change tracking just gets a bit confused.


List menu and sub menu I have a "Opinions" in my main menu that appears in main menu block in first page. I want to do something that when I click to "Opinion" in goes to a page that has 2 links: "articles" and "others". I mean I click to Opinions and after that I can select articles or other and they go to article page and other page (articles and other are my taxonomy terms)

I don't know what should I do?

If your question is not what your title says consider this:
Module you need is views module.

Create a view of article type and keep the display of  your view type as page,this view will list all nodes of article content type.Give page path as "articles" or whatever.
Create another view to show taxonomy terms of type all/vocab, this view will also be page display type.Give page path as "show-taxonomies" or whatever.
Create a menu block with two menu items "articles" and "others" link them respectively to the views page path you have set.
Now put this menu block in main content region with path specified for block display as "opinions".


Is it possible to change the Alt value inside the image.html.twig template? Is it possible to change the alt value inside the image.html.twig template?
I found out that it can be accessed via attributes.alt. And then there is a protected value. Is there a way to set it?
Something like:
{% set attributes.alt.value = 'new alt' %}

In a Twig template you can use the method attributes.setAttribute():
{% set attributes = attributes.setAttribute('alt', 'new alt') %}


Drupal 7 Customize Node Add Form First, let's describe what I have already:

Vocabulary: "Categories" with some terms added(cat1, cat2, cat3)
New content type "custom_page" where I added a new field of type "Term reference" using vocabulary "Categories";
Widget type for previous field is "Check boxes/radio buttons" because a custom_page can be part of multiple categories;

It is possible when adding a new custom_page, to add additional fields for each category selected?

Assuming, I checked "cat1" and "cat3" -> it is possible to add 3 more fields inline (new_field1, new_field2, new_field3) with every category selected?

Thanks,
Alex

Can't do with core functionality. You need to modify form using hook_form_alter. Probably you would want to use Drupal form's AJAX to make fields appear.

I don't know if there is a contrib module to do this, I can't see any.


public:// urls being printed in source code I have a weird issue with a Drupal website I am working on. The site has an audio player, jplayer, that plays MP3 files. Some of the files do not play. The only difference I've found between the files that play and the ones that do not is that the files that do not play have a src in the form of public://audio/example.mp3. The ones that do play have a typical url of http://example.com/audio/example.mp3. Is there anything that I should investigate as to why some of the urls get printed out with a public:// url?

This is the source code that makes the jplayer work..

<?php

/**
 * Implementation of theme_menu_tree().
 */
function wyep_menu_tree(&$variables) {
  return '
' . $variables['tree'] . '
';
}

/**
 * Implementation of theme_file_link().
 */
function play_file_link($variables) {

  //watchdog('theme_file_link', '
' . print_r($variables, TRUE) . '
');

  global $base_path, $base_url;

  $file = $variables['file'];

  $file->url = str_replace('public:/', $base_url . '/' . variable_get('file_public_path', 'files'), $file->uri);

  switch ($file->filemime) {
case 'audio/mpeg':
    return '

fid . '" class="jp-jplayer">

fid . '" class="jp-audio">

play

pause

stop

                            Update Required
                            To play the media you will need to either update your browser to a recent version or update your Flash plugin.

';
  }

}

Drupal 7 uses stream wrappers instead of "file paths" to reference files in the public and private upload directories. If you want to research that more, the rabbit hole starts here - http://drupal.org/node/555118

In a "vanilla" D7 setup "public://" is equivalent to the D6 "sites//files" or "sites/default/files" directory. These directories still exist in D7 but have been moved in D8 - using a stream wrapper means the files can be moved anywhere, even a remote location, and still be referenced in a consistent fashion if you update the default stream wrapper.

Clive's comment referencing file_create_url() is a function that takes a stream uri and converts it to a url that a web browser can use.

The problem is that your server-side code delivering media to jPlayer is not sending URIs in the right format. If it's a contrib module, you should open an issue in the queue and link to it here; Clive or myself might be able to provide a patch.

I'm going to assume that the module you're using was originally released in D6 and then upgraded at some point to D7? (maybe the upgrade didn't go so well :P)

Edit:

Based on the code that was posted after I originally put this answer up I'd suggest looking into two things:

Shouldn't
$file->url = str_replace('public:/', $base_url . '/' . variable_get('file_public_path', 'files'), $file->uri);
be
$file->url = file_create_url($file->uri); ?
The "setMedia" action for jPlayer, I can't remember off the top of my head if it needs to be a url or a file path, but if it's a url shouldn't you be using $file->url? if it's a file path shouldn't it be generated by drupal_realpath()?


Let Parent View child's result I need to setup a view for a parent which shows the result of his child. The result is a content type which has a user reference field to each student who owns the result.

Each students' profile has a user reference field to his /her parent username. I.m using profile 2 to setup parent and children account differently.

By using contextual filter and relationships, I can easily show the fields of the result to each student who owns the result but since parents' account are different, I really don't know how to show contents linked to individual student to show in their parent account.

Download and install the Entity Reference module
In parent user fields, add a field with Entity Reference and a widget of Auto complete (tag style)

For example: I named mine lalala (click picture below to enlarge)

For Target Type, select User
Number of Values: Unlimited (as parent could have more than 1 child)

Then go to the parents account and start typing child's account user name, you will see the name in the drop down, select it and save.

Use a comma , to add other child account. (parent has more than 1 child)

In your view

contextual filter of User id (uid) (which uses the parent's id)
add a relationship of lalala Referenced Entity

If not, try Referencing entity, but if my memory is correct it's Referenced


Views question with user reference I have a content type courses with course name, instructor, coordinator and ta fields. Instructor and coordinator are of type user_reference.

My data looks like below

course   instructor    coordinator

101       joe           guo

102       joe           larry

103       guo           joe

My course view has filter criteria as below
content access: access and Contextual filter : author ID

When Joe logs in, the display looks like

Courses

101

102

103

I'm trying to figure out how to display only the courses joe is an instructor for. It should not show 103.

Any ideas?

What you want is a contextual filter on your user reference field. It should be label like Content: Instructor (or whatever you named your instructor or coordinator field). For the When the filter value is not in the URL option, select Provide the default value and use the User ID from logged in user option.


"drush cron" doesn't work anymore after moving the site to a new server After moving a site to a new server, drush cron stopped working and now I am getting the following error:

  [Symfony\Component\Console\Exception\CommandNotFound]
  Command "cron" is not defined.

What am I missing?

The issue was fairly simple to solve.

I had forgotten to create a settings.php for each site. I was able to find out by running the following command:

drush --local -d -r /var/www/testproject/build/html status

And from the output I was able to see:

[debug] Could not find a Drupal settings.php file at sites/default/settings.php. [0.14 sec, 10.8 MB]

That was it


Drupal 8 CKEeditor license/pricing Drupal 8 ships with ckeditor as the default text editor. Drupal itself can be used free of charge without limitations. At least this is what I thought until now.
While CKEditor seems to be OpenSource, the website suggests there is a price depending on how it will be used. E.g. if a project has more than 2 developers, or more than 5 content editors.
https://ckeditor.com/pricing/
How does this play together? What am I missing? Is there a special license when using CKEditor in a Drupal project?

Both Drupal and CKEditor are licensed under GPL2+.
See https://github.com/ckeditor/ckeditor5/issues/991 and https://www.drupal.org/about/licensing.
CKEditor is not the only open source project offering commercial licensing. See the FAQ.


How can create a block that get a field value and render it? I'm trying to create a simple block that have some link fields. those links have some predefined values and after get any new values from the admin replace with values and then render that values to the theme:
my_module\src\Plugin\Block\MyBlock:

<?php

namespace Drupal\my_modules\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Block\BlockPluginInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;

/**
 * @Block(
 *   id = "my_block",
 *   admin_label = @Translation("My Block"),
 *   category = @Translation("My Block")
 * )
 */
class MyBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    // set default link field value.
    return array(
      'default_LinkA_url' => ('http://www.LinkA.com/'),
      'default_LinkB_url' => ('http://www.LinkB.com/'),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state) {
    // Add a form field to the existing block configuration form.

  $form['block_LinkA_url'] = array(
    '#type' => 'url',
    '#title' => t('Link A:'),
    '#size' => 60,
    '#default_value' => $this->configuration['default_LinkA_url'],
  );
  $form['block_LinkB_url'] = array(
    '#type' => 'url',
    '#title' => t('Link B:'),
    '#size' => 60,
    '#default_value' => $this->configuration['default_LinkB_url'],
  );
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state) {
    // Save our custom settings when the form is submitted.
    $this->setConfigurationValue['default_LinkA_url']
      = $form_state->getValue('block_LinkA_url');

    $this->setConfigurationValue['default_LinkB_url']
      = $form_state->getValue('block_LinkB_url');
  }

  /**
   * {@inheritdoc}
   */
  public function build() {
    return (
      '#markup' => $this->configuration['default_LinkA_url'],
      '#markup' => $this->configuration['default_LinkB_url'],
    );
  }
}

whatsoever I try I cant get any result, I would be happy to hear what the problem is.

If you use setConfigurationValue(), put the value as parameter in the function:

$this->setConfigurationValue('default_LinkA_url', $form_state->getValue('block_LinkA_url'));

Or better set the value in the configuration array like this:

$this->configuration['default_LinkA_url'] = $form_state->getValue('block_LinkA_url');

To display the url use the render element link:

https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Render!Element!Link.php/class/Link/8.2.x


Rating for anonymous users plus redirection to the login page I am using the Fivestar module for product rating with Ubercart. I want to enable rating for anonymous users. At the same time, when the user rates the product, this must be redirect to login page.

Is there any possibilities for doing this?

Try the Voting Rules module.

  Administrators can configure actions to occur when a user submits a
  vote, when a user deletes a vote, and when the results of a vote are
  calculated. Currently, Voting Rules supports votes on nodes, users,
  and comments.

I didn't test it, but using it is possible to achieve what you want with the the Rules module.


Featurizing a role, losing permissions I have created a role, Admin. Admin has permissions: "Assign roles" (via RoleAssign), "Access administration pages", "View admin theme", and "Administer users".

I export the role with Features (including the permissions one by one, as well as the role itself).

I delete the role in config and clear cache before enabling the feature. I enable the feature. I drush fr adminrole and I get Current state already matches defaults, aborting.

But my new Admin role doesn't have the expected permissions. Sometimes it has "Access administration pages" and "view admin theme" but it does not have "assign roles" or "administer users".

Is this a case where Features requires Strongarm? Or do I have to use Secure Permissions (which would be less than ideal because other administrators would not be able to change permissions in config anymore.)

I was confusing two different things. Because of the way Features handles permissions and roles, there are three pieces, not just two.

What I thought was happening:

I add Myrole to the Feature.
I add mypermission1, mypermission2, mypermission3, etc. to my Feature.
I save my Feature and user with Myrole will have mypermissions 1, 2, 3, etc.

What actually needs to happen:

I add Myrole to the Feature
I add mypermission1, mypermission2, mypermission3, etc. to my Feature.
I make sure that Myrole's permissions in my current config actually include mypermissions 1, 2, 3, etc.
I save my Feature and user with Myrole will have mypermissions 1, 2, 3, etc.

The first one exports whatever the state of mypermissions 1, 2, 3, etc. is at the moment of the export which means that if the role in your config does not actually have those permissions, your Feature will specify that your role does not have those permissions, explicitly. Backwards from what I was trying to do.


Validate function not working in ajax form I used Ajax in a form so that submission of form does not lead to reload of the page.It is working . But the problem is 'The Validation code is not working'. This is the code I have used in the form.

This is the code for submit button.

$form['submit'] = array(
  '#type' => 'submit',
  '#ajax' => array(
    'callback' => 'submit_driven_callback',
    'wrapper' => 'myform',
    'method' => 'replace',
    'effect' => 'fade',
  ),
  '#value' => t('Submit'),
);

I have put the validation part in the following function.

function formname_validate($form, &$form_state) {
  // Validation code
}

Am I doing it the wrong way? Should I put the validation part somewhere else?

You can try the following code.

$form['submit']['#validate'] = array('YOUR_VALIDATE_FUNCTION_NAME');


How do I update the sitemap in D7? I want to exclude some pages from the sitemap.

I go to these pages/nodes, edit them, then go to the XML sitemap tab and set it to 'Exclude'.

I then save and clear cache.

But when I look at my sitemap.xml file nothing is changed - the page URLs are still present.

How do I remove them?

The XML Sitemap module doesn't rebuild sitemaps on every node save/load; also, it's not cached like other artifacts in Drupal.

The module tracks XML Sitemap links and they are added/removed upon cron runs. So you'll need to run cron to rebuild your sitemap files.

You can also follow some of the steps in the Setting up your site map (7.x) documentation:

  Under "Inclusion" change "Excluded" to become "Included"
  To add pages linked from menus to the sitemap, visit the edit page for each menu whose items should be included (this would usually
  include the Main menu). Open the XML sitemap fieldset, and similarly
  change "Excluded" to "Included". Hit Save.
  Once that is all complete, go to Configurations --> Search and Metadata --> XML Sitemap
  Click on the Rebuild Links tab in the upper right
  Click on "Rebuild sitemap" even if the message says that you do not need to.
  Now you're taken back to the config page which shows you the link to your xmlsitemap which you can click and confirm that pages have
  been added


Custom Block to show taxonomy terms I am trying to create a block (that I can reuse in different templates and pages)that shows taxonomy terms (for a specific vocabulary).

I have already created a view to get the term list, and started overriding twig files to modify the display of the view. I modified the following files so far:

block--views-block.html.twig
views-view-fields.html.twig

The idea is to implement a bootstrap layout where the "row" div is on the first file and the "col" divs are in the second one.

Overriding those files is working but the layout breaks because there is a lot of unwanted code rendering. For example, the code generated by:

core/modules/system/templates/container.html.twig
core/modules/views/templates/views-view.html.twig

Which as I understand I can't override and I shouldn't modify (because they are in /core).

How can I get rid of all the unwanted code those files generate?

Sounds like you should enable template file suggestions in your site, this will help you to identify the right target name for a template to override the core files. You can read more about this feature in the docs at https://www.drupal.org/docs/8/theming/twig/locating-template-files-with-debugging


I created a view of a page and a block, but cannot find either. Where are they? I created a page view, but when I type in the address for it, it shows "Page not found". When I try to put the block where I want it to go, it doesn't show up, not even under disabled blocks. What step did I miss?


Query custom node by user Entity Reference I am trying to build a query that finds all nodes of a custom type where one of the fields is a user Entity Reference.  I am trying to use EntityFieldQuery but just as open to db_select().  The following is just an example of one of the queries I have tried.

$query = new EntityFieldQuery();

$query
  ->entityCondition('entity_type', 'node', '=')
  ->propertyCondition('type', 'custom_node', '=')
  ->fieldCondition('field_marketer', 'value', $user->uid, '=');

$entities = $query->execute();

Thanks in advance for any help.

The column name for an entity reference field is target_id, so your code should be:

$query = new EntityFieldQuery();

$query
  ->entityCondition('entity_type', 'node', '=')
  ->propertyCondition('type', 'custom_node', '=')
  ->fieldCondition('field_marketer', 'target_id', $user->uid, '=');

$entities = $query->execute();


How can I increase the number of excerpts shown per result? I have approximately 300 book-sized documents (50k up to 300k words each) that I'm trying to make searchable. I would like to display as many excerpts from each result as possible up to a maximum number.

It appears that excerpts are handled by Solr's highlighters, but there doesn't appear to be any parameters I can change to force it to show me more. The closest I've found is this:

  hl.snippets - Specifies maximum number of highlighted snippets to
  generate per field. It is possible for any number of snippets from
  zero to this value to be generated. The default is 1.

but it seems to have no effect on the results returned. I've increased this to 50, along with increasing maxAnalyzedChars and fragsize to no avail.

EDIT:
If I add hl.snippets=50 in a manually composed query it performs as expected - for some reason search_api_solr isn't applying the setting, it always returns 2 snippets. I've also noticed that it's not respecting my search:excerpt view settings.

Will keep updating as I persist.

I've been at this for nearly a week now and am about to start looking at other solutions. Hopefully I'm just being dense - any help is appreciated!

A little more background:
I am loading up a database with several hundred manuals, from small to phone-book sized. I need the user to be able to:

search the entire database using keywords and facets. The results must feature many large snippets which can be skimmed to determine which document is the correct one for their purpose
Then they need to perform a second search within that document only, which they will refine until they find exactly what the need from it.

So I need the ability to display lots of verbose snippets and any extra control I can have over how they are generated would be a huge boon.

Thank you :)

[Update]

I've added

<str name="hl">on</str>
<str name="hl.fl">fieldname</str>
<str name="hl.snippets">20</str>

to solrconfig.xml and confirmed that it does cause solr to return the specified number of snippets, but I still can't figure out how to get search_api_solr do the same. It appears that no matter the settings I apply in the search index or search server, the module still insists on returning 3 or less snippets and generating them via search_api's highlight.php.

[Update] There is a setting in:
Configuration -> Search API  -> Search Server -> EDIT -> Advanced:
"Retrieve result data from Solr" and "Retrieve highlighted snippets" that sounds like it makes drupal use solr's response instead of creating it via php but it appears to have no effect.

[Update] Ok, so now I guess I am going to attempt to create a simple module that uses hooks to modify the query and override the appropriate parameters, then hope that the results get processed properly.

[Update] Used devel and determined that Solr is returning the correct number of snippets according to my changed seettings in solrconfig.xml, so it's just a matter of getting drupal to take them and display them. I guess this means either hooking into highlight.php somewhere or just trying to hijack the query and write my own processor/template logic for it. Will share whatever solution I find. Tried to open an issue on drupal.org but it got flagged as spam. Oh bother :)

[Update] I am officially giving up. In order for drupal to work with the snippits that solr returns, "Retrieve result data from Solr" and "Retrieve highlighted snippets" must be enabled. When they are enabled however, Drupal asks Solr to send every field used for snippets for each result - in my case these fields are huge so this destroys performance. When those options are not enabled, Solr returns just the result data and highlights, but I cannot work with them because highlight.php generates it's own snippets from scratch. Oh well. My apologies to anyone who makes it here looking for a solution - and good luck!

[Update] Figured it out.Here's the solution I found. Somebody much more experienced than I will probably come along and offer better ideas but this works for now.

Leave "Retrieve result data from Solr" and "Retrieve highlighted snippets" unchecked, and just edit solrconfig.xml to define your snippets parameters like so:

<str name="hl">on</str>
<str name="hl.fl">fieldname</str>
<str name="hl.snippets">20</str>

Now solr will return the specified snippets in the results even if Drupal doesn't do anything with them. I cobbled together a simple module that implements hook_search_api_solr_search_results_alter (found in search_api_solr.api.php) to grab the results and store them in the $_SESSION variable:

excerpted from the solr_snippets.module I Frankensteined together:

function solr_snippets_search_api_solr_search_results_alter(\Drupal\search_api\Query\ResultSetInterface $result_set, \Drupal\search_api\Query\QueryInterface $query, \Solarium\QueryType\Select\Result\Result $result) {

    if(!isset($_SESSION['solr_snippets'])) {
        $_SESSION['solr_snippets'] = array();
        }
    $myResults = & $_SESSION['solr_snippets'];
    $myResults = '';
    // Grab the result items
    $result_items = $result_set->getResultItems();
    // Grab the highlighted snippets
    $extra_data = $result_set->getExtraData('search_api_solr_response');
    $highlights = $extra_data['highlighting'];
    [ process the results here and load them back into $myResults ]
    }

Then they are picked up by a view field:

  public function render(ResultRow $values) {

    return [
        $build['search_results'] = [
           '#theme' => 'solr_snippets',
           '#results' => $_SESSION['solr_snippets'],
          ],
        ];
  }

I also had to find a way to get the row count to the field template since it doesn't appear to be passed automatically. I didn't find the right way, but the method that worked for me was to implement hook_preprocess_views_view_field() and add it to the session variable:

function solr_snippets_preprocess_views_view_field(&$variables) {
    $_SESSION['solr_snippets']['rowNum'] = $variables['row']->index;

}

That's it, works great and I can use the twig template to customize the SERP results. Credit to https://drupalium.com/articles/creating-custom-view-fields-programmatically for the basic module that I hacked apart to make this. Also Drupalize.me was a Godsend.

Just to reiterate to anyone looking to do the same - what I did here was definitely not "best practice." Be careful and good luck!


Is it safe to use a custom value for users.status column Currently status column can have only 2 values:

0 - inactive
1 - active

I need to add a new status for the user: temporarily inactive. Will it be safe if I use status = 2 for it?

Why would you need to?

You can attach a boolean or numeric field to the user entity.

Navigate to Admin -> Configuration -> Accounts -> Add Field.


Adding onclick attribute to menu links I'm trying to add the onclick attribute to some menu links in Drupal 8 in order to track conversions with Google.

Here's a tutorial for adding onclick events in Drupal 7 that uses the Menu Attributes module.

For Drupal 8, I looked at the Link attributes module and the Menu Link attributes module but these only allow you to add classes, not set the value for onclick.

Seems Menu Item Extras is the way to go now. It makes menu items fieldable. And you probably also get the proper template suggestions already.

  Menu Item Extras provides extra fields for the Menu Items without
  using additional entities. This module is NOT an alternative of all
  Mega Menu modules - it is unique implementation of Drupal core’s Menu
  system. All fields are placed upon the Menu Item edit/add form and use
  core Menu link content entity for storing all data.


Send list of node title and body via email to users I have a question and answer site.

I would like to send via email a list of the node title and node body of all questions created over a period e.g 24hrs or 1 week to users on my site.

I do not know which module(s) would allow me select nodes of type question and then send the list via email to users on my site.

Thank you in anticipation

Hope this will help you create a module with hook_cron

    function mymodule_cron()  {

      $time_fetch=time();
    $result = db_query("SELECT node.title AS node_title, node.nid AS nid, node.created AS node_created, 'node' AS field_data_body_node_entity_type
    FROM
    {node} node
    LEFT JOIN {node_revision} node_revision ON node.vid = node_revision.vid
    LEFT JOIN {node} node_node_revision ON node_revision.nid = node_node_revision.nid
    WHERE (( (node.status = '1') AND (node.type IN  ('question')) AND (node.created BETWEEN $time_fetch+0 AND $time_fetch -604800) ))
    ORDER BY node_created DESC")->fetchAll(PDO::FETCH_ASSOC);
            //WHERE date BETWEEN DATE(NOW( ) + INTERVAL 7 DAY ))->fetchAll(PDO::FETCH_ASSOC);
        $all_user = db_query("SELECT users.mail AS users_mail, users.uid AS uid, users.created AS users_created
    FROM
    {users} users
    WHERE (( (users.status <> '0') ))
    ORDER BY users_created DESC")->fetchAll(PDO::FETCH_ASSOC);

        foreach ($result as $mail_data)
        {
            foreach ($all_user as $user_mail) {
            //dpm($mail_data);
            //dpm($user_mail);
//here i think you can use the drupal_mail function
            //$message = drupal_mail('mymodule', 'message_key', $to, user_preferred_language($user), array('body' => $body, 'subject' => $subject, $from, TRUE));

        }
        }
        }

the drupal mail api is here drupal_mail


Combining fields and avoiding duplicate display I use below code for printing out images in search results. I get double print outs on the ALT tags. If I disable ALT tags all displays just fine.

<a href="<?php print $url; ?>" class="search-result-img-wrapper">
    <?php
      print theme_image_style(array(
        'style_name' => 'thumbnail',
        'path' => $result['node']->field_image['und'][0]['uri'],
        'alt' => $title,
        'attributes' => array('class' => 'search-result-img'),
      ));
    ?>

  <a href="<?php print $url; ?>" class="search-result-img-wrapper">
    <?php
      print theme_image_style(array(
        'style_name' => 'thumbnail',
        'path' => $result['node']->field_product_image['und'][0]['uri'],
        'alt' => $title,
        'attributes' => array('class' => 'search-result-img'),
      ));
    ?>

If I add fields like below, I get only the print out of one of the fields and not both.

<a href="<?php print $url; ?>" class="search-result-img-wrapper">
    <?php
      print theme_image_style(array(
        'style_name' => 'thumbnail',
        'path' => $result['node']->field_product_image['und'][0]['uri'],
        'path' => $result['node']->field_image['und'][0]['uri'],
        'alt' => $title,
        'attributes' => array('class' => 'search-result-img'),
      ));
    ?>

What am I missing? Thanks much for your input.

I don't think this will necessarily fix your problem, but you're calling the theme_image_style incorrectly, it should be:

theme('image_style', array(
  'style_name' => 'thumbnail',
  'path' => $result['node']->field_image['und'][0]['uri'],
  'alt' => $title,
  'title' => $title,
  'attributes' => array('class' => 'search-result-img'),
));

Your second example is wrong, you can't call path twice.


Check if node update is published I've a content type with a workflow.
I have to notify users when the published version of the node is update.

Have I to check which transition is used? How?

I'm using an hook_node_presave.

[EDIT]
It seems that check if it's the default revision could be right:

 $entity->isDefaultRevision();

From draft to draft is false.
From draft to published is true.
From published to published is true.

Could be the right way?

As an alternative, consider using the Content moderation notifications module:

  Allows notifications to be sent to all users of a particular role, or to the content's author when a piece of content is transitioned from one state to another via core's content_moderation module.

I've used it with good results in several sites.


Content Type admin-side UI I have a custom content type which has grown in fields count and all that UI hints and stuff. It now takes about 4-5 screens to scroll. I was wondering if anyone knows of a module/way that allows to re-organize the Add Content UI form into sections. For instance - I would like to have all head data (title, teaser text, description) on a separate tab, all taxonomy qualifiers on another one, all images and uploads on yet another one, etc.

I think such a re-organized way will be much more friendly for the client to fill up with info and to maintain as well.

Anyone?
Artur

See the Multistep module. Although it is under development for Drupal 7.


How can I convert HTML entities imported from CSV via Feeds in to readable characters? This relates to a prior question - How can I convert character entities to display as 'normal' characters in Drupal?

It looks as if the CSV file itself is imported via Feeds, so I assume that it's Feeds that should 'parse' the HTML entities and convert them in to readable characters (Unicode?).

Is there some sort of extension or patch available for Feeds that can help me to do this?

Feeds Tamper allows you to html decode your feeds content before nodes are saved.


Hook to fetch data after a node update I have used editable views module to get a single page to edit the nodes. I want to store the updated details to an external table.

I have used hook_node_update but it only saves the first node's value to my external table not the rest of nodes(I have 18 nodes in a single page to edit).

function pmr_data_table_node_update($node) {

  if($node->type == 'upload_data'){
    $node_id = $node->nid;
    $profit = $node->field1['und'][0]['value'];
    $satisfaction = $node->field2['und'][0]['value'];
    $from = $node->field3['und'][0]['value'];
    $to = $node->field3['und'][0]['value2'];

    $newDate = date("Y-m-d H:i:s", strtotime($to));

    $entry = db_update('table_name')
     ->fields(array(
     'profitability' => $profit,
     'customer_satisfaction' => $satisfaction,
     ))
     ->condition('nid', $node_id, '=')
     ->condition('to_date', $newDate, '=')
     ->execute();
    drupal_set_message('Data updated successfully.');

  }

}

The above code only saves the first node in the editable view list. Can anybody suggest how can I save all the field values in a single round? Is there any hook where I can use to save the all the changed field values to the external table?

OR

Is there any hook by which I could get the data just after the set of nodes are updated?

The thing I didn't understand is how are you updating the nodes? you said in a single page edit? what does this mean? do you mean vbo? or is it in node page view?

Because your code seems right and should run on every node and if you are using vbo so it would be an issue related to it!

if you can explain more I'd be happy to help


Javascript/CSS from module not loading I am using a custom module (copied from a site where it is working)

The module's .info file is as follows:

name = jCarousel Rotator
description = An image rotator implementing the jCarousel jQuery plugin
package = mymodules
core = 7.x

stylesheets[all][] = css/jcarousel_rotator.css
scripts[] = js/jquery.jcarousel.min.js
scripts[] = js/jcarousel_rotator.js

But none of these files are loading.  The theme I'm in is made from scratch.. is there something that needs to be added to the template.php for those include hooks to work?

I searched all the code of the old site and the files are not being explicitly loaded elsewhere.

I have been able to load the files by adding the code manually to the footer, but this is not a great way to have a module integrated.

As requested, my html.tpl.php is as follows:

<?php include 'header.php'; ?>
<?php echo $page; ?>
<?php include 'footer.php'; ?>

Based on your edit including html.tpl.php, I agree with Chapa that's it very, umm, "Un-Drupaly".  This is the default system rendering of html.tpl.php:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN"
  "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php print $language->language; ?>" version="XHTML+RDFa 1.0" dir="<?php print $language->dir; ?>"<?php print $rdf_namespaces; ?>>

<head profile="<?php print $grddl_profile; ?>">
  <?php print $head; ?>
  <title><?php print $head_title; ?></title>
  <?php print $styles; ?>
  <?php print $scripts; ?>

<body class="<?php print $classes; ?>" <?php print $attributes;?>>

    <?php print t('Skip to main content'); ?>

  <?php print $page_top; ?>
  <?php print $page; ?>
  <?php print $page_bottom; ?>

You see where it says:

<?php print $styles; ?>
<?php print $scripts; ?>

That's where Drupal dumps your JavaScript and CSS files.  If you're not making those calls chances are you're not going to get any included files.  I guess to verify this you'd also have to edit in your header.php and footer.php files so we can see what they contain.  This is where you want to start looking.

I recommend backing up your existing html.tpl.php file to somewhere, and then overwriting it with the system version of it, which can be found at modules/system/html.tpl.php relative to the root directory of your site on your system.


How to check for differences in config Is there any way to check for differences with config in Drush 8?

I checked the list of drush 8 config commands and I couldn't find anything.

The reason I need this is that I have a site that runs behat tests via CircleCI, and sometimes I need to import the configuration more than once.  So, I wanted to write a bash script that uses Drush to check whether there are any configuration differences, and if so, automatically re-imports the config in a loop until there are no more differences.

I'm stuck on Drush 8 because the behat extension only supports Drush 8.

If you have Drupal console installed, you could try config:diff


create email id for registered users in Drupal 7 and Nginx I am working on a Drupal 7 site which lets users to register using their email, when the user verifies their email address, I am planning to create new email address for them to use, which has extensions as my domain.

Suppose my Domain is http://abcd.com When Mr. X YZ register and verify his registration he will automatically get new email address from me as x.yz@abcd.com.

How do I accomplish this with Drupal ? Can this be done via server-side if so then I have Nginx server, do I need SMPT {} Block for that ?

I was thinking to ask users to use google mail service to login to their email address provided by me. Still, not sure how to accomplish that one as well.

I feel I am really missing something, as I was searching around, there were few suggestions about Postfix but I really don't know what it is, and how it works.

Nginx won't help you. It can act as a mail proxy. But you need an MTA: Sendmail, Postfix to create a new mail account on your domain. Take a look here:

https://stackoverflow.com/questions/5273163/how-can-create-email-id-using-shell-exec-or-exec-in-php

You will require root permissions.


Commerce coupon only one coupon active at a time I have 3 types of coupons on my site, 2 of them are contrib(fixed amount and percentage amount) and 3rd one is custom(pretty much copy of percentage).
  I need to make sure, that only one coupon of custom type can be active at given time. Which hooks should I use to make sure that when one coupon of custom type is made active, the other one becomes not active?

Thanks in advance

My solution is as follows.
1. Check if entity created is a coupon and that coupon type is the one im checking using hook_entity_insert and hook_entity_update
2. Check if coupon changed or inserted has been put active if yes then load all other coupons of right type and turn them inactive


Rendering Taxonomy Custom Fields in page.tpl.php Ahoy all, so, having some issues with displaying specific fields related to taxonomy terms in a page I created (page--taxonomy.tpl.php)

Essentially, I am trying to set a background image to a div, to pull from an image field (field_hero_image)on the taxonomy term. I have this working for normal nodes just fine with the following code:

<div id="herowrap" style="background:url(<?php echo file_create_url($node->field_hero_image[$node->language][0]['uri']); ?>) no-repeat center center;background-size: cover;">

However, been having difficulty understanding how to modify this to pull this same image field from taxonomy terms.

It needs to be in page--taxonomy.tpl.php as it is being pulled before the node.tpl.php is being called (if i understand correctly?)

Any reason I can pull this easily from nodes, and not for taxonomy terms?

Thanks for any help!

Dan

I suggest taking a look at the 2 answers to this question. I think it's a similar case.


Is there a way to create an openlayers map that adjusts size with an adaptive layout? I'm building a site that will incorporate data mapped from users quite extensively, and I'd like the front page to mostly be just a map showing various relevant data. I'm also trying to build the site in a way that is adapted to mobile use.

I have an openlayers map constructed, it displays data, mostly behaves as I'd like, and I have it on the front page. That's all good. What I'd like to do is have the map become narrower in order to respond to display size. I'm currently using the omega them and I can get other elements to respond, but not the map.

Is there a way to clip the map? Can I bring in different map displays for different screens? Is this in any way possible?

I'm nearly completely new to all of this, learning css/js/php on the fly as I run into issues. I feel like this might be something js can help with (I found this link, for instance: http://pastebin.com/GumWwSMB), but I'm not sure if it's appropriate/best nor where/how to implement it.

Thanks for your help.

Oy. Okay. After poking around even more I found a much, much better solution, and now the whole question seems silly.

When setting up a map to display the data (in Administration >> Structure >> OpenLayers >> Maps), just set map width to "auto." Then it mods all on it's own. One display (block or page), and you don't even need to add any extra css to the container. It just responds. Somehow I completely forgot that auto width was an option when building the map. Super easy!


Is there a way to sort by taxonomy? On the the main content page: mysite.com/admin/content we are allowed to sort by a few criteria. Sort by content type, published date etc. but is there a way to sort by taxonomy? It seems like previous versions of drupal could do this. But not so in 7? I know you can create a view to handle this, but i am curious if its possible to accomplish the functionality via the content admin page.

There's no way to do it with the default content admin page, short of writing code to alter the form. Vocabularies aren't linked exclusively to nodes in Drupal 7, they can be linked to any type of entity using the field system, so having this functionality wouldn't make sense by default any more.

Creating a View is definitely the right way to go; personally I'd install the Administration Views module which replaces (amongst others) the default content admin page with a View.

The module page says it provides support for filtering by vocabulary out of the box, but even if it doesn't provide sorting you could easily just tweak the View to your own requirements.


Errors from custom FieldItemList::getConstraints() displayed next to every single property Summary

Errors set by constraints on custom field types appear next to every single property by default.

We can use the ::errorElement() method on the widget to place errors that come from the ::getConstraints() method of the field item.

However, errors that come from ::getConstraints() in a custom field item list will not go through ::errorElement(). How can we reasonably place them?

Details

My original problem ist very complicated. I've drastically simplified it to show only what's essential. We start with a very simple custom field type with 2 number properties.

class YearRangeType extends FieldItemBase {
  public static function propertyDefinitions($field_definition) {
    $properties['start'] = DataDefinition::create('integer');
    $properties['end'] = DataDefinition::create('integer');
    return $properties;
  }

  public static function schema($field_definition) {
    $schema = ['columns' => [
      'start' => ['type' => 'int',],
      'end' => ['type' => 'int',],
    ],];
    return $schema;
  }

  public function isEmpty() {
    $start = $this->get('start')->getValue();
    $end = $this->get('end')->getValue();
    return !($start || $end);
  }
}

We define a custom FieldItemList for it that adds a simple validation: checking if at least 2 items are present.

class YearRangeItemList extends FieldItemList {
  public function getConstraints() {
    $constraints = parent::getConstraints();
    $constraints[] = $this->getTypedDataManager()
      ->getValidationConstraintManager()
      ->create('Count', [
        'min' => 2
      ]);
    return $constraints;
  }
}

When I try to save only one item, the field will look like this:

If the errors would result from YearRangeType::getConstraints(), we could use theerrorElement()` method of the widget to place them.

However, the Drupal core class WidgetBase does deliberately not pass errors set by the item list to errorElement(), see these lines in the Drupal core code (version 8.8.1).

How else should we place them?

We can place the errors with three modifications in the widget class.

First, we add the empty form element non_field_errors we can attach the errors to.

class YearRangeWidget extends WidgetBase {
    ...
    public function form($items, &$form, $form_state, $get_delta = NULL) {
        $formElement = parent::form($items, $form, $form_state, $get_delta);
        $formElement['non_field_errors'] = ['#type' => 'item'];
        return $formElement;
    }
    ...
}

Second, in the flagErrors method, we collect all errors that do not belong to any property and call a separate method to treat them.

class YearRangeWidget extends WidgetBase {
    ...
    public function flagErrors($items, $violations, $form, $form_state) {
        $listViolations = [];
        foreach ($violations as $key => $violation) {
            if ($violation->getPropertyPath() === '') {
                $listViolations[] = $violation;
                $violations->remove($key);
            }
        }
        parent::flagErrors($items, $violations, $form, $form_state);
        $this->flagNonFieldErrors($items, $listViolations, $form, $form_state);
    }
    ...
}

Third, we define the method treating the separated errors.

class YearRangeWidget extends WidgetBase {
    ...
    public function flagNonFieldErrors($items, $violations, $form, $form_state) {
        $field = $items->getName();
        foreach ($violations as $violation) {
            $form_state->setError(
                $form[$field]['non_field_errors'],
                $violation->getMessage()
            );
        }
    }
    ...
}


How can I clone all field values when creating a node translation (entity_translation) programmatically? I use entity_translation and have an en node currently without translations. Assume it has fields field_foo and field_bar so currently they are:

$node->field_foo['en'][0]['value'] = 'foo';
$node->field_bar['en'][0]['value'] = 'bar';

I want to programmatically add anfr translation but only translate field_foo so I do:

$node->field_foo['fr'][0]['value'] = 'foo FR';

entity_translation_get_handler('node', $node)->setTranslation(array(
  'translate' => 0,
  'language' => 'fr',
  'source' => 'en'
), $node);
field_attach_update('node', $node);

This works but now if I edit (or devel) the fr node, field_bar is empty. On the frontend it does show "bar" which is the en value, but I've noticed that if I create the translation via the Drupal UI then the field_bar is not empty and contains a copy of the en value.

So, does anyone know of a way that the API will copy all values upon translation creation? Or should I be doing that myself manually via the code?

I ended up doing it manually via code:

function _populate_translation_values($node, $targetLanguage) {
  $fields = field_info_instances('node', $node->type);
  foreach($fields as $fieldName=>$fieldInstance) {
    $fieldInfo = field_info_field($fieldName);

    // only process translatable fields
    if (!$fieldInfo['translatable']) continue;

    // ignore fields which are complicated to copy - could be fixed in the future
    if (in_array($fieldInfo['type'], array('field_collection'))) continue;

    // skip fields which already have a value in the target language
    if (isset($node->{$fieldName}[$targetLanguage])) continue;

    // skip fields which don't have a value in the source language
    if (!isset($node->{$fieldName}[$node->language])) continue;

    // copy value
    $node->{$fieldName}[$targetLanguage] = $node->{$fieldName}[$node->language];
  }
}


How to reset/save $_SESSION variables in forms for each user? I need to add captcha to user login form after 3 failed logins.

To do so I built the following module, and used $_SESSION['failed_login'] to keep track of the number of the failed logins.

This module works well, but when I close the browser and test a failed login again, the number that is stored via watchdog will not reset again from 1, it continues increasingly.

<?php

function failed_login_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'user_login') {
        $form['#validate'][] = 'failed_login_myloginhandler';
    }
}

function failed_login_myloginhandler(&$form, &$form_state) {
    global $user;
    if (!$user->uid) {
        if(!$_SESSION['failed_login'])
            $_SESSION['failed_login'] = 0;
        $_SESSION['failed_login']++;
        watchdog("error", $_SESSION['failed_login']);
    }
}

What is the problem? Why it is not reset from 1 again? How can I have this temporary variable for each user who is trying to login?

By default Drupal's sessions are kept for about 23 days. You can modify this in settings.php. Look for gc_maxlifetime and cookie_lifetime to reduce it to 0 so sessions are destroyed when the browser is closed.

This will effect logged in users too so when they close the browser they will also be logged out.

On a side note if you were unaware drupal already have flood control and will block IPs for multiple failed login attempts


and  links not generated as https: I am new to Drupal and having an issue relating to SSL. The view I'm working with is using the jcarousel module to display images with links.

The data contains a link and image source. All of the links are entered using relative paths to the root of the site.

The home page has 5 links on it. When the you look at the source from the generated page, 2 of the links are https and the other 3 http even though none have the base URL in the link data.

I have added $_SERVER['HTTPS'] = 'on'; to settings.php but that hasn't corrected the issue.

What is the proper way to force both tags to be generated with https: links?

Take a look at this answer, I believe it goes into great detail about enabling SSL support on pages and image assets for Drupal 7;

How to force drupal 7 to load HTTPS assets?

Also if your still having problems, take a look at this documentation on drupal.org;

https://www.drupal.org/https-information

Hope that helps!


Call User Profile Field in Node Template I have a field in my user profile of byline (field_byline). I'd like to call this in the node template so that the byline is included next to the author's name (e.g. Posted by Mr. Rogers | Sweater Entrepreneur) I kind of have it working, but not quite there yet. I'm using Drupal 7.10

Right now, I have this in my template.php

global $user;
  $user = user_load($user->uid);
  $bylines = field_get_items('user', $user, 'field_byline');
  if ($bylines) {
    $vars['field_byline'] = $bylines[0]['value'];
  }

}

And this in my node.tpl.php

if (isset($field_byline) && !empty($field_byline)) :
  echo '| ' . $field_byline.'';
endif;

But, my problem is this only calls the correct byline while viewing the individual node. It breaks on the front page when all the nodes are looped out and only displays the byline of the first user, not the one that wrote the post.

Any help or direction would be much appreciated!

global $user is that of the currently logged in user, not specifically the owner of any specific content.

So what your code was doing was just looping through printing your byline, eg, admin, eg uid 1.  What you need to do is grab the uid from the specific user's content, user_load(THAT-UID) into a variable, and then use that to get the byline into vars[] in hook_preprocess_node() so it goes to the specific node in question, not the page it is printed on.

(in D6 at least, still learning D7 but I am sure it's pretty similar)

Addition/Edit:  In D6, you can get the uid of the node author like this:

function hook_preprocess_node(&$vars) {

  $node=$vars['node'];
  $uid=$node->uid;

  $byline= "whatever you need to do to get it with $uid"

  $vars['byline']=$byline;

}

just change hook to your theme or module name and you should be on your way.  You can now use the byline variable in your node.tpl.php (barring any typos or brainfades of mine above :)


How to fix Bootstrap theme overlapping on views administration pages Using bootstrap as an administration theme. Required rather than seven because of the way we are getting people to contribute to the site.

Under views contextual filters, they layout falls apart. Anybody solved this? See under "Path component".

I have tried debugging the page and setting clear:both everywhere etc.

It is possible to set the admin theme just for views in the views settings page: admin/structure/views/settings. "Custom admin theme for the Views UI".

This does not fix the bootstrap theme problem, but it does solve my problem where I want to use the bootstrap theme for content administration actions.

Secondly, to solve my problem where I want a consistent user interface when viewing and editing content under admin/appearance there is a setting

Use the administration theme when editing or creating content.

This enables me to provide people submitting content with the same experience as viewing.