How can I filter a view according to another view's results I have one view with two display: "latest news" and "populer news"

I want show two block side by side like mashable.com.

I can easily do that of course but one problem. There are same news both block.
I want to hide news in the "latest news block" according to "populer news block".

How can I do that?

This module might help you Views exclude previous

  The Views exclude previous module provides a views filter that
  excludes nodes that have already been loaded/displayed on the current
  page.

It excludes node in previous views loaded in your views. Example: you have two views block loading in the same page and the two block shows same node in views; you can exclude the other one in display, you can find the additional field in filter criteria in views configuration of your block. See image attached


Block on user profile only I have blocks for several profile types that links to users photos videos etc. (think myspace)

With arguments it works nice, block is visible only on page created by userXY and leads to other content made by userXY.

But, when userXY logs into his account and goes to "My account" it leads to www.example.com/user

Now blocks from all profile types are visible and they lead to false urls. The correct block is also there and works well but i can't find a way to limit other blocks not to be shown here.

I am using profile2, tokens and real name module.

Other problem which was thinking of to solve the issue was to change pattern for /user into /role/realname or anything that will change from default /user but nothing seems to work (pattern is ignored).

I think you have 2 main options:

You can use some custom PHP to control the blocks visibility. Something like:

global $user;
$account = user_load($user->uid);
if($account->profile_type[LANGUAGE_NONE][0]['value'] == 'some value') return true;
return false;

Or I think this is a good use case for the Context module. This allows you to create different "contexts" that your blocks should appear in. An example from the Context help file says:

You want to create a "pressroom" section of your site. You have a press room view that displays press release nodes, but you also want to tie a book with media resources tightly to this section. You would also like a contact block you've made to appear whenever a user is in the pressroom section.

Add a new context on admin/build/context
Under "Conditions", associate the pressroom nodetype, the pressroom view, and the media kit book with the context.
Under "Reactions > Menu", choose the pressroom menu item to be set active.
Under "Reactions > Blocks", add the contact block to a region.
Save the context.


Custom form using custom template, submit the form don't call its validate and submit handlers I created a simple custom module where I created a Class Form using a custom template form. If I don't use my custom template (I comment my _theme hook from my .module), when I submit my form, class methods handlers validate and submit are called. But When I use my custom form template, If I submit my form, validate and submit class methods handlers aren't called, I don't understand why.

This is my code; I begin with my templates/form--myformtest-form.html.twig template.

TEST

<form{{ element }}></form>

My myformtest.module code is the following.

/**
 * Implements hook_theme().
 */
function myformtest_theme($existing, $type, $theme, $path)
{
  return array(
    'form__myformtest_form' => array(
      'render element' => 'form',
      'template' => 'form--myformtest-form',
    ),
  );
}

If I comment this hook, my form use the default theme form template. In this case, submit the form call validate and submit class handlers methods. If I don't comment this hook, my form use my custom template. Then when I access to my custom form page and valid the form, validate and submit handler are never called.

This is the simple code from my src/Form/MyformtestForm.php class.

class MyformtestForm extends FormBase {
  //...
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['textfieldtest'] = [
      '#type' => 'textfield',
      '#title' => $this->t('textfieldtest'),
      '#maxlength' => 64,
      '#size' => 64,
    ];

    $form['submit'] = [
        '#type' => 'submit',
        '#value' => t('Submit'),
    ];

    return $form;
  }

  public function validateForm(array &$form, FormStateInterface $form_state) {
    ksm("MyformtestForm Validate handler!");
    // logs never displayed when I use my custom template. If I don't use the custom template, this log appears.
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    ksm("MyformtestForm Submit handler");
    // logs never displayed when I use my custom template. If I don't use the custom template, this log appears.
  }

Why handlers aren't called when my form use my custom override? How can I call them?

These are the variables existing from my custom template when I load my form page.

You need "base hook" in there, I believe.

Here's an example:

/**
 * Implements hook_theme().
 */
function formcustomtemplate_theme() {
  return array(
    'form__my_form_test' => array(
      'render element' => 'form',
      'template' => 'form--myformtest-form',
      'base hook' => 'form',
    ),
  );
}

If you are using a custom theme, and you don't need the template in your module, the approach of creating a new theme hook for your custom form is unnecessary.
Rather than create a new theme hook, use hook_theme_suggestions_alter in your theme:

/**
 * Implements hook_theme_suggestions_alter().
 */
function mytheme_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {

  if ($hook == 'form' & !empty($variables['element']['#theme'])) {
    $suggestions[] = 'form__' . $variables['element']['#theme'][0];
  }

}

then create the appopriate template in your theme.

then to see the theme suggestions output to the page, turn on twig debugging:

https://drupalize.me/blog/201405/lets-debug-twig-drupal-8

You'll see template suggestions in the markup:

<!-- FILE NAME SUGGESTIONS:
   * form--myformtest-form.html.twig
   x form.html.twig
-->

You can see that it's not yet picking up your template, so create a template file by copying the form.html.twig and renaming it.

To check where Drupal is looking for templates using the "form" hook, you can print out the theme registry from hook_theme_registry_alter:

 "form" => array:6 [▼
    "template" => "form"
    "path" => "themes/custom/mycustomtheme/templates/form"
    "type" => "theme_engine"
    "theme path" => "themes/custom/mycustomtheme”
    "render element" => "element"
    "preprocess functions" => array:4 [ …4]

This lets you know that you need to put the template in that directory.


How to bypass required fields in form validation function of a module? I have a form with two radios and two forms related to each of them. These forms have some required fields. user can just check one radio and then fill in one form. but then clicks on submit button drupal gives error for those unselected and empty field ( which are required but now they are not required because their radio isn't selected) .

How can I bypass those required inputs in my module ? I am developing my module's form with Form API.

If you are building your own form, you need to remove '#required' => TRUE, from field to bypass validation or assign FALSE value.

Example with required field:

$form['title'] = array(
  '#type' => 'textfield',
  '#title' => t('Subject'),
  '#default_value' => 'whatever',
  '#size' => 60,
  '#required' => TRUE, // remove this if you want to bypass or give it FALSE value
);

Check Form API Reference for more details

Now you can do the same for existing form by alter the form using hook_alter_form and unset required attribute or assign FALSE value.

Example:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'FORM_ID') {
    $form['FIELD_NAME']['#required'] = FALSE;
    // or
    unset($form['FIELD_NAME']['#required']);
  }
}


Views PDF pagination Is it possible to add a pagination to a pdf when using views pdf module in drupal 7. Or is there any custom module.

Yes it is possible with https://www.drupal.org/project/views_pdf. Just make the view page as any other view.


Using jQuery .ajaxstart with views exposed filter To start with, my goal was to alter the ajax loading behavior in views exposed filter (Druapl 7 and Views 7.x-3.3) and this question pretty much sorted that one out: How do I change the ajax loading behaviour in Views?

Here comes the problem, the jQuery .ajaxStart and .ajaxSuccess doesn't seem to fire when i change the exposed filter in the view.
I get my custom.js file to load correctly and this simple code works just fine:

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

      alert('message');

    }
  };
})(jQuery);

but replacing my alert message with this does not:

$('#views-exposed-form-produkter-3-kol-page', context).ajaxStart(function(){
        $('#views-exposed-form-produkter-3-kol-page,div.view-id-produkter_3_kol', context).fadeTo(300, 0.5);
      });
      $('#views-exposed-form-produkter-3-kol-page', context).ajaxSuccess(function(){
         $('#views-exposed-form-produkter-3-kol-page', context).fadeTo(300, 1.0);
         $('div.view-id-produkter_3_kol', context).css('opacity', 0.5).fadeTo(300, 1.0);
      });

I have also tried to use $(document).ajaxStart without success.
The fading also works if i remove the ajaxStart and allow it to fade when page is loaded.

So, if i could get the ajaxStart and Success to fire, everything else should work like I wanted it.

(This is my first question here, so I hope I've managed to do it the right way)

I found another js file that was causing the error, decided to live without it and everything works after removing it.

So, if someone encounter errors like this, change the the default theme and see if that solves the problem, then you know if the issue is within your custom theme or somewhere else.


Create a rule to send confirmation email message after anonymous/authenticated user has created content I have created a custom content type (CCK) called apply (machine name) and installed the Rules module. How would I go about sending the user an email (they could be anonymous or authenticated) after they have created content. I understand that I have to create a rule of some sort, could someone please walk me through it?

I want to capture the content of field_email_address somehow, as that is the field in which the user will be entering their email address.

This is my rule so far, not sure what to put in the Conditions and Elements section.

Rules works with the token module. If you haven't installed it, do so now.
In your "apply" content type ("application" would be a better name), ensure that your email field is required, and set the default to use token [current-user:mail] so that it fills with the current user's details if they're logged in.
"Conditions" is the "if" part of your rule. You use it to narrow down when the rule fires and by whom. Given that you're not needing auth, you can leave this empty. You could test for various node / field properties here e.g. node is published / field has value etc. Because you specified a content type in your "Event", the fields from that content type will become available to the subsequent "Conditions" and "Actions".
"Actions" are what happens when you trigger your rule. This is where you specify the email action. Click "Add an action", and from the supplied dropdown, choose "System > Send mail" or "Send HTML email".
In the "to" field, you can now add a token referencing the user email - probably something like [node:field_email_address]. Click the "Replacement patterns" accordion to see available tokens for each mail param.
It you're wanting to templatize & theme your HTML emails, that's possible through other modules (mimemail + mailsystem) but requires a separate discussion.


How to migrate content from json? I have a json file like this
{
  "online": false,
  "key": "123",
  "Product": {
    "name": "product name",
    "Id": 12,
  },
}

I have my json migration file
source:
  plugin: url
  data_fetcher_plugin: file
  data_parser_plugin: json
  urls:
    - 'json_path/data.json'
  item_selector: /Product
  fields:
    - name: keyword
      label: 'Keyword'
      selector: name
  ids:
    product_key:
      type: string
  constants:
    vocabulary: tag
process:
  vid: constants/vocabulary
  name: keyword
destination:
  plugin: entity:taxonomy_term

but I am getting the following error.
Drupal\Core\Database\IntegrityConstraintViolationException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'name' cannot be null

It means the xpath is not correct.
I have tried with the item_selector: $ and for the keyword selector selector: Product.name but then I am getting this error.
Passed variable is not an array or object

I have tried with item_selector: 0 and item_selector: / but nothing worked.
However when I use the following json.
{
  "online": false,
  "key": "123",
  "Product": [
    {
      "name": "product name",
      "Id": 12,
    }
  ],
}

Notice the [] brackets.
What is the issue? How can I make it work without the [] brackets because I don't have any control on the json to change it.

The data_parser_plugin: json always expects an array with numeric keys as item_selector, there is no way you can get around this requirement in YAML. If you want to use a single object as item_selector, you have to create your own data_parser_plugin.
I've already had that problem in a previous object and creates my custom plugin and used my custom data_parser_plugin: single_json_object in YAML instead.
file MY_MODULE/src/Plugin/migrate_plus/data_parser/SingleJsonObject.php
<?php

namespace Drupal\MY_MODULE\Plugin\migrate_plus\data_parser;

use Drupal\migrate_plus\Plugin\migrate_plus\data_parser\Json;

/**
 * Obtain JSON data for migration.
 *
 * @DataParser(
 *   id = "single_json_object",
 *   title = @Translation("Single JSON object as root")
 * )
 */
class SingleJsonObject extends Json {

  protected function has_string_keys(array $array) {
    return count(array_filter(array_keys($array), 'is_string')) > 0;
  }

  protected function getSourceData($url) {
    $source_data = parent::getSourceData($url);

    if ($this->has_string_keys($source_data)) {
      $sequential_array = [];
      $sequential_array[] = $source_data;
      $source_data = $sequential_array;
    }

    return $source_data;
  }
}


how to customized user login page My question is when i  browse  my admin site www.example.com/user a simple login page will appear.

Here in this login form there is no option for forget password .so I need option to request new password and new password can be send through email.

You can make a template to alter your user login form.

In template.php:

function YOURTHEMENAME_theme(){
    return array(
        'user_login' => array(
            'arguments' => array('form' => NULL),
            'render element' => 'form',
            'template' => 'templates/user-login-form',
        ),
  );
}

Then create user-login-form.tpl.php in your template folder and print the login form using

print drupal_render_children($form);

Don't forget to clear cache


Howto get ID on newly created content through Drupal 8 REST POST I have a working decoupled/headless setup working using Drupal 8 beta 10 as a backend, and a html5/js webapp as frontend, on seperate servers.

For this scenario, I'm succesfully able to post new content (an article node) as an anonymous user, using the REST /entity/node endpoint.

This works fine, I receive a 201 "Created" response, but now I'm trying to figure out a way to get the ID of this newly created node so I can GET and render it.

The current documentation and response does not provide a return (N)ID. Am I overlooking something or is this a bug?

Looking at the response code for POST requests, we can see that there's no body but a header set to the full URI of the node. You can save that URI or explode it/parse it to get just the nid.

  // 201 Created responses have an empty body.
  return new ResourceResponse(NULL, 201, array('Location' => $entity->url('canonical', ['absolute' => TRUE])));


How do I print a view table? I am using Drupal 7 with the Print module installed.
I used this module to print nodes, but how can I print a view table?

Is there a module that I can use?

Most people just use a stylesheet to exclude layout for printing. it does not rely on any particular module.

The idea is simple, you include a stylesheet in your theme which removes the layout from your site, typically by using style:display:none; etc. You also size the font and remove images where possible to save ink.

You can read a really good tutorial here: http://www.alistapart.com/articles/goingtoprint/


Add access code per page I need to create 10 or so pages that are linked in a specific order but can only be accessible when the user enters the correct access code.

The first page would be open and "unlocked" - but the user will need to enter some details before being able to see the next page, they would be presented with the access code for the 2nd page and this would be added to their user profile as their current access code level.

To see the next page, the user would require to enter a specific code to unlock that page.

How would I go about getting this to work? From what I know, webforms would be useful for "linking the pages in order" but I haven't found a way where you must enter a "password" access the next page of the form.

The idea is that the 10 pages would act as 10 different levels for a simple learning "game."

My first reaction would be to create 10 roles (Level 0 to 9) and to restrict access to the pages using Content Access to control access to the pages by role. Then use Rules to assign roles based on the tasks you set out in the learning game.


Drush 9 command equivalent to core-quick-drupal (qd)? In Drush 8, there is a core-quick-drupal (qd) command, however, it's missing in Drush 9.

Is there any equivalent command in Drush 9 which allows to download, install and serve Drupal with minimal configuration and dependencies?

drush qd is not currently available in Drush 9. It would be easy enough to make a short shell script to call composer create-project followed by drush site-install and drush uli.

This command will probably reappear in a later release, sometime after 9.0.0 stable. A pull request that implemented qd would also be welcome.


Create users to post unplublished nodes so admin could approve How can I create some users in Drupal 6 to post unpublished nodes so that admin could approve those unpublished node?

There are multiple ways.  (Edit:The workbench module is very popular, but is for Drupal 7 only). I have achieved good results using the revisioning module, which has a release for Drupal 6.


Invalid Argument Exception when saving a view using a custom filter handler I am working on a project which implements a custom views filter; more specifically based on the InOperator class.

I have been following the guide below to implement the custom filter:
Creating a custom Views filter in Drupal 8 and the repo used in that guide may be obtained here:
Accompanying GitHub repo

Everything works with both my custom filter, and the filter provided in the referenced guide whilst inspecting in the views preview, however when the view is saved, the website crashes with the following error:

InvalidArgumentException: The configuration property display.default.display_options.filters.node_titles.value.my_title doesn't exist. in Drupal\Core\Config\Schema\ArrayElement->get() (line 74 of core/lib/Drupal/Core/Config/Schema/ArrayElement.php)

Any advice on how to fix this or if there are any steps that have been missed out would be greatly appreciated; even if a link could be provided to more recent documentation as I have not found much on this subject other than reading through the base classes.  Even then I cannot find any reference to the error which is displayed.

To reproduce

Download the module in the linked repo and enable on a D8 site.
Create a view of nodes.
Add the 'Node titles' filter and select an option.
Save the view.

Many thanks in advance.

The problem here is that there is no schema definition defined for the new custom filter.

You need to create a file in config/schema/YOUR_MODULE.views.filter.yml

With the following definitions with the machine names to match your specific setup.

views.filter.YOUR_VARIABLE:
  type: views_filter
  label: 'Example'

views.filter_value.YOUR_VARIABLE:
  type: views.filter_value.in_operator
  label: 'Example'


How can I change the name attribute to "email" in the user login form? Users do not always login with their Drupal user name but in some projects by email for example.

What would be the Drupalitically correct way in this case to change the "name"-Attribute of the user name login text field in the user login form? For example to change it to "email" so that a HubSpot JS Snippet would recognize login form submissions? How would this be done in both Drupal 7 and Drupal 8?

This is a variation of a frequently asked question.

The user login form for Drupal is built using Drupal Form API.

In Drupal 7 core, the user login form is declared in user.module:

https://github.com/drupal/drupal/blob/7.x/modules/user/user.module#L2111

  // Display login form:
  $form['name'] = array('#type' => 'textfield',
    '#title' => t('Username'),
    '#size' => 60,
    '#maxlength' => USERNAME_MAX_LENGTH,
    '#required' => TRUE,
  );

  $form['name']['#description'] = t('Enter your @s username.', array('@s' => variable_get('site_name', 'Drupal')));
  $form['pass'] = array('#type' => 'password',
    '#title' => t('Password'),
    '#description' => t('Enter the password that accompanies your username.'),
    '#required' => TRUE,
  );
  $form['#validate'] = user_login_default_validators();
  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array('#type' => 'submit', '#value' => t('Log in'));

And in Drupal 8 core, it's declared in UserLoginForm.php:

https://github.com/drupal/core/blob/8.8.x/modules/user/src/Form/UserLoginForm.php#L94

    // Display login form:
    $form['name'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Username'),
      '#size' => 60,
      '#maxlength' => UserInterface::USERNAME_MAX_LENGTH,
      '#description' => $this->t('Enter your @s username.', ['@s' => $config->get('name')]),
      '#required' => TRUE,
      '#attributes' => [
        'autocorrect' => 'none',
        'autocapitalize' => 'none',
        'spellcheck' => 'false',
        'autofocus' => 'autofocus',
      ],
    ];

    $form['pass'] = [
      '#type' => 'password',
      '#title' => $this->t('Password'),
      '#size' => 60,
      '#description' => $this->t('Enter the password that accompanies your username.'),
      '#required' => TRUE,
    ];

    $form['actions'] = ['#type' => 'actions'];
    $form['actions']['submit'] = ['#type' => 'submit', '#value' => $this->t('Log in')];

If you need to customize it, you should not edit the code in core. Instead, you should do it using hook_form_alter() in a custom module.

This is a classic example of one of the first exercises new developers can do to learn how to build Drupal modules, and a web search should reveal many tutorials.

As @Jaypan pointed out in the comments above, you probably want to change the label on the field ($form['name']['#title']) rather than its name.

Here's an example of how to do that with hook_form_alter() in Drupal 7:

function YOUR_MODULE_NAME_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id=='user_login') {

     // This will change the field label from "Username" to "Email".
     // The t() function marks the string as translatable by Drupal.
     $form['name']['#title'] = t("Email");

  }
}

In Drupal 8, it's almost the same, but $form_state is now an object and must be type hinted as an instance of \Drupal\Core\Form\FormStateInterface:

function YOUR_MODULE_NAME_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id=='user_login') {

     // This will change the field label from "Username" to "Email".
     // The t() function marks the string as translatable by Drupal.
     $form['name']['#title'] = t("Email");

  }
}


How to update jQuery to version 1.4? I installed the jQuery Update module, version 6.x-2.0-alpha1, which supports jQuery 1.3.2. I need to update it to jQuery 1.4 or higher, for a jQuery plugin.

I tried replacing the existing jquery.js and jquery-min.js files in the jquery_update/replace directory with the latest jQuery files, and made some changes to jquery_update.module as suggested in Using Newer Versions of jQuery. After doing so, jQuery started loading from misc/jquery.js, which was an older version.

Is there any simple way to update jQuery? I cannot implement the noConflict solution since I will be using third-party jQuery plugins.

The dev version of jQuery Update for Drupal 6 will get you up to jQuery version 1.7 (but it does break some of the admin UI).

There are a few patches available, (see Fix jQuery 1.7 for Drupal 6 and the Issue Queue in general), with varying reported levels of success.

If you choose to go down the 'manual' route then you'll have a lot of core/contrib javascript to fix. I think your best bet would be to base whatever solution you come up with on the current dev release of jQuery Update.

If you specifically only need version 1.4.2, then there's some instructions on how to do it here.


theme("pager") returns NULL I am trying to use theme_pager to create pagination as below, but pagination does not appear. I have tried using var_dump(theme('pager', NULL, 10)) and the result is NULL.

$q="SELECT DISTINCT(node.nid) AS nid, node.type AS node_type, node.vid AS node_vid, node.title AS node_title, node.language AS node_language, node.created AS node_created, node_revisions.teaser AS node_revisions_teaser, node_revisions.format AS node_revisions_format FROM node node  LEFT JOIN node_revisions node_revisions ON node.vid = node_revisions.vid WHERE (node.type in ('slideshow')) AND (node.status <> 0) AND (node.language='$lang') GROUP BY nid ORDER BY node_created DESC";
$result = pager_query($q, 10, 0);
//Process data.
return $output . theme('pager', NULL, 10);

also i tried to simplify the query and to make it from one table as below, but this didn't work as well

SELECT nid, title, language, created FROM node WHERE node.type='slideshow' AND node.status  0 AND node.language='en' ORDER BY created DESC

Any idea is highly appreciated!

The problem is the query that is probably too complex, and pager_query() cannot alter it to obtain the total number of row matching the query passed as argument.
As reported in the documentation for pager_query():

  The pager uses LIMIT-based queries to fetch only the records required to render a certain page. However, it has to learn the total number of records returned by the query to compute the number of pages (the number of records / records per page). This is done by inserting COUNT(*) in the original query. For example, the query SELECT nid, type FROM node WHERE status = '1' ORDER BY sticky DESC, created DESC would be rewritten to read SELECT COUNT(*) FROM node WHERE status = '1' ORDER BY sticky DESC, created DESC. Rewriting the query is accomplished using a regular expression.

  Unfortunately, the rewrite rule does not always work as intended for queries that already have a COUNT(*) or a GROUP BY clause, and possibly for other complex queries. In those cases, you can optionally pass a query that will be used to count the records.

  For example, if you want to page the query SELECT COUNT(*), TYPE FROM node GROUP BY TYPE, pager_query() would invoke the incorrect query SELECT COUNT(*) FROM node GROUP BY TYPE. So instead, you should pass SELECT COUNT(DISTINCT(TYPE)) FROM node as the optional $count_query parameter.


Display VAT price on products I have added a 20% vat on my products. This is added during checkout. How can I add it to the display price when you view the product?

I'm assuming you're using the VAT module. Ubercart's prices aren't flexible enough to adjust the display price based on the VAT. You should probably enter the prices for each product including the VAT and adjust your uc_vat so the sell price is inclusive.


Parameters and key value pairs for VotingAPI My services definitions list notes that to 'select votes' using VotingAPI I have to POST the parameters 'type' (mandatory), and to 'set votes' I have to post a 'votes' array (mandatory) and 'criteria' array (optional). What are the key pair results I need to call these APIs? For 'type' I have tried 'percent', 'points', 'node', 'vote, but none of those work. For the votes array I need entity ID but how/where can I find the entity ID? I am needing to set and select votes which have been submitted on nodes.
Thank you

I solved it. The entity ID is the node id (nid) if you are voting on a node for example. eg for nid of 75, it is entity_id: 75. Other parameters are 'percent', 'points' or 'options' for vote type. And for tag it is 'vote' or whatever custom tag you created as a field.  The 'value' of course is the number you are voting. If you are using standard settings for 5star, you enter eg 20 (for 1 star), 40, 60, 80 or 100 (5 stars). The mandatory parameters are entity_id, tag and value. I've read the system can work out the other details, eg user id from the currently logged in user.

eg this format worked for me: let newVote = ["votes":[["value":100,"uid":32,"entity_id":1,"entity_type":"node","tag":"vote","value_type":"percent"]]]

see Votingapi REST server call internal server error - 'services exception: missing entity ID'


How can I add multiple field collections based on a reference on a new node I am trying to figure out how can I add multiple field collections to a node when a user starts filling out a node.

Here is how my nodes are basically set up:

Color Card Content Type:
 - id
 - name
 - colors_term_reference(multi select)

Style Content Type:
 - id
 - color_card_node_reference (select)
 - color_images_collection (unlimited field collection)
   - color_term (single select)
   - image

When a user starts filling out the node form, I want the field collections to get created and all the colors that were chosen in the color card get  preselected.

So ideally if color has the following colors: red, blue, and green, when a user starts filling out my style node and chooses that color card the field collection would have red, blue, and green preselected and they would only need to upload the images.

Color Card:
- id: 1
- name: Cool Colors
- colors_term_reference:
  10 (red)
  17 (blue)
  38 (green)

Style:
- id: 1
- color_card_node_reference: 1
- color_image_collection:
  0:
    color_term: 10,
    image:
  1:
    color_term: 17,
    image:
  2:
    color_term: 38:
    image:

I ended up using the same approach as How to create (& pre-populate) multiple “field collection” fields on an ajax call.

Use hook_form_FORM_ID_alter() to the node you need the functionality at.

// Add ajax callback when a node reference is entered or changed.
$form['field_node_reference'][LANGUAGE_NONE][0]['target_id']['#ajax'] = array(
  'callback' => 'your_module_ajax_rebuild_form',
  'wrapper' => 'field-collection-values',
);

Create ajax callback.

/**
 * Ajax callback, rebuilds and returns the field_collection_colorizer
 * element.
 */
function your_module_ajax_rebuild_form() {
  // Get Field collections and children.
  $field_collection_colorizer = &$form_state['field']['field_collection'][LANGUAGE_NONE];
  $field_childs = &$form_state['field']['field_collection'][LANGUAGE_NONE]['entity'];

  // Found that I had to set item and items count in order for this to work.
  $field_collection_colorizer['item_count'] = $options_count;
  $field_collection_colorizer['items_count'] = $options_count;

  // Create any new field collection instances if needed.
  for ($i = 0; $i < $field_collection_colorizer['item_count']; $i++) {
    if (!isset($field_collection_colorizer['entity'][$i])) {
      $field_collection_colorizer['entity'][$i] = entity_create('field_collection_item', array('field_name' => 'field_collection_colorizer'));
    }
  }

  // Reset the input to make sure cached version of the form insn't returned.
  $form_state['input'] = array();

  // Rebuild the form.
  $form = drupal_rebuild_form($form_state['build_info']['form_id'], $form_state, $form);

  // Return the field you want to replace.
  return $form['field_collection_colorizer'];
}


Display and Modify CSS variable ? (Module) I'm developing a basic module that allows site admin to have the NavBar for mobile and Administration menu for the desktop view.

This can easily be done by adding this CSS.

#navbar-administration {
    display: none;
}

@media only screen and (min-width: 0px) and (max-width: 959px) {

    #navbar-administration {
        display: block;
    }  /* show it on small screens */;
}

#admin-menu {
    display: block;
}

@media (max-width: 960px) {

    #admin-menu {
        display: none;
    }
}

I'm using hook_page_build() to display it on every page. Now I want user to be able to change on an administration page the 960 width which is the default line break to changes menu to their desired value.

My question  how can I display  the default variable value (960) on a text field and it can be modify the css once the number on the text field is been change.

You have many options:

Make a system settings form that stores the value to a drupal variable. Read that value from your (themes) css. Then when that form is submitted in your theme form submit handler have code clears the cache:   cache_clear_all("{$theme}:css:*", NULL, TRUE);. Where $theme is your theme name. The CSS should be re-generated on page load.
I believe the LESS module allows you to easily make CSS variables applied to your files (in Less-3.x or greater for drupal). If you're not currently using LESS, then this is less helpful (pun NOT intended!)


Array $field_instance is occassionally empty I am trying to determine why, on certain nodes, my address fields are not geocoded to my geofield. I think I have it tracked down to this part of geocoder.widget.inc (line 347).

function geocoder_widget_get_entity_field_value($entity_type, $field_instance, $entity) {
    $field_name = is_array($field_instance['widget']['settings']['geocoder_field']) ? reset($field_instance['widget']['settings']['geocoder_field']) : $field_instance['widget']['settings']['geocoder_field'];

If I add dpm($field_instance), on one node update, it will show me that array. On a different node update, there is no devel message (i.e. no array). Both nodes have addresses.

The problem is, I cannot figure out why one would be blank while the other would not be.

Apparently this was an issue with the manual lat/lon override. I didn't have it checked to allow it, but when I did check it and edited the problem nodes, the override box was already checked. Unchecking it then allowed my address field to be geocoded.


'Failed to get available update data" behind a proxy I am running Drupal 8.1.2 behind proxy in Ubuntu 16.04. There is an error:

Failed to get available update data for one project.

even the following is added in settings.ini:

$settings['http_client_config']['proxy']['http'] = '192.168.1.8:3128';
$settings['http_client_config']['proxy']['https'] = '192.168.1.8:3128';
$settings['http_client_config']['proxy']['no'] = ['127.0.0.1', 'localhost'];

I tried both 192.168.1.8:3128 and http://192.168.1.8:3128/ and neither works.

Both http_proxy and https_proxy work well in bash though.

How can I fix the error?

Update, with screenshot:

I solved the problem on Ubuntu 14.04.5 with Drupal 8.5.6. This should also work for Ubuntu 16.04.4. Install php7.0-curl (or php-curl or php5-curl or php7.2-curl) and write http:// before your proxy name (otherwise GuzzleHttp uses tcp://, I think).

Console/SSH

sudo apt update
# Use php --version to find out what version of PHP you're on
sudo apt install php7.0-curl
sudo service apache2 restart

Config

/var/www/html/<DRUPALFOLDER>/sites/default/settings.php

$settings['http_client_config']['proxy']['http'] = 'http://192.168.1.8:3128';
$settings['http_client_config']['proxy']['https'] = 'http://192.168.1.8:3128';
$settings['http_client_config']['proxy']['no'] = ['127.0.0.1', 'localhost'];

Optional

The old syntax is no longer necessary (but would not hurt either):

$settings['proxy_server'] = '192.168.1.8';  // HERE WITHOUT http:// !!!
$settings['proxy_port'] = 3128;
$settings['proxy_username'] = '';
$settings['proxy_password'] = '';
$settings['proxy_user_agent'] = '';
$settings['proxy_exceptions'] = array('127.0.0.1', 'localhost');

Console/SSH (again)

sudo service apache2 restart

For the Googlers: errors on my way

Show logs with

drush ws --count=100 --extended --tail
# or cd into `<DRUPALFOLDER>` and do
php drush.phar ws --count=100 --extended --tail

►►►

 *****  24/Aug **:**  update    error     GuzzleHttp\Exception\RequestException: Error creating resource: [message]
                                          fopen(http://updates.drupal.org/release-history/drupal/8.x?site_key=****************************
                                          ***************&version=8.5.6&list=**********************************************************...
                                          ...*************************************************************************): failed to open
                                          stream: Connection timed out
                                          [file] /var/www/html/******************/vendor/guzzlehttp/guzzle/src/Handler/StreamHandler.php
                                          [line] 324 in GuzzleHttp\Exception\RequestException::wrapException() (line 52 of
                                          /var/www/html/******************/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php).
 *****  24/Aug **:**  update    error     GuzzleHttp\Exception\RequestException: Error creating resource: [message]
                                          fopen(http://updates.drupal.org/release-history/admin_toolbar/8.x?site_key=*********************
                                          ***************************************&list=admin_toolbar%2Cadmin_toolbar_tools): failed to
                                          open stream: Connection timed out
                                          [file] /var/www/html/******************/vendor/guzzlehttp/guzzle/src/Handler/StreamHandler.php
                                          [line] 324 in GuzzleHttp\Exception\RequestException::wrapException() (line 52 of
                                          /var/www/html/******************/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php).

►►►

 *****  24/Aug **:**  notic  user  Session opened for ***.
                      e
 *****  24/Aug **:**  error  upda  GuzzleHttp\Exception\ClientException: Client error: `GET
                             te    http://updates.drupal.org/release-history/admin_toolbar/8.x?site_key=**********************************
                                   *********&version=8.x-1.24&list=admin_toolbar%2Cadmin_toolbar_tools` resulted in a `400 Bad Request`
                                   response:

 *****  24/Aug **:**  error  upda  GuzzleHttp\Exception\ClientException: Client error: `GET
                             te    http://updates.drupal.org/release-history/drupal/8.x?site_key=*****************************************
                                   **&version=8.5.6&list=******************************************************************************...
                                   ...***************************` resulted in a `400 Bad Request` response:


How to change a field type from Integer to Decimal? I have a content type with an integer content field. The field needs to contain float data. What's the easiest way to change the field type from integer to decimal? (There are thousands of existing nodes I will have to convert).

I've found a solution in this comment and this comment. Is it the best?

Just to merge all the previous suggestions into one convenient chunk:

// Change this to your field name, obvs.
$field = 'field_myfieldname';

// Update the storage tables
$tables = array('field_data', 'field_revision');
foreach ($tables as $table) {
  $tablename = $table .'_'. $field;
  $fieldname = $field .'_value';
  db_change_field($tablename, $fieldname, $fieldname, array(
    'type' => 'numeric',
    'precision' => 10,
    'scale' => 2,
    'not null' => FALSE,
  ));
}

// Fetch the current field configuration
$field_config = db_query("SELECT data FROM {field_config} WHERE field_name = :field_name", array(
    ':field_name' => $field,
  ))
  ->fetchObject();
$data = unserialize($field_config->data);

// Update the settings entry
$data['settings'] = array(
  'precision' => 10,
  'scale' => 2,
  'decimal_separator' => '.',
);

// Store the new field config, update the field type at the same time
db_update('field_config')
  ->fields(array(
    'data' => serialize($data),
    'type' => 'number_decimal',
  ))
  ->condition('field_name', $field)
  ->execute();

// If you are confident about what bundles have instances of this field you can
// go straight to the db_query with a hardcoded entity_type / bundle.
$instances = field_info_field_map();
foreach ($instances[$field]['bundles'] as $entity_type => $bundles) {
  foreach ($bundles as $bundle) {

    // Fetch the field instance data
    $field_config_instance = db_query("SELECT data FROM {field_config_instance}
                                       WHERE field_name = :field_name
                                       AND entity_type = :entity_type
                                       AND bundle = :bundle", array(
        ':field_name' => $field,
        ':entity_type' => $entity_type,
        ':bundle' => $bundle,
      ))
      ->fetchObject();
    $data = unserialize($field_config_instance->data);

    // Update it with the new display type
    $data['display']['default']['type'] = 'number_decimal';

    // Store it back to the database
    db_update('field_config_instance')
      ->fields(array('data' => serialize($data)))
      ->condition('field_name', $field)
      ->condition('entity_type', $entity_type)
      ->condition('bundle', $bundle)
      ->execute();

  }
}


Commerce product programatically with price How do I get the correct price in the site's default currency to work like the the add product form does?

This function gives a product with a price of $0.01 I want $1.00.

I am sure this has to do with calculated price?

function generate_products () {

    $product_type = 'product';

    $values = array (
        'price' => 1.00 ,
        'currency_code' => commerce_default_currency() ,
    );

    $extras = array(
        'status' => 1,
        'uid' => 1,
        'sku' => randomName ( 10 ),
        'title' => randomName ( 10 ),
    );

    commerce_installments_create_product ($product_type,$values,$extras);
}

function commerce_installments_create_product ( $product_type , $values , $extras ) {
    $form_state = array ();
    $form_state[ 'values' ] = $values;
    $form = array ();
    $form[ '#parents' ] = array ();

    // Generate a new product object
    $new_product = commerce_product_new ( $product_type );

    $new_product->status = $extras[ 'status' ];
    $new_product->uid = $extras[ 'uid' ];

    $new_product->sku = $extras[ 'sku' ];
    $new_product->title = $extras[ 'title' ];
    $new_product->created = $new_product->changed = time ();

    if ( ! empty( $values[ 'original_order' ] ) ) {
        // field_original_order[und][0][target_id]
        $order = array ( LANGUAGE_NONE => array ( 0 => array ( 'target_id' => $values[ 'original_order' ] ) ) );
        $form_state[ 'values' ][ 'field_original_order' ] = $order;
    }

    if ( ! empty( $values[ 'original_line_item' ] ) ) {
        // field_original_line_item[und][0][target_id]
        $line_item = array ( LANGUAGE_NONE => array ( 0 => array ( 'target_id' => $values[ 'original_line_item' ] ) ) );
        $form_state[ 'values' ][ 'field_original_line_item' ] = $line_item;
    }

    if ( ! empty( $values[ 'original_product' ] ) ) {
        $product = array ( LANGUAGE_NONE => array ( 0 => array ( 'target_id' => $values[ 'original_product' ] ) ) );
        $form_state[ 'values' ][ 'field_original_product' ] = $product;
    }

    //commerce_price[und][0][amount]
    $price = array ( LANGUAGE_NONE => array ( 0 => array (
        'amount' => $values[ 'price' ] ,
        'currency_code' => $values[ 'currency_code' ],
    ) ) );
    $form_state[ 'values' ][ 'commerce_price' ] = $price;

    // Notify field widgets to save their field data
    field_attach_submit ( 'commerce_product' , $new_product , $form , $form_state );

    commerce_product_save ( $new_product );
    return $new_product->product_id;
}

//function based on answer here How do I programmatically create an entity with its fields?

Prices are stocked as integer in database.

Try replacing 1.00 by 100 in your price array :

$values = array (
        'price' => 100 ,
        'currency_code' => commerce_default_currency() ,
    );

Cf : http://drupal.org/node/1124416


recent forum topics on sidebar of home page, recent articles and forum topics on article pages, recent articles on forum page I'm having a little trouble finding information to help me figure out what I'm trying to do. Please forgive me, as I am new to drupal's api. I have 3 particular scenarios where I would like a little helpful nudge in the right direction.

1 - I really enjoy having the most recent articles being shown on the front page by default. I would like to know how to have recent forum topics, separate from the recent articles, on the sidebar. Just text would be sufficient. Please tell me this is possible. I've searched for hours looking for some kind of information or maybe a module that accomplishes this.

2 - On the Forum, I would like the exact opposite. I would like the recent articles to be on the sidebar. Just the titles would be sufficient here as well.

3 - On the Article Pages, I would like both recent forum topics and articles on the sidebar.

I'm using the core Forum module, as well as Advanced Forum module. -Edit

Are there global variables I can use to achieve this? This, I'm sure, would help others as well with average time on site, and bounce rate.

--Edit--

As Dooshta mentioned, this can be accomplished with Views. It's so very easy to use!

Also, I noticed that there were disabled blocks already there for what I was looking for. I've enabled Recent Content for Article Topics, Active Forum Topics, and New Forum Topics. Once I'm done styling them on my local Drupal Installation, I'll post a link to my live site  to show an example for this Question!

--Edit--

I attempted using the provided blocks, however, I had a problem with a Configure Block link showing up on both provided forum blocks for all roles except admin. After a little research, I seen that it has been a problem for a long time and there's no simple fix. So I decided to use Views instead.

As I mentioned before, Views is absolutely simple to use. I created an Active Forum Topic Block, New Forum Topic Block, and a New Article Block for use on the sidebar. I couldn't configure the Active Forum Topic Block to display the topics in order with last topic commented on first until after creating it, but it wasn't difficult to figure out at all. the page is informative and organized.

If you would like to see how I used Views on my site, go to Strong Local Business. The New Articles don't display on the front page as intended, however you can see them on the sidebar when viewing an article, as designed.

Thanks again, Dooshta!

I hope this question helps others who may want to achieve the same results.

Sounds like something that would be easiest to accomplish with the Views module (seeing as you're using the Advanced Forum module you should already have it installed). It allows you to create blocks with the necessary content and then you can just adjust the block settings to get them displayed where you want.


How to get jquery switchClass working in Drupal 7 I want to use the jquery "switchClass" in a Drupal 7 Website. I already got the jquery accordion and tabs working, by adding the library in this way:

drupal_add_library('system', 'ui.tabs');

drupal_add_library('system', 'ui.accordion');

Now i'm trying to get switchClass working this way:

drupal_add_library('system', 'ui.switchClass');

... which is not working.

What am i doing wrong?

Thank you for helping!

Lars

switchclass() isn't a library, it's a function that's part of UI Effects. So...

drupal_add_library('system', 'effects');

Should then let you use:

$('.foo').switchClass('foo', 'bar', 1000);


Can i specify an image style in my custom module I search everywhere in the web but i dont find any solution.

I make an entity query for get some nodes. I pass the nodes to my template. In there nodes, i have an image field. So my questions is, can i specify an image style in this case ?

Controllers.php

$query = $this->entity_query->get('node');
$query->condition('type', 'foo');
$nids = $query->execute();
$foos = $this->entity_manager->getStorage('node')->loadMultiple($nids);
return array(
        '#theme' => 'foo',
        '#foos' => $foos
    );

template.html.twig

{% for foo in foos %}
    <img src='{{ file_url(foo.field_picture.entity.uri.value) }}'>
{% endfor %}

There are several options:

Use a view
Use Twig Tweak with a display mode, where you configure the image style
Use this code How to find image style URL from within twig template?

If you don't need more than what is in your question, I would start with 1, because don't reinvent code for things that are in core.


Is it possible to address a single item of a field collection in pathauto? I'm making sort of a slideshow for a customer

The slideshow has a field collection which has itself several fields that contain the actual content of the slides (headline, text, image, alt text, image caption)

And the slideshow is a node which uses several fields: title, teaser texts, teaser title texts, links to other pages etc.

The customer wants the slides to have individual URLs which I want to be created with pathauto module. The token which I use for a normal node (on admin/config/search/path/patterns) is like this [node:title]-[node:nid]. This works ok

But how about the token for a individual slide? If I administer the fields for my field collection (admin/structure/field-collections/field-pages/fields), there is no such default field like URL-alias.

Do I need to use the token hooks to create new tokens? But how? How can I then add them to the URL-alias? I suggest with hook_presave? Could it be done?

I managed it now like this in a custom module.
What I do is add a new argument to the system path, so
node/<nid> becomes node/<nid>/<slide_num>

Can it be made better?

/**
 * implements hook_pathauto_alias_alter()
 * alters the alias of a newly created slideshow node
 */
function coco_slideshow_pathauto_alias_alter(&$alias, &$context) {
        // print_r(array($alias, $context));
    if ($context['module'] == 'node' && $context['type'] == 'slideshow'
        && ($context['op'] == 'insert'
            || $context['op'] == 'update')
        ) {
            $node = $context['data']['node'];

            module_load_include('inc', 'pathauto');
            module_load_include('inc', 'path');

            // get default path alias from patterns
            // this will be start of url alias
            $pattern = pathauto_pattern_load_by_entity('node', $node->type, $node->language);
            $path = pathauto_clean_alias(token_replace($pattern, array(
                'node' => $node,
            ), array(
                'sanitize' => false,
                'clear' => FALSE,
                'callback' => 'pathauto_clean_token_values',
                'language' => (object) array('language' => $node->language),
                'pathauto' => TRUE,
            )));

            $pages = field_get_items('node', $node, 'field_pages');
            if (!empty($pages)) {
                $slide_id = $pages[0]['value'];
                $slide = field_collection_item_load($slide_id);
                if (!empty($slide)) {
                    $headline = field_get_items('field_collection_item', $slide, 'field_slide_headline');
                    $headline_text = $headline[0]['safe_value'];
                    if (!empty($headline)) {
                        $path_text = pathauto_cleanstring("{$headline_text} {$slide_id}");
                        // alias is replaced with new one
                        $alias = "{$path}-{$path_text}";
                    }
                }
            }
    }

}

/**
 * implements hook_node_insert()
 *
 * creates aliases for each slide in slideshow node type
 */
function coco_slideshow_node_insert($node) {
    if ($node->type == 'slideshow') {
        module_load_include('inc', 'pathauto');
        module_load_include('inc', 'path');

        $title = $node->title;
        $nid = $node->nid;

        // get default path alias from patterns
        // this will be start of url alias
        $pattern = pathauto_pattern_load_by_entity('node', $node->type, $node->language);
        $path = pathauto_clean_alias(token_replace($pattern, array(
            'node' => $node,
        ), array(
            'sanitize' => TRUE,
            'clear' => TRUE,
            'callback' => 'pathauto_clean_token_values',
            'language' => (object) array('language' => $node->language),
            'pathauto' => TRUE,
        )));

        $pages = field_get_items('node', $node, 'field_pages');
        if (!empty($pages)) {
            $slides = field_collection_item_load_multiple($pages);
            if (!empty($slides)) {

                $i=0;
                foreach ($slides as $slide_id => $slide) {
                    $headline = field_get_items('field_collection_item', $slide, 'field_slide_headline');
                    if (!empty($headline)) {
                        $headline_text = $headline[0]['safe_value'];

                        // create clean string for pathauto for every single slide
                        // this will be second part of url alias
                        $path_text = pathauto_cleanstring("{$headline_text} {$slide_id}");

                        // first slide should alias to node/<nid>
                        // not to node/<nid>/<slide_id>
                        // this is handled in hook_pathauto_alias_alter
                        if ($i > 0) {
                            $save = array(
                                'source' => "node/{$nid}/{$i}",
                                'alias' => "{$path}-{$path_text}",
                                'language' => $node->language,
                            );
                            path_save($save);
                        }
                    }
                    $i++;
                }
            }
        }
    }
}

/**
 * implements hook_node_update
 */

function coco_slideshow_node_update($node) {
    if ($node->type == 'slideshow') {
        module_load_include('inc', 'pathauto');
        module_load_include('inc', 'path');

        $title = $node->title;
        $nid = $node->nid;

        // get default path alias from patterns
        // this will be start of url alias
        $pattern = pathauto_pattern_load_by_entity('node', $node->type, $node->language);
        $path = pathauto_clean_alias(token_replace($pattern, array(
            'node' => $node,
        ), array(
            'sanitize' => TRUE,
            'clear' => TRUE,
            'callback' => 'pathauto_clean_token_values',
            'language' => (object) array('language' => $node->language),
            'pathauto' => TRUE,
        )));

        $pages = field_get_items('node', $node, 'field_pages');
        if (!empty($pages)) {
            $slides = field_collection_item_load_multiple($pages);
            if (!empty($slides)) {

                $i=0;
                foreach ($slides as $slide_id => $slide) {
                    $headline = field_get_items('field_collection_item', $slide, 'field_slide_headline');
                    if (!empty($headline)) {
                        $headline_text = $headline[0]['safe_value'];

                        // create clean string for pathauto for every single slide
                        // this will be second part of url alias
                        $path_text = pathauto_cleanstring("{$headline_text} {$slide_id}");

                        // first slide should alias to node/<nid>
                        // not to node/<nid>/<slide_id>
                        // this is handled in hook_pathauto_alias_alter
                        if ($i == 0) {
                            $save = array(
                                'source' => "node/{$nid}",
                                'alias' => "{$path}-{$path_text}",
                                'language' => $node->language,
                            );
                            $temp = drupal_get_path_alias("node/{$nid}", $node->language);
                            path_delete(array('alias' => $temp));
                            // print '<xmp>' . print_r($save,1). '</xmp>';
                            path_save($save);
                        } else {
                            $save = array(
                                'source' => "node/{$nid}/{$i}",
                                'alias' => "{$path}-{$path_text}",
                                'language' => $node->language,
                            );
                            path_delete(array('source' => "node/{$nid}/{$id}"));
                            path_save($save);
                        }
                    }
                    $i++;
                }
            }
        }
    }
}


Convert dropdown of exposed sorting of view into Checkboxes I have created view in that view I exposed sorting with dropdown field 'Distance', 'Rating', 'Review', it works fine. Now I want to convert that dropdown into checkboxes with AJAX callback.
I used module  Better Exposed Filters please suggest me to how to do that.

I Suppose this may help you using Better Exposed Filters


When a node is created, automatically update data in a corresponding node Background (simplified)
We're collecting data for a study in which participants come in on several occasions to have health measures taken. We have two custom node types: Participant stores background data about a person, and Visit stores information from a single visit (e.g., their blood pressure that day). Each Visit is related to one Participant via a field created by the Node References module.
On each visit, a participant might qualify for a one-time reward. Visit nodes have a reward_visit field indicating whether the participant earned a reward on this visit, and Participant nodes have a reward_ever field indicating whether the participant has ever received a reward.
Question
I'd like to set up the following behavior: If a Visit node is created where reward_visit was set to Yes, also set reward_ever to Yes in the corresponding Participant node.
Is there a way to make this happen automatically, using Node References or some other relations module? I could custom-code it using hook_node_insert() or something, but I'd like to know if there's already an accepted way.

UPDATE:
The answer to this question is "Rules". I hadn't learned about them at the time. With a rule, you can choose to trigger on saving or updating new content and use conditions to limit it to the content type in question. For the action, choose "set a data value" and the relation between the two nodes should allow you to select the relevant field on the node you just created as the source, and the relevant field on the related node as the value to set.

Original answer:
I ended up writing a small custom module that implements hook_node_insert and hook_node_alter for visit nodes. It gets the nid of the related participant from the submission, gets it using node_load(), changes the relevant values, and saves it using node_save(). I still suspect there's a less kludgy solution, but this seems to work perfectly well.


How do you get the weather module to recognise SVG files? How do you get the weather module to recognise SVG files?

I have my SVGs in: /sites/default/files/icons/svg

They are named correctly: 01d.svg, 01m.svg ...etc.

and that is where I am pointing to (icons/svg) from: admin/config/user-interface/weather.

PNGs work fine, but when I switch to SVGs the display falls back to the default icon set?

Thanks.

I don't like to, but I hacked the module: weather_theme.inc. I altered:

$image = $custom_path . $symbol . '.svg';

Here's the full function:

/**
 * Returns the <img> tag for the weather image to use for the current condition.
 *
 * @param $symbol
 *   The weather condition number from yr.no
 * @param $condition
 *   The translated condition text.
 *
 * @return $string
 *   Ready formatted HTML <img> tag
 */
function weather_format_image($symbol, $condition) {
  // Support a custom image directory. If the variable is not set or the specified
  // file is not available, fall back to the default images of the module.
  $custom_path = file_default_scheme() . '://' . variable_get('weather_image_directory', '') . '/';
  // Construct the filename
  $image = $custom_path . $symbol . '.png';
  if (!is_readable($image)) {
    $default_path = drupal_get_path('module', 'weather') . '/images/';
    $image = $default_path . $symbol . '.png';
  }
  $size = getimagesize($image);
  // Prepare the <img> tag
  return theme('image', array(
    'path' => $image,
    'width' => $size[0],
    'height' => $size[1],
    'alt' => $condition,
    'title' => $condition,
    'attributes' => array('class' => 'weather-image')
  ));
}


restric view row by the URL in block I have a view block disply that contains a list of nodes.
i want to restrict Nid's by my url in one field in node.(Similarly, system block visibility)
for example i have a field with name field_visibility and save node by fill that gallery

so, my list in block is:

  view-row-1 => [nid]-1 => field_visibility ='gallery' view-row-2 =>
  [nid]-2 => field_visibility ='contact' view-row-3 => [nid]-3 =>
  field_visibility ='blog' . . .

so in page www.example.com/gallery, in block should be

1. [nid]-2
2. [nid]-3

and in page www.example.com/contact, in block should be

1. [nid]-1
2. [nid]-3

No need to use field_visibility

try this if using Views 3

Click on the "advanced" tab.
Click on add under "contextual filters".
Choose Content:nid.
Under "when the filter variable is not available, choose "provide default value".
From the drop down menu select "content id from url".
Scroll all the way down to the bottom of the window and click on the "More" link.
Click "Exclude"


How to set up a field to provide a publish/unpublish feature? For layout reasons, I need a field providing a publish/unpublish feature.

We already have something very close with the Publish Content module.

Still, it looks like there's no option for setting it up as field.

Which alternative do we have here?

I would use the Flag module. Excerpt from its project page (bold markup added here):

... Flag is a flexible flagging system that is completely customizable by the administrator. Using this module, the site administrator can provide any number of flags for nodes, comments, users, and any other type of entity. Some possibilities include bookmarks, marking important, friends, or flag as offensive. With extensive views integration, you can create custom lists of popular content or keep tabs on important content.
Flags may be per-user, meaning that each user can mark an item individually, or global, meaning that the item is either marked or it is not marked, and any user who changes that changes it for everyone.
In this way, additional flags (similar to published and sticky) can be put on nodes, or other items, and dealt with by the system however the administration likes.

So by using a "global flag" (whatever you'd call such flag), you could just "mark or do not mark" something as published. If appropriate, you could also consider Attaching fields to flags.
If you're not familiar with the Flag module, checkout the set of 8 video tutorials about the flag module.
Refer to Flag's Community documentation for (way) more details.
PS: near the bottom of the Flags setup is an option 'Display link as field', which will include it as a field, for views, Panels, etc (if that's why you want a field).


Coloring rows in returned drupal search results I'm trying to modify search-result.tpl.php and template.php to color the backgrounds of search results returned such that every row has a different color than the one that preceded it. Only two colors are used. so, row #1 returned would have background #eee and row 2 would have #ff0000 as its background color. It would start over again at row #3 having #eee and so on. This is easily enough accomplished with PHP. But how can I implement this with Drupal?

Here's how I'm trying to print it out in search-result.tpl.php:

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

    <?php $inc=0; ?>
      <?php if ($inc %2 == 0) {
                $color = '#eee';
              } else {
                $color = '#ff0000';
              }
              ?>
      <div style="background-color: <?php print $color ?>">

<?php print render($teaser['field_icon']); ?>

<a href="<?php print $result['link']; ?>"><?php print $result['title']; ?>

      <?php print render($teaser['field_type']); ?>
      <?php print render($teaser['field_event_dates']); ?>
      <?php print render($teaser['body']); ?>

      <?php $inc++; ?>

Not getting errors, but the results are not what I was expecting. Each row is just returning the same color background #eee, the first color). So either the $inc variable is not getting incremented or (perhaps more likely) it's becoming '0' again after every returned result. So then I'm thinking maybe I need to add something to my preprocess_search_result function in my template.php file...but I don't know what to add there.

Any help would be greatly appreciated.

I would create your search results page using views, this has the odd/even class functionality built-in. The current code you provided won't work since the $inc value starts as 0 and there is no loop where $inc++ occurs so everytime this template is loaded $inc will start as 0 and end as 1.


Devel themer not working (cant see the checkbox) I want to see from where different elements are coming from. Theme Developer module does this, but I cannot see the checkbox in the lower left of  the page. It was working earlier but it isnt now, i am using drupal 7.

Anyone seen this issue?

Check to see if the module is still enabled.
Clear the cache.
Check to see if the currently logged-in user has appropriate permissions to see devel_themer info.

It's likely #3.


How to set maximum height in image style in Drupal 7? I want to define an image style in Drupal 7 which changes the width of images to 200px and the max of the height to 150px. That means if a picture is 400x300 the image style should change it to 200x150 but if an image is 250x120 the image style should change only the width of it to 200px and the height shouldn't be changed.

How can I do it ? It seems it is not possible by 'admin/config/media/image-styles'.

Your approach will differ depending on whether you want your images to be cropped or scaled to fit the appropriate size, but generally speaking, in most of the image style effects where you can specify a width and height, if you just enter one value, the value for the other will be automatically calculated ("Resize" is an exception, but since that can result in distorted images, you almost always want to use "Scale" or "Scale and crop" instead.) For example, if you add a "Scale" effect, leave the width field blank and set the height to 150px, when processing a 400x600px image, the system will notice that it needs to divide the height by 4 in order to reduce its height to 150px, and apply the same division to the width, resulting in a 100x150px image.

Again, depending on how you want images to be scaled or cropped, applying more than one action in sequence may also get you where you want to be. For example, scale to a certain width, then crop to a certain height. The "Scale and crop" action can do both of these together in one action, but might not do it in exactly the manner you want.


Drush dl not working with PHP 7 and ubuntu 16.04 When i try to do:

drush dl drupal-8

i get the following error:

PHP Fatal error:  Uncaught Error: Call to undefined function Drush\UpdateService\simplexml_load_file() in /home/alexander/.config/composer/vendor/drush/drush/lib/Drush/UpdateService/Project.php:74
Stack trace:
#0 /home/alexander/.config/composer/vendor/drush/drush/lib/Drush/UpdateService/ReleaseInfo.php(64): Drush\UpdateService\Project::getInstance(Array, 86400)
#1 /home/alexander/.config/composer/vendor/drush/drush/lib/Drush/UpdateService/ReleaseInfo.php(122): Drush\UpdateService\ReleaseInfo->get(Array)
#2 /home/alexander/.config/composer/vendor/drush/drush/commands/pm/download.pm.inc(111): Drush\UpdateService\ReleaseInfo->selectReleaseBasedOnStrategy(Array, '', 'auto', false, NULL)
#3 /home/alexander/.config/composer/vendor/drush/drush/includes/command.inc(366): drush_pm_download()
#4 /home/alexander/.config/composer/vendor/drush/drush/includes/command.inc(217): _drush_invoke_hooks(Array, Array)
#5 /home/alexander/.config/composer/vendor/drush/drush/includes/command.inc(185): drush_command()
#6 /home/alexander/.config/compos in /home/alexander/.config/composer/vendor/drush/drush/lib/Drush/UpdateService/Project.php on line 74
Drush command terminated abnormally due to an unrecoverable error.

Other commands does work: drush cc, drush status.

Here's output of drush status:

 PHP executable         :  /usr/bin/php
 PHP configuration      :  /etc/php/7.0/cli/php.ini
 PHP OS                 :  Linux
 Drush script           :  /home/alexander/.config/composer/vendor/drush/drush/drush.php
 Drush version          :  8.1.2
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :

Sounds like you managed to install/configure PHP without the simplexml extension.

Install the php7.0-xml package with apt-get as follows.

sudo apt-get install php-xml

Also check the UI installer, if you're missing this, then you're likely also missing a bunch of other extensions link mbstring, gd and so on to install/use Drupal.


Using Rules and Rules Once per day how can I check when a node's date has expired? I have a content type which has an end date field, once the current date is past this end date then I need to change a boolean field to 0 on that particular node.

I am really struggling to get anything close to working (using the Rules module), I am getting values such as this in my Data selectors:

node:field-category:0
node:field-category:1
node:field-category:2
node:field-category:3

I don't know why these delta values are there or how to get rid of them, every video tutorial I watch the persons data selection is working perfectly.

I understand I need to drill down by adding a Rules Condition to check for a particular field on the node type in question. But, like I said, I am just getting these delta values.

Now coming to the loop and I am unable to get the value from the end date for the very reason that it is not there.

Even when I have gotten close to having the loop working, when I look for the boolean field which needs to be altered if the current date > end date, this is also showing me several values with numbers after them.

What am I doing wrong?

From the "...adding a condition to check for a particular field on the node type in question..." in your question, I bet you are aware about the importance of adding a Rules condition Entity has field (related to your field you're looking for). If not have a look at what is mentioned in the Rules UI, e.g. when you're adding a "data comparison" condition: somewhere it says "The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')".

However, even though nowhere in your question you indicate which Rules Event you're using, I bet you're using the wrong one. And the "Rules once per day" in your title is probably a good indication of what you really try to use as a kind of Rules Event (which is not really an event).

Nevertheless, I think you're just using the wrong approach (sorry). What I would do in your scenario, is a variation of my answer to "Rule to store user's last post date and scheduled rule based 30 day reminder". Some more details about how to adapt that answer to fit your case here:

Create a variation of the Rules Component (in Step 2) to change that boolean field for "a" node (which at least requires the node id as a parameter). Use the "execute" link in front of the Rules Component to QA-test your component (with a single node id, etc).
Create a variation of the Rule (in Step 3) like so:

Use a Rules Event like "when such node gets created or updated" (something that fits your case).
In the Rules Condition of that rule, for sure you'll be able to use the "Entity has field" condition (for your date field).
In the Rules Action, you "schedule" the execution of the Rules Component mentioned above. For this you need to enable the Rules Scheduler, and that should do the trick.

Last but not least, be patient ... and wait until the specified date arrives, then wait for your next cron job to run (if you don't run that, nothing will actually get executed, be aware!). And then: voilà.


How can I make a custom content entity ID editable on the content entity form? I've created a custom content entity with a string ID field named 'lot_number':

*   entity_keys = {
*     "id" = "lot_number",

This is its field definition:

$fields['lot_number'] = BaseFieldDefinition::create('string')
  ->setLabel(t('Lot Number'))
  ->setDescription(t('Unique alphanumeric lot number for a batch of inventory.'))
  ->setRequired(TRUE)
  ->setSetting('max_length', 20)
  ->setDisplayOptions('view', array(
    'label' => 'inline',
    'type' => 'string',
    'weight' => 10,
  ))
  ->setDisplayOptions('form', array(
    'type' => 'string_textfield',
    'weight' => 10,
    'settings' => array(
      'size' => '10',
      ),
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE)
  ->addConstraint('UniqueField', []);

My problem is that this lot_number field does not show up on the content entity form. I tried adding it to the form programmatically in the buildForm() method of my form controller (that extends ContentEntityForm.) The following code gets it to show up on the form:

$form['lot_number'] = [
  '#type' => 'machine_name',
  '#title' => $this->t('Lot Number'),
  '#weight' => 10,
  '#size' => 20,
  '#maxlength' => 20,
  '#required' => TRUE,
  '#default_value' => $lot_master->getLotNumber(),
  '#machine_name' => [
    'exists' => '\Drupal\galt_inv\Entity\LotMaster::load',
  ],
  '#disabled' => !$lot_master->isNew(),
];

However, when I attempt to submit the form, I get an error message:

Error: Cannot unset string offsets in Drupal\Core\Field\WidgetBase->extractFormValues() (line 354 of core/lib/Drupal/Core/Field/WidgetBase.php).

I tried changing $form['lot_number'] to $form['lot_number']['widget'][0] in an attempt to make it match the rest of the form elements, but that didn't work at all.

Is there some simple way to get a content entity ID onto the content entity edit form? Any advice would be greatly appreciated.

You have both a widget configured and a custom form element, that results in Drupal being confused about the structure.

If you have a form element defined by yourself, don't define form display options and you should be OK.

The reason the widget show up like with other fields is likely actually a regression with the security fix in 8.3.1 that denies edit access to the entity. When we did that, we didn't anticipate a use case like this. You could override the default fieldAccess() method on the EntityAccessControlHandler to grant edit access to the id field, at least when it is new.

Or you do not make the lot number the actual entity ID but have a technical auto-increment ID, then you don't have to worry about this stuff.


AJAX form - replacing #default_value not working I have an AJAX form. I want to update the text of a textfield when a button is triggered. But this does not work. My form is below:

<?php
function my_form($form, &$form_state) {
  $form['ask_first_name'] = array(
    '#type' => 'textfield',
    '#title' => t('Ask me my first name'),
    '#default_value' => 'I LOVE chickens',
    '#prefix' => '
',
    '#suffix' => '
',
  );
  $form['update'] = array(
    '#type' => 'button',
    '#value' => t('Update'),
    '#ajax' => array(
      'callback' => 'ajax_example_autotextfields_callback',
      'wrapper' => 'textfields',
      'effect' => 'fade',
    ),
  );

  // shouldn't this update the default value when the button is pressed??
  if (isset($form_state['values'])) {
    $form['ask_first_name']['#default_value'] = 'I HATE chickens';
  }

  return $form;
}
?>

When I press the 'update' button I'm expecting the field text to change, but it doesn't. If I use #value instead of #default_value it works, but I know I shouldn't use that because I still want the user to be able to change it again.

<?php
// using #value works - but should I use that?
$form['ask_first_name']['#value'] = 'I HATE chickens';
?>

What is the recommended Drupal way to change the field value after AJAX is triggered?

NOTE: This answer solved the problem in my case, but as mentioned in the comments there is not access to the values in $form_state['values'] after submit. However, I'm storing the data in $form_state['storage'] so I can still access the data, though I'll probably implement ctools object cache in the end.

This is taken from the description of #default_value in the form api documentation:

The value of the form element that will be displayed or selected
initially if the form has not been submitted yet

Because your form has been submitted, it wont be using #default_value. Just use #value, the user will still be able to change it.
2021 edit.....
As people have pointed out, the above is wrong as although it will allow you to set the value, it wont allow the user to submit an altered value.
Now using Drupal 9, in a form alter, I needed to set some default field values when an ajax button (which I inserted) was clicked.
I needed to set default values on the node "body" field and "field_url" link field.
I removed the user input for these fields before setting a default value.
$userInput = $form_state->getUserInput();
unset($userInput['body']);
unset($userInput['field_url']);
$form_state->setUserInput($userInput);

$form['body']['widget'][0]['#default_value'] = 'my default value set after ajax callback';
$form['field_url']['widget'][0]['uri']['#default_value'] = 'my default value';

To be honest, I am not 100% sure it is the correct way, but it does work.


How to display module ouptput in a page with content I would like to display my module otuput in one page. The only solution I found till now is to use iframes. Is there some better solution?

I created a module to display a map with branches, branches are stored in DB. But before and after this map there should be some content, like text or pictures.

I hope there is a posibility. Maybe with blocks?

If the code for output your result is not so big than you can put the code in block and show that block on any page you want.


Drupal 7 form, query DB and results display I'm still somewhat new to Drupal but have a lot of experience programming in PHP. I'm looking for a list of modules in Drupal. I need to do this common list of tasks that are very typical of DB interaction:

Present a form to a user.
Do a query (select or insert) to one or many tables in a database in a custom DB or the one Drupal uses/
Present results in table form.

Please help me out thanks. Could anybody can give a sample examples.

This is what you need. Take a look into the Examples for Developers module. And Views of course. No need for handcrafted SQL.


Can an embedded video be made responsive? I currently use the Video filter module to embed Youtube videos in my posts, but on mobile devices the videos are not responsive. They still maintain their width no matter how narrow the screen is.

I am open to another method of embedding videos even raw HTML and Javascript if the video displays will be responsive

We use Fitvids in combo with Video filter to make youtube videos responsive.  You can either add the JS yourself or use the Drupal module version, it works either way.

In the case of using the Drupal module, you'll add the video filter HTML selector to the UI for fitvids and then your video will be responsive.

For example, on my site, I have a video using video filter:

[VIDEO::https://www.youtube.com/watch?v=y0bA_KH-D-I]

... and then in the video filter UI, I have added the slector for the video here:

/admin/config/media/fitvids

In my case video filter is using embedded-video as its wrapper HTML element so I added .embedded-video to the fitvids UI in Drupal.

For more info see:

https://github.com/davatron5000/FitVids.js/
http://fitvidsjs.com
https://www.drupal.org/project/fitvids


VBO copy Field Decimal I need to copy a value of one field to a decimal filed. When I try to do this with VBO and a token [node:price] I get an error: Only numbers and the decimal separator. Is there a way to copy fields into a decimal data type?

I think I would just add a quick jquery script myself that converts to the right format and autofills it into the field on the 'change' event.

I dont know your level of expertise on jquery, but if needed i can provide you a small example


How can i set the value of first field to the second in same form I have a form with a value field and i would like to set the value to a markup field as shown below. The problem is that it retuns empty. Is there other alternatives.

public function buildForm(array $form, FormStateInterface $form_state) {
     $form['container']['#tree'] = TRUE;
     $form['container']['#type'] = 'container';
     $form['container']['store_value'] = [
         '#type' => 'value',
         '#value' => 'Angeline Mnene'
     ];
     $form['container']['show_value'] = [
         '#type' => 'markup',
         '#markup' => 'The stored value is: ' . $form_state-
          >getValue(['container','store_value']),
     ];

     return $form;
}

I finally got an answer and would like to post it here, to help someone who may run into this problem as well.

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

     //SET THE VALUE HERE
     $form_state->setValue('store_value', 'The stored value is: Angeline
     Mnene');

     $form['container']['#tree'] = TRUE;
     $form['container']['#type'] = 'container';
     $form['container']['show_value'] = [
         '#type' => 'markup',
         '#markup' => 'The stored value is: ' . $form_state-
          >getValue('store_value'),
     ];

     return $form;
}


How to let selected role submit multiple data for 1 node? I want to do a product price compare site. So a product is a node and product can have many different price at different store. I want to allow selected user's role able to submit new price or new store from time to time but I want them to submit data on the node page similar to submitting comments, NOT on node edit page.

I'm looking onto entityreference but i'm not sure where to start and what others module needed to accomplish my objective.

Thanks for helping.

The Field Collection module will let you do a couple of helpful things here:

you can group a set of fields, ie store name, price so that this data is part of the same entity
you can embed links to add/edit/delete field collections right on the node.

Embedding the form in the node is trickier, but doable, and Field Collection will get you off to a good start.

Once the Field Collection module is enabled, create a field of the type field collection on your content type. Set the widget to 'embedded'. Then go and add individual fields to your content type.

There is basic documentation at https://www.drupal.org/node/1353926 and a video tutorial at https://www.youtube.com/watch?v=1V1ofpgUw-Y.


How do I get $node->body $node->teaser? I'm migrating a large custom module and theme from Drupal 6 and can't work out how to convert references to $node->body and $node->teaser since they are no longer fields in the node object, right?

Use this code in a preprocess hook:

$node = \Drupal::entityManager()->getStorage('node')->load($nid);
$view_builder = \Drupal::entityManager()->getViewBuilder('node');
$variables['node_full'] = $view_builder->view($node, 'full');
$variables['node_teaser'] = $view_builder->view($node, 'teaser');
$variables['body_full'] = $node->body->view('full');
$variables['body_teaser'] = $node->body->view('teaser');

And in twig

{{ node_full }}
{{ node_teaser }}
{{ body_full }}
{{ body_teaser }}

Use the rendered node and configure the view modes full, teaser or a custom view mode. The single rendered field does not work well with other code.


.info styles load before base theme I have a base theme and a sub-theme. The sub-theme specifies a single styles.css in the *.info file. The base theme provides CDN css stylesheets, via this hook:

function MYTHEME_preprocess_html(&$css) {

  drupal_add_css('http://yui.yahooapis.com/pure/0.5.0/pure-min.css', array(
    'group' => CSS_THEME,
    'preprocess' => FALSE
  ));

  drupal_add_css('http://yui.yahooapis.com/pure/0.5.0/grids-responsive-old-ie-min.css', array(
    'group' => CSS_THEME,
    'browsers' => array('IE' => 'lte IE 8'),
    'preprocess' => FALSE
  ));

  drupal_add_css('http://yui.yahooapis.com/pure/0.5.0/grids-responsive-min.css', array(
    'group' => CSS_THEME,
    'browsers' => array('IE' => 'gt IE 8'),
    'preprocess' => FALSE
  ));

  drupal_add_css('http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css', array(
    'group' => CSS_THEME,
    'preprocess' => FALSE
  ));

}

The resulting HTML is this:

<style type="text/css" media="screen">@import url("http://mysite.local/sites/all/themes/mytheme/styles.css?nezret");</style>

<link type="text/css" rel="stylesheet" href="http://yui.yahooapis.com/pure/0.5.0/pure-min.css?nezret" media="all">

<link type="text/css" rel="stylesheet" href="http://yui.yahooapis.com/pure/0.5.0/grids-responsive-min.css?nezret" media="all">

I need the @import to come in dead last in rendered order -- otherwise it seems the base theme styles are overriding my theme specific styless...

I have tried to correct this in the sub--theme by doing:

  function MYTHEME_css_alter(&$css) {

    foreach($css as $key => $value) {
      if($key == 'sites/all/themes/MYTHEME/styles.css') {
        $css[$key]['weight'] = 1000;
      }
    }

    uasort($css, 'drupal_sort_weight');

  }

This fixes the array but not the rendering order...WTF am I missing or doing wrong???

I would be curious to hear a alternative solution but this works too (albeit hackish):

I removed the reference to the stylesheet in *.info and simply added the call inside template.php:

function MYTHEME_preprocess_html(&$vars) {
    drupal_add_css(path_to_theme().'/styles.css', array(
      'group' => CSS_THEME,
      'preprocess' => FALSE
    ));
}


Line breaks in site name but not in title tag For design purposes I need line breaks in a multilingual site name. I have managed to do so by adding
 tags in the site name variable. But they show in the title within the html head tag and I don't know how to get rid of them.

I am using a custom Zen subtheme to which I have added the html.tpl.php file. In that I have tried the following approaches to no avail:

<title><?php print preg_replace('/
/iU', '', $head_title); ?></title>

<title><?php print strip_tags($head_title); ?></title>

<title><?php $head_title = str_replace('
', '', $head_title);
  print $head_title; ?></title>

Please excuse any profanities I may have committed in the use of php, I am no coder. Any ideas are most welcome.

Here is what I just found: There is no tags in the title, it's just a string. So the fix is quite simple.

in the html.tpl.php replace:

<title><?php print $head_title ?></title>

With this:

<title><?php
$break_tag = array("&lt;br /&gt;");
$simple_space = array(" ");
$new_head_title = str_replace($break_tag, $simple_space, $head_title);
print $new_head_title;
?></title>

Hope it helps.


Retrieve newly created Term tid I've created a PHP program outside Drupal that inserts Terms into my Drupal installation.

define('DRUPAL_DIR', __DIR__);

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;

$autoloader = require_once DRUPAL_DIR . '/autoload.php';
$request = Request::createFromGlobals();
$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
$kernel->boot();

require_once DRUPAL_DIR . '/core/includes/database.inc';
require_once DRUPAL_DIR . '/core/includes/schema.inc';

$term = \Drupal\taxonomy\Entity\Term::create([
      'vid' => 'subject',
      'langcode' => 'en',
      'name' => 'Test af Tag',
      'description' => [
        'value' => '
My description.
',
        'format' => 'full_html',
      ],
      'weight' => -1,
      'parent' => array(0),
])->save();

var_dump($term);

My question is - how do I retrieve the newly created Term tid?
The var_dump only gives a

  string(9) "SAVED_NEW"

Why on earth doesn't it return the newly created Entity/Term?!?

I need it in case there will be a child Term later.
I've looked at www.drupal.org/documentation and api.drupal.org. But those pages just confuses me more :-(

Thank you very much

Why on earth doesn't it return the newly created Entity/Term?!?

Why would it? You already have the term object, why do you need it to be chained in a return from a save method that can and does provide you with extra context??

Just use this:

$term = \Drupal\taxonomy\Entity\Term::create([
  'vid' => 'subject',
  'langcode' => 'en',
  'name' => 'Test af Tag',
  'description' => [
    'value' => '
My description.
',
    'format' => 'full_html',
  ],
  'weight' => -1,
  'parent' => array(0),
]);

$inserted_or_updated = $term->save();

$tid = $term->id();


create chains of views joins so one view can 'see' across more than one join Assuming the individual joins work can we join multiple times across columns like this?... (BTW I've checked this first query and it does indeed work correctly)

SELECT *
FROM a
LEFT JOIN b
ON a.a_id = b.references_a_id
LEFT JOIN c
ON b.references_c_id = c.c_id
LEFT JOIN d
ON c.references_d_id = d.d_id

As per the following table.column structure:

a.a_id
a.a_col

b.b_id
b.references_a_id
b.references_c_id
b.b_col

c.c_id
c.references_d_id
c.c_col

d.d_id
d.d_col

Is it possible to link these together in a view so that because we have the joins defined in hook_views_data_alter() we can have the following:

pseudo-description of the Views setup:

(views setup)

"SHOW" 'a'

...

"FIELDS" > "add" > overlay menu "Add fields" >
    a: a_id
    a: a_col
    b: b_id
    b: references_a_id
    b: references_c_id
    b: b_col
    c: c_id
    c: references_d_id
    c: c_col
    d: d_id
    d: d_col

So because this is not working for me... in hook_views_data_alter()

$data['b']['table']['join']['a']['left_field'] = 'a_id';
$data['b']['table']['join']['a']['left_table'] = 'a';
$data['b']['table']['join']['a']['field'] = 'references_a_id';
$data['b']['table']['join']['c']['left_field'] = 'c_id';
$data['b']['table']['join']['c']['left_table'] = 'c';
$data['b']['table']['join']['c']['field'] = 'references_c_id';
$data['c']['table']['join']['d']['left_field'] = 'd_id';
$data['c']['table']['join']['d']['left_table'] = 'd';
$data['c']['table']['join']['d']['field'] = 'references_d_id';

... I wonder if I should be doing something bizarre like this...

$data['b']['table']['join']['a']['left_field'] = 'a_id';
$data['b']['table']['join']['a']['left_table'] = 'a';
$data['b']['table']['join']['a']['field'] = 'references_a_id';
$data['b']['table']['join']['c']['left_field'] = 'c_id';
$data['b']['table']['join']['c']['left_table'] = 'c';
$data['b']['table']['join']['c']['field'] = 'references_c_id';
$data['b']['table']['join']['c']['left_table']['c']['join']['d']['left_field'] = 'd_id';
$data['b']['table']['join']['c']['left_table']['c']['join']['d']['left_table'] = 'd';
$data['b']['table']['join']['c']['left_table']['c']['join']['d']['field'] = 'references_d_id';

I added a relationship to the mix and that's opened up two extra sets of fields ('c' and 'd') I can't explain why, I think it's something to do with the joins that were already setup on these base tables. This then meant that when I bridged them with the relationship it opened it all up.

example:

$data['a']['a_id']['relationship']['handler'] = 'views_handler_relationship';
$data['a']['a_id']['relationship']['base'] = 'b';
$data['a']['a_id']['relationship']['base field'] = 'references_a_id';
    (... etc.)


How to apply a style to a specific page? I want to apply different stype on the pages of my site.

The following code applies a hard background to all product pages :

body.path-product {
    background-image: url("/themes/contrib/bootstrap_subtheme_front_office/images/background-page.svg");
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
    background-repeat: no-repeat;
    background-position: center center;
    background-attachment: fixed;
}

I want a different style to be applied for the product/add/produit path.

How to do this ?

Screenshot :

enter image description here

In my theme I created a file "html--product--add.html.twig" and I pasted in the contents of "html.html.twig".

{#
/**
 * @file
 * Default theme implementation to display the basic html structure of a single
 * Drupal page.
 *
 * Variables:
 * - $css: An array of CSS files for the current page.
 * - $language: (object) The language the site is being displayed in.
 *   $language->language contains its textual representation.
 *   $language->dir contains the language direction. It will either be 'ltr' or
 *   'rtl'.
 * - $rdf_namespaces: All the RDF namespace prefixes used in the HTML document.
 * - $grddl_profile: A GRDDL profile allowing agents to extract the RDF data.
 * - $head_title: A modified version of the page title, for use in the TITLE
 *   tag.
 * - $head_title_array: (array) An associative array containing the string parts
 *   that were used to generate the $head_title variable, already prepared to be
 *   output as TITLE tag. The key/value pairs may contain one or more of the
 *   following, depending on conditions:
 *   - title: The title of the current page, if any.
 *   - name: The name of the site.
 *   - slogan: The slogan of the site, if any, and if there is no title.
 * - $head: Markup for the HEAD section (including meta tags, keyword tags, and
 *   so on).
 * - $styles: Style tags necessary to import all CSS files for the page.
 * - $scripts: Script tags necessary to load the JavaScript files and settings
 *   for the page.
 * - $page_top: Initial markup from any modules that have altered the
 *   page. This variable should always be output first, before all other dynamic
 *   content.
 * - $page: The rendered page content.
 * - $page_bottom: Final closing markup from any modules that have altered the
 *   page. This variable should always be output last, after all other dynamic
 *   content.
 * - $classes String of classes that can be used to style contextually through
 *   CSS.
 *
 * @ingroup templates
 *
 * @see bootstrap_preprocess_html()
 * @see template_preprocess()
 * @see template_preprocess_html()
 * @see template_process()
 */
#}
{%
  set body_classes = [
    logged_in ? 'user-logged-in',
    not root_path ? 'path-frontpage' : 'path-' ~ root_path|clean_class,
    node_type ? 'page-node-type-' ~ node_type|clean_class,
    db_offline ? 'db-offline',
    theme.settings.navbar_position ? 'navbar-is-' ~ theme.settings.navbar_position,
    theme.has_glyphicons ? 'has-glyphicons',
  ]
%}
<!DOCTYPE html>
<html {{ html_attributes }}>
  <head>
    <head-placeholder token="{{ placeholder_token|raw }}">
    <title>{{ head_title|safe_join(' | ') }}</title>
    <css-placeholder token="{{ placeholder_token|raw }}">
    <js-placeholder token="{{ placeholder_token|raw }}">
  </head>
  <body{{ attributes.addClass(body_classes) }}>
    <a href="#main-content" class="visually-hidden focusable skip-link">
      {{ 'Skip to main content'|t }}
    </a>
    {{ page_top }}
    {{ page }}
    {{ page_bottom }}
    <js-bottom-placeholder token="{{ placeholder_token|raw }}">
  </body>
</html>

How to put the class "body.path-product-add" in this file ?

I guess you want to apply that class to the body tag. If that's true then you just need to append body_classes array and put your class in the end.

set body_classes = [
  logged_in ? 'user-logged-in',
  not root_path ? 'path-frontpage' : 'path-' ~ root_path|clean_class,
  node_type ? 'page-node-type-' ~ node_type|clean_class,
  db_offline ? 'db-offline',
  theme.settings.navbar_position ? 'navbar-is-' ~ theme.settings.navbar_position,
  theme.has_glyphicons ? 'has-glyphicons',
  'path-product-add',
]

And then clear cache of your website.