Set a content type's teaser image (right outlined) So I'm looking to get the image of the teaser display from the bottom outlined to the right. Here's screenshots to make it clearer.

As you can see, I've already managed to do it once, but I can't reproduce.
Also, can't find how to get the "add to cart button" on the product.

What you will want to do is go to your views admin page for that view.

If the view is built using fields simply click on that field and select:

Style Settings
Check the box titled "customize field HTML"
You can modify the view to display it as a div or leave it as is
Check the box titled "create a css class"
Type in a css class
Click apply. And save the view.

Now you can go to your theme .css file and create a new css rule to position the image. And should apply for all future views with that css class for that field.

Let me know if you need further help.


How to send an email after a specific node field gets updated by an admin? I need to send an email notification to the node editor (reviewer/moderator) when an admin changes a (custom) field.

I've added the list of editors as a field in node form.

The nodes will be created by users and unpublished by default.

The nodes will be assigned to editor for review by admin, the editor should be able to view records assigned to the editor.

When admin assigns a node to editor, the editor should be notified by email.

How can I notify editors when they are assigned a node by admin?

Rules requires data comparison, conditions to trigger action. But I need to trigger action when a particular field gets changed.

I would like to use Drupal hooks like hook_node_update, by that way we can get the email id of the editor (in my scenario) and notify the editor.

Programmatically where and how I use hook_node_update() to achieve this? Or can the Rules module be used? If so please explain in detail how to create a rule for this.

Check notification email link
my point is enough to post in comment box so i am posted here


Responsive not working after converting html theme to Drupal theme While trying to convert a HTML responsive theme to Drupal 7 theme, it's responsive is not working!!!

Can anyone help me with this to sort the issue? We have copied Bartik theme and removed the CSS and pasted the HTML5 theme CSS and JS that we created. changed the index.tpl into page --front.tpl.php and copied it into the template folder. In the page-- front.tpl.php we give all the path for CSS and JS as:

<?php $path="http://".$_SERVER['HTTP_HOST']; ?>
<link rel="icon" href="$path.">
<link rel="shortcut icon" href="images/favicon.ico" />
<link rel="stylesheet" href="<?php echo $path.base_path().path_to_theme()?>/css/style.css">.

"As specified we gave path for all CSS and JS files, but don't know where we went wrong!!"

To create or convert a Drupal 7 responsive theme, it is not a good idea to start with stripping down and modifying a fully developed, non-responsive theme such as Bartik.

Instead you start out with a responsive starter theme or base theme framework, where the css is already reset for you and where the the framework is already prepared for you to add your own classes to construct whatever look and feel you're after.  Basically, you install your framework, then create a sub-theme, and use that you build your own responsive theme.

Good foundations for this is IMHO Zen, Omega or AdaptiveTheme (suggested by @Kojo in a comment), but many other alternatives exist.


Create webform field on node create Ok, I'm building a custom module that has content type that is webform enabled. When creating a node of this type, I need to automatically create one webform select field when node gets saved. How can I achieve this? The goal is that all webforms have this field when they're created, rest are user created.

I am not sure about your use case.

But the following module does exactly that.

Webform Default Fields

  With this module you can easily create much of nodes with same webform
  fields. It can be applicable in case of job vacancies with reply form,
  kind of quality feedback control or whatever your mind suggests you.

  Because you can create more than one webform-enabled content types,
  you respectively can attach different default fields for each of them.


How do I pass a theme variable from a template to another? Several fields in a node need to be displayed in a particular way depending upon which newsletter body they are a part of. How do I pass a variable from the enclosing newsletter body to enclosed fields so that I can inform the field of its context and control the way the field is displayed?

I have a theme that has preprocess functions both for the newsletter body and for fields contained within the body.

I want to set a variable in the body preprocess function, and its related twig template, that can be inspected by the field preprocess function, and/or its own template.

In other words, I want each field to be aware of the body context in which it is being rendered.

Specifically, I have mytheme_preprocess_simplenews_newsletter_body() that sets a variable ($variables['summons'] = 'placeholder';) which can be inspected (and also set) by the theme's simplenews-newsletter-body.html.twig template, but (because it's in a different render array) is subsequently neither visible to mytheme_preprocess_field() nor field--node--title.html.twig.

How do I communicate between the two render arrays?

Note that

There are apparently global variables like $db_is_active and
$is_admin.
Sometimes, it is possible to achieve this kind of thing by cascading CSS
class attributes from a containing element to a contained element. This is not generally satisfactory and in this particular case, it won't wash on different target mail clients unpredictable treatment of CSS.

The solution I am working with is to use drupal_static(); simplified essentials in code below - take care with the &ampersands. It is giving me control where I need it.

So, using this approach, I can - taking their global context into account -  per field, set variables in the usual way e.g. in mytheme_preprocess_field() subsequently to be used in a related template like field--node--title--agenda.html.twig

function mytheme_preprocess_simplenews_newsletter_body(&$variables) {
  // prepare to alter static var ...
  // get a reference binding to static var
  $var = &myvariable_function();
  // alter static var
  $var = 'simplenews_newsletter';
}

function mytheme_preprocess_field(&$variables, $hook) {
  // prepare to read static var
  // assign static var
  $var = myvariable_function();
  // $element is the render array for the field
  $element = $variables['element'];
  // filter those cases where it matters that we're theming a newsletter
  if ($element['#view_mode'] == 'email_html' and $var == 'simplenews_newsletter') {
    // Do stuff here like setting a variable for twig ...
    $variables['summons'] = 'some text';
  }
}
function &myvariable_function() {
  $var = &drupal_static(__FUNCTION__);
  if (!isset($var)) {
    // generate contents of static variable
    $var =  'initial_value';
  }
  return $var;
}

I am sure that there are other ways of communicating common context between different levels of a page's render hierarchy. Let me know how you'd do it.


What are the recommended directory permissions? I'm gearing up to deploy a Drupal 7 site and I can't find any documentation about what the recommended security-conscious file and directory permissions should be set to.

Specifically default/files/ (also sub directories?), settings.php, .htaccess and anything else I should be aware of.

That drupal page like so many is very long and confusing. But it contains this post by Jason, who hit the nail on the head:

  Posted by Jason Sale on November 1, 2010 at 12:40pm

  Thanks for writing this and everything, but all that I and 99% of people reading this page really want is a list of numbers next to a list of folders.

  /default on 755
  /default/files including all subfolders and files on 744 (or 755)
  /default/themes including all subfolders and files on 755
  /default/modules including all subfolders and files on 755
  /default/settings.php and /default/default.settings.php on 444


Get custom fields from users table in global user object I've altered users table and added two new fields directly using MySQL workbench

first_name
last_name

If we add new fields by config > people > site information > manage fields, it does not allow adding drop-down list. So, directly added using MySQL workbench.

Now I was able to alter user_register_form and added above two fields with validation.
At the time of creating new user, the values of first_name and last_name gets stored in users table.

Now, how to get those two fields when user logs in?

i've used below code to print user object

global $user;
$user_full = user_load($user->uid);
print_r($user_full);

Any help would be appreciated, thanks !!

You can implement the hook_user_load() for this purpose

I have altered the user table with field "fname" , Now you can load this in user object with the help of hook_user_load() func.

function testing_custom_user_load($users) {
  foreach ($users as $record) {
     foreach ($users as $record) {

        $result = db_query("SELECT fname FROM {users} WHERE uid IN ($record->uid)")->fetchAssoc();

        $users[$record->uid]->extra =$result['fname'];
     }
  }

}

Just put this code snippet in any of your custom module file.


Different cusztomizable user profile types We need to add different customizable user profile fields in Drupal 6.  How can this be accomplished?

You can try creating different content types and referencing those contents with different users


List of content type in a bloc view I created a block which displays several type of content. On the page of Country, I have a block which has a list such as:

Anthem
Flag

To be able to do this, I addd a filter in the Advanced column. I don't know if it's the best way, feel free to tell me if there is a better way to do it. Well, this is what I have after this modification:

Anthem of XXX
Flag of XXX

As you can see, this is the right list. There is one type of Anthem or Flag. This is the other half of the issue, I don't know how to not let the flag to be chosen on the formula of a Country if it has already been for an other one. So, in the list, how to display the type of the content and not the title such as on the first list.

Thanks :D !

UPDATE: this are the screenshots of what I did and the result I have:

I want to add other types of content but I didn't find how to do.

Assuming you are trying to add a personalized text that links to the anthem of the country.

To achieve this, you can add a global text field and rewrite the output.

Step by step:

1) Add the field "Link to content" and fill out your personalized       text in the box that says "text that will show". Check the box       "exclude from display."

2) Select your title field and check the box "exclude from    display."

3) Add the field "custom text" (category global)

4) In the text field, add the token as seen in replacement patterns below called "{{ view_node }}" for the link to the content.

5) Save it all and you now have a link to the content of the current    country page, assuming you have set up the right    contextual filter.

If you are trying to achieve something else, please clarify and let me know.


Facets hierarchical taxonomy terms not working I use the Facet module version 8.x-1.x-dev. I have a list of taxonomy terms with parents and childs.

The taxonomy term facet is an Entity reference field. I can't get the hierarchical structure working in the frontend.

I fixed it by re-added the field from admin/config/search/search-api/index/default_index/fields and take the ID from the index instead of name. Then in the Facet settings use Transform entity ID to label. Then the hierarchical structure from the taxonomy terms works!


Displaying view as row-based table, not as grid Currently I have my view style set to grid (row style); but they're not displayed too nicely. Is there anyway I could modify the views grid php file so that I can have them displayed as a real table? If you set the view to table, you get all your fields as columns. I want to have something like

Feature A          x
Feature B          y

etc. so that they display nicely in a table view in iOS.

You can probably achieve this with CSS, rather than modifying the PHP - or are you saying you want to output as an actual HTML table?  Views should do that for you.


Configuring views to display all book-pages inside a book, from whenever you are inside the book Configuring views to display all book-pages inside a book, from whenever you are inside the book.

Is this possible? If so please advice the way to do it.

The contexual filter of All sub nodes of this book page creates an error soon as I relate it to any position or Node ID on a book-hierarchy.
When set view all pages instead - other books page is viewed together with the pages I want to display.

(The  Relationships here is set to top level book with Require this relationship)

I did found the reason why it not work (as it should), it's probably a bug at the "filter criteria", who not where working with setting of Book depth.
I am lucky because I had different content-types on each level of the book.
And when trash away the book depth filter criteria  I could set filtering on the Content type instaed, and all works out as I wanted.
So this problem is solved,now I can display all book-pages inside a book, from whenever you are inside the book without any problem.


How do I add a custom html.node--.html.twig based on content-type? I want to override the default html.html.twig according to my custom content-type.
But I only get suggestions like:

* html--node--16.html.twig
* html--node--%.html.twig
* html--node.html.twig
x html.html.twig

I have tried for file-name

html--node--content-type.html.twig

But this was not successful. Can anybody help?

You can use hook_theme_suggestions_HOOK_alter() to add another suggestion, something like:

function THEME_theme_suggestions_html_alter(&$suggestions, $variables) {
    // Check it's a node page.
    if (($node = \Drupal::routeMatch()->getParameter('node')) && $node instanceof \Drupal\node\NodeInterface) {
        // Insert as second to last so the more specific template by ID still works.
        array_splice($suggestions, count($suggestions) - 1, 0, 'html__node__' . $node->getType());
    }
}


How do I remove extra space in table field? I'm using Views Module. I created a new ContentType with 3 custom fields: (text)Criteria, (decimal)Monthly, (decimal)Semester.

I created a table style view that retrieved the ContentType I created and dropped the values into a table. I'm actually using Javascript to grab the contents of each row generating a JSON array of objects with key-value-pairs for the content of the table, then I'm doing some fancy Javascript rendering. It's just a quick way to leverage Drupal's views and get the data where I want it exactly.

Anyway, when I grab the content of the Title row, $(this).find('td.views-field-title a').text();, it works fine, but when I try the exact same thing with the other 3 rows, I end up with a lot of space and \n. So my object ends up looking like:

[
 {'title':'Correct Title','criteria':'\n     Criteria Title    ','monthly':'\n     $70.00     '},
 {...},
 {...}
]

I can't figure out where the \n and extra space is coming from. It seems to be how the view formats the fields. How can I get rid of those?

Note: I do have the fields set to Plain Text in the configuration.

I checked this in my site and this is indeed default behaviour of Views. The easiest way to fix this is by changing your code to:

$.trim($(this).find('td.views-field-title a').text());


Migrate into custom File Type I am writing the script for a file migration and am using the MigrateDestinationFile method.  I noticed that when I migrate the files that they default to the Document file type.  However, I have created custom file types and want the files to be migrated to those file types.

How can I do so?

I was hoping I could do something like this, but it's not working:

$this->destination = new MigrateDestinationFile('custom_file_type');

I really wish this was better documented.  In addition to the above you need to add a field mapping to the type:

$this->destination = new MigrateDestinationFile('custom_file_type');
$this->addFieldMapping('type')->defaultValue('custom_file_type');

That's it!


Alter Color module fieldset within theme settings form I've set up Color module for my theme - it works pretty well, but takes too much vertical space (I have a bunch of colors).
What i'm trying to do is to alter system-theme-settings form to make Color scheme fieldset collapsible.
So here's my code:

function test_form_system_theme_settings_alter(&$form, &$form_state) {
  drupal_set_message('DEBUG: ' . print_r($form['logo'], 1));
  // Above line prints array of logo settings - so function works well

  drupal_set_message('DEBUG: ' . print_r($form['color'], 1));
  /* This line prints nothing and I get:
   * 'Notice: Undefined index: color in test_form_system_theme_settings_alter()
   * (line 16 of /var/www/sites/all/themes/test/theme-settings.php).'
   */
}

As you can see, i can't alter $form['color'] because it doesn't exist.
Here's the color_form_system_theme_settings_alter function.

Am i missing something?

Definitly system-theme-settings is a core form where color module adding its fields using hook_form_alter in the same manner you are doing.

The point at which your hook_form_alter is invoked seems to be earlier then the color module's.

Check out hook_module_implements_alter to alter the registry of modules implementing a hook.


Rendering an entity the formatter way I have written a custom formatter for taxonomy term fields. Now I would like to expand the module and add a custom entity renderer to show the entity in the very same formatter-like way, using mostly the same code.

The reason I need it is that while theming Search API Views fields, I'm not given an option to format term reference as a field, but only as entity.

I thought I'd provide a custom entity view (via hook_entity_info_alter). But then, how do I provide the HTML output of the entity?

You can't render an entity like a field and vice versa. These are two entirely different things. However if you in a field loaded a related entity and rendered as a way of rendering the field, there could be some common ground.

That being said, your reason for asking this question doesn't really make sense. If you have a field on an entity and want to render the field. No matter how you render it, (through views, by viewing the entity etc.) you will have to use a field formatter to render that field.

Also regarding entities there is no common way of rendering them. The module defining them can render them any way it would like to and it's up to that module to make a way to render the entity. That being said, the entity API module does create some apis for doing this in a generic way, but that is not a part of Drupal 7 core.


How do I create a View of different entity types? I haven't used Views much before but it feels like I should be so I'm getting stuck in...

I think I'm missing something obvious here but how would I go about creating a view that 'mixes' several different entity types?

I have a custom field type attached to nodes, users, and also to user profiles provided by the Profile2 module. The field contains lat/long data (I know OpenLayers etc. provide this functionality, the field type was built as an exercise).

How can I create a view that contains all of the different entities that have this lat/long field associated with them? I'm basically after a simple table with 'Entity Title', 'Lat' and 'Long' as columns.

All of the different entity types are separated when I create a view (Content, Users & Profile) and I can't find a way to group them together so to speak.

Is this possible with Views or is not quite there yet with regard to entities?

Views uses a term it calls base table translated into SQL it is the table used for the initial query

SELECT something FROM {base_table};

The thing is that what you want to do is a bit atypical, instead of doing

SELECT something, field_item FROM {entity} LEFT JOIN {field};

You want to do

SELECT something, field_item FROM {field} LEFT JOIN {entity};

In order to do this you need to use the field you are after as the base table. By default this is not possible, but it's not much work required in order to do it. What you need to do, is to use hook_views_data or hook_views_data_alter and add the data for the field table and make it selectable as base table displayed when you create a view.

There's a lot of doc on how to do this (the Views doc), and I have written this in one or more answers here. So I won't bother explaining how to do this.


Retina image support (@1x @2x @3x) I've been struggling for a while to figure out how to support higher pixel density screens for my images in drupal. I have 3 variations for every image on the site (@1x, @2x, @3x) but I haven't been able to find an easy way to use them. I searched around and found articles like:
https://www.advomatic.com/blog/adding-responsive-images-to-your-drupal-8-site
and https://evolvingweb.ca/blog/making-drupal-websites-retina-ready

but they usually talk about using the retina module for drupal which seems to not pass security adviory policy or are just adding different image styles and using the picture tag. Is there no way to use just srcset and using 3 different images for different dpi in drupal?

Ideally I'd like to have an image field which will just let me upload 3 images for different dpi.

I think the answer from @ipwa is close but is not quite there.

What you want is an output like this:

<img src="/fallback.jpg" srcset="/1x.jpg 1x, /2x.jpg 2x, /3x.jpg 3x" />

Here's what you need to do:

Enable both the Breakpoint and Repsonsive Image Style modules.
Add an image field for uploading 1 image to a content type. Editors should upload the highest quality image needed.
Configure three normal image styles that produce the desired resolutions for each of the 1x, 2x, and 3x pixel densities.
In your theme, or a custom module, create a breakpoint yaml file with the following contents:

my_module_or_theme.image_pixel_density_only:
  label: Pixel Density Only
  mediaQuery: ''
  weight: 0
  multipliers:
    - 1x
    - 2x
    - 3x

Rebuild caches.
Add a new responsive image style.
Configure the responsive image style so that it uses the breakpoint group that you just created. This should expose a 1x, 2x, and 3x fieldset. For each of these fieldsets, select type "Select a single image style." and choose the appropriate image style.
Configure the image field formatter for image field you created in step 1 to use the responsive image style you just created.

Drupal will output the srcset just like I described above and will not output a "sizes" attribute (which you don't need). Browsers will know what the pixel density is of the device and automatically select the most appropriate image based on that.


How to create access permissions system similar to Organic Groups access, using Eck entities There currently still is not a working version for Organic Groups access control, compatible with ECK entities.

My current site contains entity type project and entity type project content.
The project content references the project through an entityreference field.

I would like to use an access control system that grants access to specific projects, and when that access is granted, the user has also access to specific project content entity types.

I know that Organic groups uses a relationship approach in which the group membership is an entity, and there is a two level deep relationship between group content (or group member) and the group.

In my case I prefer the simple direct entityreference (one level relation) between content and project. This would serve simplicity and performance. If you would advise against that, please let me kow.

I would like to receive guidance on how to set up such permission system, and possibly your suggestions and recomendations based on your experience with a similar setup. Thank you.

If you'd be willing to use the Group module, then you could do like so:

You can configure a Group Type named "Project", so that this Group Type would replace your entity type project.
You can create 1 Group (of group type "Project") for each of your Projects (each Group probably labelled with the name of a specific project).
You can assign nodes to a Group (of group type "Project"), so that these nodes would replace your project content entity types.

Group is available as of D7, and has a D8 version also. It is designed to be an alternative to Organic Groups. The Group module creates groups as entities, making them fully fieldable, extensible and exportable.

With the above in place, you also have the permission system you're looking for, out-of-the-Group-box.

More info:

Refer to "What are the various roles supported by the Group module?" for more details about the supported roles.
Refer to my answer to "How to configure access to courses for teachers and students?" for a sample configuration.

Integration with various modules

The Group module integrates with various other (popular) modules, including:

Rules, as illustrated in the answer to the question "How to bulk assign existing content to a group created with the Group module?".
Views, as illustrated in the answer to the question "How to show the content of a group on the group page when using the Group module?".
Pathauto.

The beauty, IMO, of these integrations are that they are more or less out-of-the box (not dozens of extra modules needed to make those integrations work).

Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".


Integration between js and php code in custom module I'm writing a custom module which outputs blocks with various deltas. Later, a jQuery code has to be attached for every generated block, aware of their id's, as in $('#mymodule-block-delta'). How is that accomplished?

You would use drupal_add_js() to pass the data from PHP to JS:

$block_ids = array('blockid1', 'blockid2');
$settings = array('myModule' => array('blockIds' => $block_ids));
drupal_add_js($settings, 'setting');

Then in JS you can pick these up like so:

var blockIds = Drupal.settings.myModule.blockIds;


How have multiple instances of a Custom Block? So I have a custom block that has been created within the module. I have used the drupal API to generate the brand new fields - which works perfectly.

However, I am having an issue regarding multiple instances of the custom block. As I want the blocks to be sandboxed as the custom fields are only related to the block used within the one region.

Now using Multi Block, I can create another instance of that block but the field is exactly the same. What would be the best approach for having one block but whenever its used, its custom fields per block.

case 'live_chat_block' :
    variable_set('text_variable', $edit['text_body']);
break;

Now the idea I had was to add in the "panel page" as variable ID but there might be a better way. Any suggestions would be useful.

Just to expand on what i would like to achieve:

We currently have panel pages implemented and we have built a custom block with custom fields inside that custom block. The requirement is that every block that we drag into one of the panel pages, we would like for them to have unique fields.

Panel Page: 1
Block ID: 123
Custom Field Title: Superman

Panel Page 2:
Block ID: 123
Custom Field Title: Batman

Now as you see, the only thing that changes is the panel pages, the block stay the same and the custom fields need to be unique to that panel page and not the block.

Currently, when changing one block, it impacts on all the other blocks as well.

function livechat_block_configure($delta=''){
  $form = array();

  switch($delta) {
     case 'live_chat_block' :
        // checkbox example:
      $form['text_body'] = array(
        '#type' => 'textfield',
        '#title' => t('Enter in Title here'),
        '#default_value' => variable_get('text_variable', ''),
      );

        break;
  }
  return $form;

}

Add the following function in your template.php

function <themeName>_render_block($module, $delta, array $options = array()){
  $default_options = array(
    'title' => '<none>',
    'region' => -1,
  );

  $options = array_merge($default_options, $options);

  $block = db_query('SELECT * FROM {block} WHERE module = :module AND delta = :delta', array(':module' => $module, ':delta' => $delta))->fetchObject();
  if($block) {
    $block = block_load($module, $delta);
    $block->title = $options['title'];
    $block->region = $options['region'];
    $blocks = array($block);
    $rblocks = _block_render_blocks($blocks);
    $render_array = _block_get_renderable_array($rblocks);
    return drupal_render($render_array);
  }
  return "";
}

then when you want to render the block just write the following line

print render <themeName>_render_block($module_name, <id of block>, array of options like title etc)

You can find module name and block id by going to block configuration page so for the path
admin/structure/block/manage/views/locations-block_1/configure
module name is "views" and id is "location-block_1"

So the render function will be

print render <themeName>_render_block("views", "location-block_1", array("title" => t("My block title")));


How to change DateTime field value on form submit I am trying to update a DateTime field in an altered form submit. Something like:

php
function my_module_form_submit($form, FormStateInterface $form_state) {
  if (!$profile->field_someother_field->isEmpty()) {
    $date = new DrupalDateTime();
    $date->setTimezone(new \DateTimezone(DATETIME_STORAGE_TIMEZONE));
    $string = $date->format(DATETIME_DATETIME_STORAGE_FORMAT);
    $form_state->setValue('field_date_updated_details', [$string]);
  }
}

But this fails with various messages (depending on whether I set the value as an array or directly as string).

Any advice?

The form value need to be an call DrupalDateTime, so you can directly pass $date as value.


Inspect $form from hook API How can I inspect the $form element from the hook_node_insert($node, $form, $form_value).
I need to know how it construct.
I try with firephp (dfb($form, 'form', FirePHP::LOG);) with no success.
Please help.

Install the devel module http://drupal.org/project/devel. In your code call dpm($form);


D7 - Can't set selected value of a webform select element I'm trying to set the selected value of a webform select form element before it is rendered. I'm using the below code and the textfields are working just fine but no luck with the select options.

function mytheme_preprocess_webform_form(&$vars) {
    $vars['form']['submitted']['emailAddress']['#value'] = 'some@email.com'; //This is working
    $vars['form']['submitted']['country']['#selected'] = 'BARBADOS'; // This is not working even though #default value is used instead
}

I can't figure it out why this is not working for select field. I would be glad if someone could help me.

Thanks in advance.

You can set value by using #value

$vars['form']['submitted']['country']['#value'] = 'BARBADOS';

But make sure that the select option key should be same

Example:

<option value="BARBADOS">BARBADOS</option>
$vars['form']['submitted']['country']['#value'] = 'BARBADOS'; //will work

<option value="barbados">BARBADOS</option>
$vars['form']['submitted']['country']['#value'] = 'BARBADOS'; //will not work
$vars['form']['submitted']['country']['#value'] = 'barbados'; //will work


How to get referring items from a Entityreference field in the opposing item list? (back reference) Using an Entityreference field in a content type A makes it possible to reference multiple items from another content type B to it. On node teaser pages or any other Views lists you can list them additionally on each row of content item from the content type A as a sub-list of referenced items. But how can I list the reference sources the other way around automatically without using another Entityreference field on the content type B (needless double-edit)?

Example: A car (content type A) has been repaired in 3 different car service stations (content type B). So the content type "car" gets a Entityreference field to add them (items from B). When I build a list of service stations (B), I would like to see a list of the cars (A) being repared in them automatically without an additional back reference field or additional modules like CER, making things needlessly complicated in the database.

NOTE: Basically it's the behaviour we would expect from Taxonomy terms, which are also Entityreferences in Drupal 8, but they seem to have some more build in functionality to work from both sides in item lists.

At the moment I only see 2 (edit: 3) options to solve the backreferencing issue without creating SQL request duplicates:

Using Views Field View for nesting a list of type A nodes referencing node type B via contextual filters in the second view to filter for each items nid (possible performance issue).
Syncing 2 Entityreference fields from both content types and maybe automate them with Rules and using the second Entityreference field for the back reference list in Views.
Using the CER module (I know you said no but), I think after testing that this module is the best option at the moment if you know that you want this connection synced "fix" and not individually changed.

First would have a huge performance impact if the lists and nested lists are long. And the caching modules required to compensate it are not ready yet for D8.

Second can have other issues sinces Rules not always work flawlessly and I am not 100% sure if Rules supports the needed triggers for this approach.

EDIT: Third is my recommendation. After testing around I was quite impressed about its simpleness and working warranty. It's not as flexible as using rules, but as I sad, rules is a story of ots own. So maybe you give it another try (CER).


Saving and retrieving value in hook_node_form_alter() This is in Drupal 7.

I have managed to add a section to the node vertical tab. But I have not found out how to save the value and retrieve the value. After saving the node if i go back to the node edit form it still shows the default value. What am I missing?

function myModule_form_node_form_alter(&$form, &$form_state, $form_id) {
  $form['test_settings'] = array(
    '#type' => 'fieldset',
    '#title' => t('test settings'),
    '#weight' => 0,
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
    '#group' => 'additional_settings',
   );

   $form['test_settings']['node_uaid'] = array(
    '#type' => 'textfield',
    '#title' => t('uaid'),
    '#default_value' => variable_get('node_uaid', "default"),
    '#size' => 50,
    '#maxlength' => 50,
    '#description' => t('test UAID.'),
    '#required' => FALSE,
    '#group' => 'settingsform'
   );
}

The final objective is a field in the node add/edit vertical form that is directly associated with that node. This field should be accessible in relation to the node.

Unlike building a settings form in Drupal using system_settings_form(), you need to do more than define the form field so that it's processed. You need to define a submit handler so your custom field can be processed. In your hook_form_alter() add a submit handler:

$form['#submit'][] = 'myModule_form_node_form_submit';

Then define your submit handler to process the form value for saving.

function myModule_form_node_form_submit($form, &$form_state) {
  variable_set('node_uaid', $form_state['values']['node_uaid']);
}


Can not find field_image(image) in drupal 7.24 I am new to Drupal. I am using a beginners guide pdf to get accustomed to it. It says at point 10 that :

Now, we will move on to the image property. We are going to use an existing field
for this property. In the Add existing field section, enter image for the Label. Select
Image: field_image (Image) from the Field to share drop-down, and click on the
Save button.

But in my installation:

I find no field_image (image)! What has happend?

An image field will only appear as an "existing field" if it has already been defined for some content type.  The tutorial you're following assumes it does exist.  It look like this is not the case in your configuration. By default, the standard Article content type has an image field.  You may have removed it, or deleted the Article type.

If there is no existing type with an image field, you need to add it as a new field, as shown below:

If no Image field appears in this menu, you may need to enable the core Image module. To do so, navigate to: Home » Administration » Modules. Then locate the Image module in the core sectio, make sure there is a tickmark next to it, and click Save configuration.


Send email before role expiration after long searching and many attempts I definitely need your help.

On the website I am currently working on, people can buy a "Participant" role for 1 year.
I'm using ubercart to handle the purchasing process.

I am trying to set up an automatic email which is sent when the Participant role is about to expire. Lets say 1 month before.

I know there is the Role module in UberCart, but I really don't like it and I also think it is not flexible enough. I also know about the User Expire module, but I am not sure I can do what I want to with it.

I was trying to create a Rule which:
- runs on every Cron run
- scan all the users Expiry Date field
- send an email to all the user with expiration closer than 1 month

Please give me some help...I am really out of ideas.

I hope I am missing a very easy way to implement it.

Thank you in advance,
guidout

Create a custom module, implement hook_cron(), it is nothing but a function which will be called whenever cron runs.

Here is an article explaining what are hooks.

For code reference install examples module.

Implement hook_cron()
Load all the instance of the computed field, where you store the expiry date

Either you can directly query the database using db_select()
Or, use field_attach_load() to load only that field instances, instead of loading whole user object. Here is an example of how to use field_attach_load().

Check the expiry date.

Send a mail using drupal_mail() if the role is going to expire.

Note: You probably want this cron to run only once a day, for that install Elysia Cron and configure this hook to run once everyday by 12:00 am.


Is there a way to create field collection table dropbox for added content in form Im creating a form in content type form format
I will enable public users to create content type for this form.

I have integrated a field collection module within this form like
adding multiple participants

The fields in the field collection contain fields for name, address, contact info, etc..
The user can add as many participants they want in the field collection.

My question is:
Whenever i try to click the button "add another Item" the whole field collection form stacks up in the page. So when I add 10 participants it will make the page longer and difficult to navigate.

What im thnking is, is there a way that i can create a table that contains the added info (displaying limited fields only) when I click the add another item.

similr to hierarchical Hierarchical Select dropbox function if you are familiar with this

Is there a module that performs similar to this?

There's the field collection table module which provides a table-based widget and formatter for field collection fields.

It's not the same as the hierarchical select Dropbox but its worth a look, and would probably serve as a good place to start if you're thinking about coding your own solution.


Views AJAX pager not working, though AJAX is enabled I have a view of 6 news items on my front page. These get rendered in teaser mode. I enabled a pager of 6 items, and also enabled AJAX as you can see in the settings below. AJAX is enabled in the Drupal modules, I am not blocking Javascript and the ajax.js file is loaded fine when I inspect my site. I have checked the console for errors, but no errors were shown. I tried to disable semantic views, but to no avail.

The view export can be found here, and the site can be found here. This is just a test environment: some other pages may not work.

A bigger image can be found here

I can't (yet) answer your question, but I can see where I think it's going wrong.

The Views JS is loading for your site, but the Views classes aren't being applied the same on your site and the test I'm using. I expect if you swap to another theme, you'll see the View start working. (That doesn't mean you need to abandon your theme, but it may help you track the problem down.)

In your JS console, you can inspect variables - and the relevant variable for you looks like Drupal.views.instances.GENERATEDNAMEHERE.element_settings.selector.

On a working test site, I see this (zoom in to see the JS). Note that the value in selector can then be used to obtain the wrapper div for the view HTML.

(To test: Copy the value from selector, and use it as a jQuery() selector. You can do this in your JS console.)

On your site, I see a value set in the same (similar, due to the generated ID) location, but that same value doesn't match an element in your HTML - jQuery returns an empty array, instead of an array populated with (one) matching HTML element.

So ... you need to work out what about your theme is preventing that DIV being applied. If your theme is from Drupal Contrib, you might check the issue queue. If you're using a module which strips extraneous DIV elements, that might be a place to look. And so forth.

Hope this helps ... it's not really an answer, but I hope it moves you closer to one!


In the People list, change from time span display to date display This is Drupal 7: when I am logged in as administrator and I click "People" to check the registered users, the default Drupal display is the "Member for", which displays a time span. For example: "2 min 10 sec" or "23 hours 24 min" or even "6 days 22 hours". How can I change that display to a "Member since" display that would show the date and time the user actually registered? Thanks!

I'm not aware of an existing module that will do this but the following function in a custom module will do the trick:

function MYMODULE_form_user_admin_account_alter(&$form, &$form_state) {
  // Get the user IDs listed in the form
  $uids = array_keys($form['accounts']['#options']);

  // Since loading the user objects will incur overhead it would be best to get the
  // created data directly from the users table. It's a shame because this query has
  // already been run in user_admin_account(), but it's not saved anywhere that we can
  // easily pick it up.
  $sql = 'SELECT uid, created FROM {users} WHERE uid IN (:uids)';
  $created_data = db_query($sql, array(':uids' => $uids))->fetchAllKeyed();

  // Loop through the results and change the column data for the "Member for" column.
  foreach ($created_data as $uid => $created) {
    $form['accounts']['#options'][$uid]['member_for'] = date('d/m/Y H:i', $created);
  }

  // Finally change the header to say "Member Since"
  $form['accounts']['#header']['member_for']['data'] = t('Member Since');
}

The only thing you might want to change is the date format...see PHP's date() function for all the available tokens


How do I limit use of Simple XML Sitemap to certain roles? For my Page content type, I want nodes created by administrators to be in my Simple XML Sitemap, but I want to exclude nodes created by non-admin users.
Administrators have permission to administer Simple XML Sitemap, and regular users do not.
On the Page content type settings, I have checked the box to index nodes of type Page by default.  (You must enable indexing by default in order to get the Simple XML Sitemap settings widget on the node edit screen.)
I tried to change the settings in hook_form_alter(), but it doesn't work because non-admin users do not ever see the Simple Sitemap widget (it is not attached to the form if the user does not have admin permission for Simple XML Sitemap).
So I'm stuck:

I have to enable indexing by default on the node edit page to get the widget to appear.
Non-admin users do not have access to the widget, so I cannot change the value for non-admin users with hook_form_alter() (I have to accept the default).

How do I resolve this paradox?

I found the answer based on this drupal.org comment.
You have to use hook_node_insert().
/**
 * Implements hook_node_insert() for MYMODULE.
 */
function MYMODULE_node_insert(EntityInterface $node) {
  switch ($node->getType()) {
    case 'page':
      $user = Drupal::currentUser();
      if (!$user->hasPermission('administer content')) {
        // Turn off Simple XML sitemap.
        $generator = \Drupal::service('simple_sitemap.generator');
        $generator->setEntityInstanceSettings('node', $node->id(), ['index' => FALSE]);
      }
      break;
  }
}


Theming custom fields Migrating from D7 to D8, can someone explain how to theme a custom field in a content type?

Say I start with the "Basic page" content type and I add an image field, however I don't want this image to appear in the body of the text, I want it to span the entire page.

In Drupal 7 I would have gone into /sites/all/themes/mytheme/templates/page.tpl.php and added the following:

<?php if(isset($node->field_image_undernav) && count($node->field_image_undernav) > 0):?>
    <?php $imagePath = file_create_url($node->field_image_undernav['und'][0]['uri']); ?>
    <img class="img-responsive" id="img-top" src="<?php print $imagePath;?>"/>
<?php endif; ?>

How do I do this in Drupal 8? I'm guessing it's something like /themes/mytheme/page.html.twig and adding:

{# Top Image #}
    {% if page.machine_name_of_field %}
       {% block machine_name_of_field %}
         {{ page.machine_name_of_field }}
    {% endblock %}
{% endif %}

This changes where I can render the image in the template, but includes unwanted fields (like title) and some DIV wrappers. I just want to locate the image URL.

If I do

{{ dump(page.machine_machine_name_of_field) }}

I get NULL. If I dump(page), I see the URL but concatenated as part of a string in ["#markup"]. Any way to extract just the image URL from this field so I can place it exactly where and how I want?

The official D8 theming documentation doesn't seem to have this info, and unofficial guides like John Hannah's is helpful but seems to stop after basic setup.

Any guidance on this specific issue or documentation to learn more is much appreciated.

Berdir set me in the right direction with this question but the actual specifics of what I needed are buried in the replies to this question on rendering images from a node:

in  /themes/mytheme/page.html.twig add

{{ file_url(node.machine_name_of_field.entity.uri.value) }}

That renders just the image URL so I can place the image anywhere.


How can I let anonymous users comment only once? I'd like anonymous users to be able to comment only once on a node. I thought about checking whether there's already a comment from the user's IP-adress and, if yes, hiding the comment form, but I don't know how to do that.

How can I achieve this?

You can do this by means of two functions called flood_register_event() and
 flood_is_allowed().

When a anon user views a node, call flood_is_allowed in hook_node_view that sets COMMENT_NODE_CLOSED for the node.

When a anon user comments, register that as a flood event in hook_comment_presave for that particular node. By setting the $threshold (parameter for flood_is_allowed) to 1, the user will be stopped from commenting after the first comment is posted.

This is the bare bones of how to implement hooks that make use of these functions:

function MYMODULE_comment_presave($comment) {
  global $user;
  if (!$user->uid) {
    flood_register_event($comment->nid);
  }
}
function MYMODULE_node_view($node, $view_mode, $langcode) {
  global $user;
  if (!$user->uid && !flood_is_allowed($node->nid, 1)) {
    // This bars the anon user from posting a second comment of the node.
    // For a more sophisticated blocking method (e.g. to prevent the comment form from
    // showing up), ask another question about how to do that.
    $node->comment = COMMENT_NODE_CLOSED;
  }
}

PS: The module Anonymous Publishing is already using this pair of functions to limit the number of comments an anonymous user can post (but not exactly in the way you specify).  However, looking at the source code of that module should give you an idea about how to use this pair of functions for flood control of anonymous comments.


Entity references linked to a wrong referent On a Drupal 7 multilingual site, I have a content type containing a field_group containing itself entity references fields.

I haven't enabled the i18n submodule "Synchronize translations" ("i18n_sync").

I have a content in French:

contentFR

entityreferenceFR 1
entityreferenceFR 2

I want to translate this content in Italian, so I translate the entity references first, like this :

entityreferenceIT 1 (translation of entityreferenceFR 1)
entityreferenceIT 2 (translation of entityreferenceFR 2)

Then, I translate "contentFR" in Italian, and associate my 2 Italian entityreferences to this new Italian content, like this:

contentIT (translation of contentFR)

entityreferenceIT 1
entityreferenceIT 2

Everything seems to go perfectly well, except that, when I go back to my French content, the references are the italian ones, like this:

contentFR

entityreferenceIT 1
entityreferenceIT 2

If I edit again the French content to set the French references instead of the Italian ones, the switch happens again in the other way:

contentIT

entityreferenceFR 1
entityreferenceFR 2

This is a live production site with 5 enabled languages. We've just enabled Italian and the issue exists only since then. Before, with other languages, everything was working well; the entity references were not linked to a wrong referent.

Also, I've seen this quite similar thread (Node translation syncing problem with entity references) but:

In my case, there's no synchronizing set on the reference field
There wasn't any answer given in the original thread

The enabled i18 modules are: Block languages, Multilingual content, Multilingual select, Path translation, String translation, Taxonomy translation, Translation redirect, Translation sets, and Variable translation. The disabled modules are: Field translation and Synchronize translations.

Do you have any idea why this happens?

I guess you need to enable entity translation for this field; it can be done in the field UI, after installing the Entity Translation module.


Add additional CSS class for particullar field in a node I'm trying to add additional CSS class to a field after the field is added. But not for all fields of that particullar content type, but only for those, that editor would like to. Like a module Formatter_field lets user to chose the field format - I have an image field and couple of different image formats, which I can chose after I upload an image which formatter_field.

I cannot find anywhere a solution, how to add additional css class to the same field.

For example:

User uploads an image via image field, using formatter_field he/she choses image format from image_cache and then adds CSS class wich adds border. Then adds another image to the same node (as image field is set to "unlimited"), choses different format and adds different CSS class, which gives different border to that image. And all this in one node.

update:

In my exact case I want to create a horizontal gallery, where images and texts are shown inline horizontally in such a way, that some of the pictures are bigger, some are smaller and are aligned in different heights and sometimes between those pictures there are text blocks with explanations about the works. Like in on a real gallery wall. :) Would be great that all one gallery is one node as it is easier to edit.

You could try theme_field as well

  Returns HTML for a field.

This is the default theme implementation to display the value of a field. Theme developers who are comfortable with overriding theme functions may do so in order to customize this markup. This function can be overridden with varying levels of specificity. For example, for a field named 'body' displayed on the 'article' content type, any of the following functions will override this default implementation. The first of these functions that exists is used:

THEMENAME_field_body_article()
THEMENAME_field__article()
THEMENAME_field__body()
THEMENAME_field()


Changing all PNG files in site to JPEG? Is there any way to instantly change all the PNG images in a D7 site to JPEG (with or without backup creating)? By all PNG images I mean to those uploaded via image-field as well as those uploaded via CKeditor.

Going through page after page and changing them manually would take much time, therefore I'm looking for a more automatic way.

Thanks for your advice.

With imagecache_actions module you have several actions. One of then is "File Format switcher" so you can serve JPEG instead of png without converting the source images.

For more information:
https://www.drupal.org/project/imagecache_actions


Issue with translating SQL query into Database API (count(*)) I'm currently building some SQL queries for a view that will display some statistics, and I'm having trouble with adding COUNT(*) in a couple SQL queries:

Original SQL query

SELECT LIBELLE, COUNT(*)
FROM PRESTATIONS
WHERE EXERCICE = 2017
AND NUMCOLL = 89519
AND ETAT = 'R?gl?e'
AND PRESTATION = 'AIDES'
group by LIBELLE;

The result is the following:

+----------+----------+
| LIBELLE  | COUNT(*) |
+----------+----------+
| RESULT 1 | 1        |
+----------+----------+
| RESULT 2 | 3        |
+----------+----------+

This is how I set my code up after reading a bit of documentation:

$group = $value->andConditionGroup()
    ->condition('EXERCICE', 2017, '=')
    ->condition('NUMCOLL', 89519, '=')
    ->condition('ETAT', 'R?gl?e', '=');

$con = \Database::getConnection('old_db');
$value = $con->select('PRESTATIONS', 'prestations');
$value->fields('prestations', ['LIBELLE']);
$value->condition($group);
$value->condition('PRESTATION', 'AIDES', '=');
$value->groupBy('LIBELLE');
$nb_demandes = $value->countQuery()->execute()->fetchAll();

However, when executing this code, I have the following error:

  Syntax error or access violation: 1055
  'old_db.prestations.PRESTATION' isn't in GROUP BY: SELECT COUNT(*)
  AS expression FROM (SELECT prestations.PRESTATION AS PRESTATION,
  prestations.LIBELLE AS LIBELLE, 1 AS expression FROM {PRESTATIONS}
  prestations WHERE ( (EXERCICE = :db_condition_placeholder_0) AND
  (NUMCOLL = :db_condition_placeholder_1) AND (ETAT =
  :db_condition_placeholder_2) )AND( (EXERCICE =
  :db_condition_placeholder_3) AND (NUMCOLL =
  :db_condition_placeholder_4) AND (ETAT = :db_condition_placeholder_5)
  )AND (PRESTATION = :db_condition_placeholder_6) GROUP BY LIBELLE)
  subquery; Array ( [:db_condition_placeholder_0] => 2017
  [:db_condition_placeholder_1] => 89519 [:db_condition_placeholder_2]
  => R?gl?e [:db_condition_placeholder_3] => 2017 [:db_condition_placeholder_4] => 89519 [:db_condition_placeholder_5]
  => R?gl?e [:db_condition_placeholder_6] => AIDES )

I do believe I didn't set up my COUNT(*) correctly but I can't find another way to do so.

How can I solve this?

Thank you in advance

As @Clive said, just add an expression to your first query. countQuery() is only about getting a single count for a query and in many cases it is very inefficient.

$con = \Database::getConnection('old_db');
$query = $con->select('PRESTATIONS', 'prestations');
$query->fields('prestations', ['LIBELLE']);
$query->addExpression('COUNT(*)', 'count');
$query->condition($group);
$query->condition('PRESTATION', 'AIDES', '=');
$query->groupBy('LIBELLE');

foreach ($query->execute() as $row) {
}


When should I use collect an end date for a field, instead of using 2 separated date fields? I need to make a content type with a Start Date and an End Date. I know that I can handle this in two ways:

Have two separate field
Have one field with a option of "collect an end date".

I wonder when I should choose either of these options. I assume that the second option is for representing an Event in a Calendar. But if I don't need this, is the first option then the best?

EDIT:

If you plan use the "collect an end date" option you need read this:

How to use the Time ago view formatter when you have an end date collected in your date field?

Because you can have problems with the Views module and the Time ago view formatter.

Why having two fields if one will be enough to serve the purpose?

Your question itself states that you need a "Start Date and End Date" so I think option 2 will be better, as it's simpler and could perfectly solve the problem you are facing. Also, the Date module is highly flexible, so displaying your dates in different formats will be easy enough.

On the other hand, only reason that comes to my mind for having 2 separate fields could be for re-usability, for example, if you wanted to reuse only one of your fields in another content type.


Compare specific content type with tags I have a content type called 'message' which has tags. The idea is that when viewing a message, the sidebar shows a block that lists titles of other messages who have the same tags as the one the user is currently viewing. I reckon this can be done with a view, though I have no idea how to work this out.

I managed to get it to work with a context filter.


Which hook to use in a custom module for tracking access to one particular page? I'm probably not fully awake this morning because it seems so trivial but I cannot figure it out.

I need a hook to track when user access a certain page (path = 'export-csv'). This page is not a node neither a View and neither a form... It is just a "path". And I need a hook that I could use in my custom module's file, not in templates.

I thought of something like hook_preprocess_page or but it doesn't seem to work.

I need a hook called before the page is fully loaded because the page is never truly displayed (it is a page for downloading a file and it just shows the download popup).

If you need precisions about my code or something, just ask. But I don't think that it is necessary.

Thanks in advance of course.

edit: I found a part of solution here but I still have trouble because of the nature of the page. I never truly land on the page and I think the hook is not called before the popup happens.

The callback function of this page looks like this:

function grap_contact_export_csv_page() {
  header("Cache-Control: public");
  header("Content-Type: application/octet-stream");
  header("Cache-Control: no-store, no-cache, must-revalidate");
  header("Cache-Control: post-check=0, pre-check=0");
  header("Content-Disposition: attachment; filename=\"grape-export.csv\";" );
  header("Content-Transfer-Encoding: binary");
  $fp = fopen('export.csv', 'r') or die('Impossible d\'accéder au fichier');
  echo fread($fp, filesize('export.csv'));
  fclose($fp);
  drupal_exit();
}

That's how I achieved that:

function grap_contact_export_csv_page() {
  grap_log_export(); // Calling another function to record tracking in DB
  header("Cache-Control: public");
  header("Content-Type: application/octet-stream");
  header("Cache-Control: no-store, no-cache, must-revalidate");
  header("Cache-Control: post-check=0, pre-check=0");
  header("Content-Disposition: attachment; filename=\"grape-export.csv\";" );
  header("Content-Transfer-Encoding: binary");
  $fp = fopen('export.csv', 'r') or die('Impossible d\'accéder au fichier');
  echo fread($fp, filesize('export.csv'));
  fclose($fp);
  drupal_exit();
}


How can I display a change password form on its own? I have a need to place a user's password reset form in areas outside the context of the user edit page.

This Change Password module looked promising; however, it is only available for drupal 6 and only a dev snapshot is available.

I could use hook_form_alter to hide the fields on the edit user form that are not related to the user's password, but I would prefer not to do that if at all possible.

I'm hopping this functionality exists somewhere already.

Thanks in advance.

I couldn't find anything out there already and it sounded like a handy thing to have, so here's a small module providing a block with a change password form:

File: change_password.info

name = Change Password
description = Provides a block containing a form for the current user to change their password.
core = 7.x

File: change_password.module

<?php

/**
 * Implements hook_block_info().
 */
function change_password_block_info() {
  return array(
    'change_password_form' => array(
      'info' => t('Change Password Form')
    )
  );
}

/**
 * Implements hook_block_view().
 */
function change_password_block_view($delta = '') {
  $block = array();
  // Only show the block for a logged-in user.
  if ($delta == 'change_password_form' && user_is_logged_in()) {
    $block['subject'] = t('Change Password');
    $block['content'] = drupal_get_form('change_password_form');
  }
  return $block;
}

/**
 * Password change form.
 */
function change_password_form($form, &$form_state) {
  // Sanity check
  if (user_is_anonymous()) {
    return $form; // Or drupal_access_denied()?
  }

  // Get the currently logged in user object.
  $form['#account'] = $GLOBALS['user'];

  // Textfield cor current password confirmation.
  $form['current_pass'] = array(
    '#type' => 'password',
    '#title' => t('Current password'),
    '#size' => 25,
    '#required' => TRUE
  );

  // Password confirm field.
  $form['account']['pass'] = array(
    '#type' => 'password_confirm',
    '#size' => 25,
    '#title' => t('New Password'),
    '#required' => TRUE
  );

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

  return $form;
}

/**
 * Validate handler for change_password_form().
 */
function change_password_form_validate(&$form, &$form_state) {
  // Make sure the password functions are present.
  require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');

  // Make sure the provided current password is valid for this account.
  if (!user_check_password($form_state['values']['current_pass'], $form['#account'])) {
    form_set_error('current_pass', t('The current password you provided is incorrect.'));
  }
}

 /**
 * Submit handler for change_password_form().
 */
function change_password_form_submit(&$form, &$form_state) {
  // Set up the edit array to pass to user_save()
  $edit = array('pass' => $form_state['values']['pass']);

  // Save the account with the new password.
  user_save($form['#account'], $edit);

  // Inform the user.
  drupal_set_message(t('Your password has been changed.'));
}

It's (lightly) tested and works, but you might want to give it a once-over for your own peace of mind.

Update I've chucked it up as a sandbox project in case anyone's interested.


How do I theme user reset password page? How I can template the user reset password page when I receive the reset password token based link?

/user/reset/2289/1545342420/zrmQkJAN9whwgu2xbKCW0KbIKigx7AsUgSo88UKr1c4

Wooha! I found the answer myself. These are the template file names which can be overridden to theme the pages.

page--user--reset.tpl.php
- To theme the reset password page when you will receive this of reset password URL in the email. /user/reset/2289/1545342420/zrmQkJAN9whwgu2xbKCW0KbIKigx7AsUgSo88UKr1c4

page--user--login.tpl.php
- To reset the user login page.

page--user--pass.tpl.php
- To theme the user password page when user enters the email address to recover the password.

See this for more information as well.
https://www.drupal.org/node/350634


Embedded field collection not saving with node using conditional fields Why is the field collection portion of my node form not saving?  I am working on a form that collects travel plans from staff members.  As part of this I have a nested field collection to collect itineraries and legs within those itineraries.

to give you a rough description of the related fields:

This is not all the fields on the form, but this should give the idea of the structure.  I fill out the form, save, and the saved node contains all the other information, but nothing that was in the field collections shows up.

Since country is an additional module, I tried deleting the country field, but that didn't solve anything.  I'm also using the conditional fields module extensively to show and hide other fields though the fields in the field collection are not affected by this.

Finally I'm using a custom module called missions (UPDATE:  I've disabled the module, and the problem persists, so it seems not to have been the form_alter) to show one field in the field_mr_fc_legs field collection when field_mr_home_leave is checked.  The entire code of which can be found below:

/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function missions_form_mission_request_node_form_alter(&$form, &$form_state, $form_id)
{
  $form['body'][LANGUAGE_NONE][0] += array(
    '#placeholder' => t('Day 1

*  Activity 1
*  Activity 2

Day 2'),
  );
  $form['field_mr_home_leave'][LANGUAGE_NONE]['#ajax'] = array(
    'callback' => 'missions_hide_home_leave_toggle',
    'wrapper' => 'itinerary-section',
  );
  $form['field_mr_fc_itineraries']['#prefix'] = '
';
  $form['field_mr_fc_itineraries']['#suffix'] = '
';
  if ((!empty($form_state['complete form']['field_mr_home_leave']['und']['#value']) && $form_state['complete form']['field_mr_home_leave']['und']['#value'] == 1) || (empty($form_state['values']['field_mr_home_leave']) && $form['field_mr_home_leave'][LANGUAGE_NONE]['#default_value'] == 1)) {
    $home_leave_toggle_access = true;
  } else {
    $home_leave_toggle_access = false;
  }
  foreach ($form['field_mr_fc_itineraries'][LANGUAGE_NONE] as $key => &$itinerary) {
    if (is_integer($key)) {
      foreach ($itinerary['field_mr_fc_legs'][LANGUAGE_NONE] as $key => &$leg) {
        if (is_integer($key)) {
          $leg['field_mr_fc_leg_home_leave']['#access'] = $home_leave_toggle_access;
        }
      }
    }
  }

}

function missions_hide_home_leave_toggle($form, $form_state) {
  return $form['field_mr_fc_itineraries'];
}

What is the likely cause of this?  The Recent log messages report shows just that the node was updated.  Is it my module?  Is it nested field collections?

What I've tried

I disabled my module, and it didn't make a difference
I removed the nested field collection and it didn't make a difference.
I removed the country field to verify that it wasn't the country module causing the issue.
The issue seems to be caused by conditional fields, when I disable that, the form saves properly.

I think, it's because field collection is not part of the node, field collection is a separate entity, which needs to be saved separately.

I once had to add up some number fields and save the value in a field collection field on hook_node_presave

/**
 * Implements hook_node_presave().
 */
function MYMODULE_node_presave($node)
{
  foreach ($node->field_collection_field[LANGUAGE_NONE] as $key => $value) {
    $fc_id = $node->field_collection_field[LANGUAGE_NONE][$key]['value'];
    $field_collection_item = entity_load_single('field_collection_item', $fc_id);
    $field_collection_item->save(TRUE);
  }
}


Use Drush to update multi-site setup I have a multi-site setup where 3 different sites share the same codebase.  All of the modules are in the all/modules folder so they all have the exact same modules.  I want to update the modules and core for the codebase with drush but I can't find a way to do it.

There is no settings.php file in sites/default so drush is throwing an error.  Do I need to just create a dummy database so drush can connect and update the modules? Obviously I will have to run update.php on the sites after the updates are made.

The databases are separated, they just share modules and core.

Instead of applying the updates to each individual site by using @sites which never worked, I was able to achieve it by running the updates on one specific site. Here is the code that worked for me:

drush -l example.com pm-update

example.com being the name of my symlink.  Side note: I did not have to create a drush alias for this to work.


Remove Home from menu at module installation I can remove the "Home" tab from the main menu going to /admin/structure/menu/manage/main, but I would like to automate it so that it is done at module installation. I checked that the configuration is saved in core.menu.static_menu_link_overrides.yml, but I cannot put it in config/install since it defines pages created by core. As a matter of fact, I should set enabled=false in the already existing page standard__front_page; how can I do that at module installation?

Following the suggestion from @Leigh Mason and copying almost verbatim from the link he posted, I ended up implementing hook_install():

function hook_install() {
  $menu_link_manager = \Drupal::service('plugin.manager.menu.link') ;
  $front_page_link = $menu_link_manager->getDefinition('standard.front_page') ;
  $front_page_link['enabled'] = 0 ;
  $menu_link_manager->updateDefinition($menu_id, $front_page_link) ;
  $cache = \Drupal::cache('menu') ;
  $cache->deleteAll() ;
}

and the link was successfully deleted. I think that the last two lines are not really needed, I will check it at the next build from scratch...


all internal links won't work in a local-wamp site even after .HTaccess and mod_rewrite setup I've imported a Drupal 7.41 existing site to my local machine on a wamp server. I've already imported it's .HTaccess (uncustomized), and have enabled mod_rewrite in WAMP and restarted all services.

Yet, anytime I click on one of the internal links at the local site, I get, is some, 404 error, and in some WSOD.

When I tried to log in via localhost:8095/yoyo I got this error after filling the details and clicking on the log in button, I've seen the following error, but I don't know should I do with it exactly? (Adding some kind of a class manually?) Updating the theme maybe?

For the 404 errors on any internal links, have you edited the /rewritebase in htaccess? If the site now resides in a file, or in the root, this may need commenting out, or enabling.

As for the error. Are you certain you copied all files correctly?

Also, are you certain your mySql was dumped correctly?

Steps to try and fix can be...

Move files again.
Try dropping and reimporting the database.
Running registry rebuild. Note: this is not a module, this is something you can run with drush, or by placing the php in your directory and accessing it.
Try following this guys comment https://www.drupal.org/node/1323786#comment-5305922


Render media entity image I have a media entity target id and I want to render the image contained in it. I've loaded the media entity using Media::load, I was hoping to use something like render() on some rendererable array that I can extract/generate from that media entity object.
I found a somehow related question here: How to get Media entity image (Entity Reference Field) URL in TWIG theme, using ImageStyle::load, but I want to render the whole image with its defined attributes (alt, title or fields). Any suggestions please?

You need to build a render array
$build = \Drupal::entityTypeManager()->getViewBuilder('media')->view($media, $view_mode);

and then place it unrendered in a template, Twig renders this automatically.


What is the difference between "content type" and "custom content type"? Can anyone explain to me the difference between content type and custom content type?

A content type is a type of node. Node types (aka content types) are generally created through the browser UI. However, they can also be created through code, which people refer generally refer to as a custom content type.


Query fieldCondition for custom content type I am attempting to query a custom content type called players (machine name) in a Drupal 7 module and it seemed to be working fine up until an hour ago. Nothing has changed on my side but now the 'Select' works ( with no fieldCondition, but when I add a fieldCondition I am getting empty results.

Here is my query:

$query = new EntityFieldQuery;
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'players')
  ->fieldCondition('field_email_address', 'value', $email_address)
  ->fieldCondition('field_password', 'value', $password)
  ->range(0, 1);

$results = $query->execute();

I have verified and reverified the bundle name, each machine name for the fields, and the values being passed in, but when I dump and die the query results, they come up empty.

Any ideas?

Assuming you're using the Email field module, the column name is email, rather than value.

If that's the case, just change that line to:

->fieldCondition('field_email_address', 'email', $email_address, '=')

You may need to make a similar change for the password field, depending on what type it is. The easiest way to check for valid column names is in the .install file of the module that provides it, within its implementation of hook_field_schema().


Only one of my site node's doesn't print it's alias I use the latest version of the famous Pathauto module and my site pages have Automatic alias that are shown well in the URL navigation bar of the browser... All of these pages are in Hebrew, But one of the pages which is in English, doesn't show it's alias and only node/20 is being printed...

For example you could go on all main-menu links and see it, instead of that one...

Here is a live example in my site.

What can cause it? Thanks!

assuming you are using Pathauto to accomplish this, try:

check the settings under /admin/config/search/path/settings and make sure the Update action is set to Create a new alias, Delete the old alias
edit the node, and make sure the 'generate automatic URL alias' is checked and save the node again - this should reset the alias for the node


how do I display both a term view and parent terms view on the same taxonomy term page I am using search api views to override core taxonomy term pages. I would like to create a view that displays parent term content as well like a related content block. Or as a view I can use when results are empty.

I am not able to achieve this so far. I have tried the Parent terms (indexed) filter using every default argument combination I can think of. I have tried the indexed taxonomy terms filter also using every default argument I could imagine. What I assumed would be a very simple views has turned out to be rather complicated. I am starting to wonder if it is actually not a configuration problem at all but related to search api and might not even be possible in the first place.

Please follow the steps to show content of Parent Term on current Term.

Create a view as block
Add relationship as Parent Term
Add contextual filter as Term ID using the relationship and set it like this
Add filter criteria as Taxonomy Vocabulary using the relationship
Add fields whatever you have in taxonomy and use relationship as well

You can also follow the steps in the pics I've created for you.

You don't need to create a new view to show the content of current taxonomy, you can set manage display. Go to admin/structure/taxonomy/TAXONOMYNAME/display

While if you want to display using view, then create another view and follow these steps:

Add contextual filter as Term ID and set it like this
Add fields of the taxonomy you want to show

Note that we won't use any relationship in this view

Now, go to in the block configuration admin/structure/block and enable these.

I hope this will work for you


Billing address missing for recurring orders I'm using Datatrans module as payment gateway. Module does not fully support recurring payment, so I had to add some missing functionality. I added method createPayment:
  public function createPayment(PaymentInterface $payment, $capture = TRUE) {

    // Allowing only new payments
    $this->assertPaymentState($payment, ['new']);

    $payment_method = $payment->getPaymentMethod();
    $amount = strval(floor(floatval($payment->getAmount()->getNumber())*100));

    // Calling Datatrans API and handling response
    $transaction_data = [
      'apiUrl' => $this->configuration['r_api_url'],
      'errorEmail' => $this->configuration['r_error_email'],
      'successEmail' => $this->configuration['r_success_email'],
      'transactionRefNo' => $payment->getOrderId(),
      'merchantAccountId' => $this->configuration['r_merchant_id'],
      'merchantAccountPassword' => $this->configuration['r_merchant_password'],
      'sign' => $this->configuration['r_sign'],
      'req_type' => $this->configuration['req_type'],
      'expm' => $payment_method->expm->getValue()[0]['value'],
      'expy' => $payment_method->expy->getValue()[0]['value'],
      'amount' => $amount,
      'currencyCode' => $payment->getAmount()->getCurrencyCode(),
      'aliasCC' => $payment_method->getRemoteId(),
    ];

    $transaction = DatatransHelper::makeTransaction($transaction_data);

    // Saving payment locally

    $next_state = $capture ? 'completed' : 'authorization';
    $payment->setState($next_state);
    $payment->setRemoteId($transaction["uppTransactionId"]);
    $payment->setExpiresTime(strtotime('+5 days'));
    $payment->save();

  }

And it works, but problem I have is that all recurring orders created by recurring module do not have billing addresses.
Looked at database and condition for an order to have billing address (table "commerce_order") it must have id of user profile set in fields "billing_profile__target_id" and "billing_profile__target_revision_id". If I put some billing profile ids there directly, by editing database billing profile for that order appear and everything works as expected.
What (and where) should I add to my code to set that billing address?
Inside RecurringOrderManager() , refreshOrder() and createOrder() methods I saw row like:
 $billing_profile = $payment_method ? $payment_method->getBillingProfile() : NULL;

and that getBillingProfile() may be the method I'm missing (I do have null instead of billing profile id in database), but what confuses me is that it's defined in PaymentMethodInterface and Datatrans module is not implementing it at all?!
Is it up to Datatrans module to do something in order to set billing profile? How can I do that? I'm not very familiar with this and any hint is welcome.

Some workaround:
  // For unknown reason recurring orders are not getting billing profiles.
  // This method is checking of order has billing profile and if not
  // it finds it's initial order over subscription and copies it's
  // billing profile.
  public static function addMissingBillingAddress (Order $order)
  {
    if ($order->getBillingProfile() == null) {
      $subscriptions = self::collectSubscriptions($order);
      $subscription = array_shift($subscriptions);
      $initialOrder = $subscription->getInitialOrder();
      $billingProfile = $initialOrder->getBillingProfile();
      $order->setBillingProfile($billingProfile);
      $order->save();
      return;
    }
  }

  public static function collectSubscriptions($order) {
    $subscriptions = [];
    foreach ($order->getItems() as $order_item) {
      if ($order_item->get('subscription')->isEmpty()) {
        // A recurring order item without a subscription ID is malformed.
        continue;
      }
      /** @var \Drupal\commerce_recurring\Entity\SubscriptionInterface $subscription */
      $subscription = $order_item->get('subscription')->entity;
      // Guard against deleted subscription entities.
      if ($subscription) {
        $subscriptions[$subscription->id()] = $subscription;
      }
    }
    return $subscriptions;
  }

When I'm processing recurring order I'm checking if billing address is missing and if it does I'm collecting one from initial order (over subscription) and injecting that one.
Of course, I would like to know why it's not added at first place.


Possible to theme the form's elements with own twig? I was thinking to get twig outputs so I could use these twig variables on a form.html.twig such as below:

            {{ form.name }}
            {{ form.mail }}
            {{ form.subject }}

            {{ form.body }}

            {{ form.submit }}

Any idea how to get the similar variables via hooks on MYTHEME.theme?

I found out a solution which I ended with using {{ element.[machine name] }} instead of {{ children }} on my custom template which is cloned by form.html.twig. The result of the code look similar below:

            {{ element.name }}
            {{ element.mail }}
            {{ element.subject }}

            {{ element.body }}

            {{ element.submit }}

If you have other suggestion, I am happy to know! :)


How do I find a Form_ID for hook_form_FORM_ID_alter? I want to alter the form for a content type I created for videos.  The type is called Videos.  How would I use hook_form_alter to alter the form to create the content?

The form ID is used as the id attribute on the form when it renders.

For content types the pattern is also predictable:  node-[TYPE_NAME]-form.  So in your case you're looking for:  hook_form_node_videos_form_alter().

Another way to handle it is to use the main hook_form_alter() and check the $form_id parameter when you load the form you'd like to target.


Event is not responding properly I created 2 rules with the same action, which sends Drupal logs to the site. One is Content is created with the After saving new content (rules_entity_insert:node) event; the other one is Content is updated with the After updating content (rules_entity_update:node) event. Also, they use the same Condition: Node is of type condition.

I am using a REST request to create/edit a node. However, when I do a POST, I am getting 2 logs in the site, which means that both rules are being triggered. PATCHing a node is working fine: A single log is created.

Am I missing something?

I am using the Rules module 8.x-3.0-alpha3. The action is programatically created.

Problem solved by https://www.drupal.org/project/rules/issues/2990211#comment-12716081

  I have another rule that modify the title of my node with event
  After updating content (rules_entity_update:node). But since that rule is necessary, then it should not be deleted but still I dont want
  to get a duplicate result when a node is created. So what I did, is I
  change the other rule that modifies the title into event Before
  saving content (rules_entity_presave:node) so it wont be called on
  node creation, and this works!


Where do I put PHP to get a term ID? I've been trying to figure our how to get a term ID of a taxonomy term I created, and I found a little bit of php that looks like it should work. However I have no idea where to put it to get a response.

I'm working on a D6 site that needed updating and already found this script

$term = taxonomy_get_term($tid);
$name = $term->name;

Any pointers?

That code won't work.  The first line is using the $tid to load the term, obviously that won't work if you don't know the Term ID in the first place.

You don't need to use any PHP to get a taxonomy terms ID. Just goto the edit page of that term and look at the url. It will be /taxonomy/term/TID/edit


Optional field in admin panel to filter nodes in view Is there a way to add a optional field that filters nodes in a view?

I'm fairly new to drupal but I have a view that renders nodes depending on their categories. I can edit the view and manually add the filter but that affects all the nodes with that view. So is there a way to add filed to the "edit" screen of a page so I can have a field, that when filled it will filter the nodes it picks up and when it is empty it shows all the nodes?

Sorry if I'm using the wrong vocabulary, really new to Drupal

Not a problem... Drupal does have its own jargon but after a while you will get it.
Very simple solution whenever you want to offer user an option of refining the view or sort... Expose the relevant filter(s), in this case the vocabulary or taxonomy term...
You might also think about using the global null function so as to reduce load on your server ... This will basically produce no results until the user chooses a vocabulary or taxonomy term (category)... Here is an excellent walkthrough on how to do this: How to prevent views from loading the results upfront

Cheers,
gg


How can I add HTML ASCII codes into menu link items? Is there a module or method for adding in HTML ASCII codes into menu item links in Drupal 7?

Currently, I want to make the following a link in my footer menu.

&copy; Copyright 1998-2000

Yes. Menu HTML.

  This very simple module adds a checkbox to the menu item edit form and allows the admin to add html to the menu item title. The idea is to use this for external links for which you want to display a logo of the visited site or simply to add strong on some words.


where is the breadcrumb printed at in the omega kickstart theme? can someone tell me where omega kickstart breadcrumb is printed in code I have looked in the templates dir and there dosent seem to be a page.tpl.php and the template.tpl.php in the main dir dosent have it either I want to move it to just over the content

By default it's printed in in the omega/templates/zone--content.tpl.php template file in the Omega theme itself.

<?php if ($breadcrumb): ?>
  <div id="breadcrumb" class="grid-<?php print $columns; ?>"><?php print $breadcrumb; ?>

<?php endif; ?>


How can you change the temporary directory? I migrated the site from the local server to live server. But the images do not appear - the website logo and some PDFs. I've been seeing the problem could be here "Config" >> "file system" and my temporary directory is: /Applications/MAMP/tmp/php because I need to change that. But I do not know how. if you can help me. please

  Warning: move_uploaded_file(temporary://logo_verde_maior.png): failed
  to open stream:
  "Drupal\Core\StreamWrapper\TemporaryStream::stream_open" call failed
  in Drupal\Core\File\FileSystem->moveUploadedFile() (line 81 of
  core/lib/Drupal/Core/File/FileSystem.php).

This is error:

  Warning: move_uploaded_file(): Unable to move '/tmp/php9al1tV' to
  'temporary://logo_verde_maior.png' in
  Drupal\Core\File\FileSystem->moveUploadedFile() (line 81 of
  core/lib/Drupal/Core/File/FileSystem.php). File upload error. Could
  not move uploaded file.

In https://www.drupal.org/node/3039026 / https://www.drupal.org/node/3039255, which was introduced in Drupal 8.8.0, the ability to configure the temp directory was removed from the UI and moved to settings.php.

From the change record:

  The following lines are now in default.settings.php

/**
 * Temporary file path:
 *
 * A local file system path where temporary files will be stored. This directory
 * must be absolute, outside of the Drupal installation directory and not
 * accessible over the web.
 *
 * If this is not set, the default for the operating system will be used.
 *
 * @see \Drupal\Component\FileSystem\FileSystem::getOsTemporaryDirectory()
 */
# $settings['file_temp_path'] = '/tmp';

So, you should edit your settings file.

If your temp directory is different in your environments, you need a mechanism to handle this.  I typically use .env files for this, the database connection info, and some other settings.


Content and data migration module? I'm looking for a content and data migration module.

Which are commonly used?

Try

Backup and Migrate

Migrate

Related projects

Migrate Extras

Migrate Drupal


How to unpublish nodes which are missing in migration source? I have a CSV file with two rows. I executed the migration and two nodes are imported.
Now I deleted one row from the CSV and execute the migration again.
I now want to unpublish the node which is missing in the CSV.
Is it possible? How will I do that?

I have used an EventSubscriber for this. Here is my code.
/**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events = [];
    $events[MigrateEvents::PRE_IMPORT][] = ['archiveMissingNodes'];

    return $events;
  }

  /**
   * Archives the missing contact persons.
   *
   * @param \Drupal\migrate\Event\MigrateImportEvent $event
   *   The migration import event.
   *
   * @throws \Drupal\Core\Entity\EntityStorageException
   */
  public function archiveMissingNodes(MigrateImportEvent $event) {
    $migration = $event->getMigration();

    if ($migration->id() === 'my_migration_id') {
      $id_map = $migration->getIdMap();
      $id_map->prepareUpdate();

      // Clone so that any generators aren't initialized prematurely.
      $source = clone $migration->getSourcePlugin();
      $source->rewind();
      $source_id_values = [];

      while ($source->valid()) {
        $source_id_values[] = $source->current()->getSourceIdValues();
        $source->next();
      }
      $id_map->rewind();

      while ($id_map->valid()) {
        $map_source_id = $id_map->currentSource();

        $destination_ids = $id_map->currentDestination();

        if (!empty($destination_ids['nid'])) {
          $node = $this->nodeStorage->load($destination_ids['nid']);

          if ($node instanceof NodeInterface) {
            if (!in_array($map_source_id, $source_id_values, TRUE) && $node->get('moderation_state')->getString() !== 'archived') {
              $node->setNewRevision(TRUE);
              $node->set('moderation_state', 'archived');
              $node->set('revision_log', '');
              $node->setRevisionCreationTime($this->time->getRequestTime());
              $node->setRevisionUserId($this->currentUser->id());
              $node->setRevisionTranslationAffected(TRUE);
              $node->save();
            }
          }
        }

        $id_map->next();
      }
    }
  }


Creating a Youtube block using Views for Embedded media field module I created a content type called Videos.

In it there is a file field with a Embedded Media Field widget, and using the Media: YouTube module to post Youtube videos.

I created a block showing links to the latest 10 nodes of content type Videos.

This works fine.  However now I want to create another block showing a thumbnail of the latest video and if a user clicks on it, it will take the user to the node of that video.  I have played around in Views and there doesn't seem to be a way to expose the thumbnail of a video.

Any suggestions?

You should use the formatter, that's how it works. You just change the Option of the field to Image Thumbnail.


How to add fields to file entities? In Drupal 7, the Media module allowed you to add fields on a file entity. I don't see this ability out of the box in Drupal 8.

How can I add fields to file entities in Drupal 8?

In D8 the module File Entity provides this feature, same as in D7. It was required by Media, so you probably installed it without noticing in D7.

The new Media package for D8 doesn't use this anymore. Instead it uses a new media entity for the extra information. There is work going on to put the media entity in core for 8.3:

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


How to get all node entities tagged with a specific term? For a given taxonomy term in D8, is there any API function/method that returns all node entities that reference it?

You can use loadByProperties() to get all node entities that reference $term_id:

$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadByProperties([
  'field_tags' => $term_id,
]);


Unable to set default value for checkbox form element inside tableselect I've created a custom table using a tableselect element, and within each row, I have a checkbox form element that should populate the checkbox from a checkbox field in the node. I've tried every possible format of #default_value (setting it to 1, array(1), etc), to no avail. Since in HTML it's the checked attribute that causes a checkbox to show as checked, I came up with this option:

  foreach($translations as $locale => $locale_data) {
    // Get data for other fields...

    // Get data for Staging Only checkbox
    $staging_only = isset($entity->field_pub_staging_only[$locale]) ? (int)$entity->field_pub_staging_only[$locale][0]['value'] : 0;

    $row = array(
     'language_locale' => $locale_link,
     'status' => $status,
     'stage_url' => $stage_url,
     'start_date' => array(
       'data'=> array(
         '#type'=>'textfield',
         '#value'=> $new_start_date,
         '#title' => 'Start Date',
         '#title_display'=>'invisible',
         '#name'=> 'start_date[' . $locale . ']',
         '#id'=>  'start-date[' . $locale . ']',
         '#attributes' => array('class' => array('datepicker')),
         '#size' => 10,
         '#maxlength' => 10
       ),
     ),
     'end_date' => array(
       'data'=> array(
         '#type'=>'textfield',
         '#value'=> $new_end_date,
         '#title' => 'End Date',
         '#title_display'=>'invisible',
         '#name'=> 'end_date[' . $locale . ']',
         '#id'=> 'end-date[' . $locale . ']',
         '#attributes' => array('class' => array('datepicker')),
         '#size' => 10,
         '#maxlength' => 10
       ),
     ),
      'staging_only' => array(
        'data'=> array(
          '#type'=>'checkbox',
          '#title' => 'Staging Only',
          '#title_display'=>'invisible',
          '#name'=> 'staging_only[' . $locale . ']',
          '#id'=> 'staging_only[' . $locale . ']',
          '#default_value' => $staging_only
        ),
      ),
      'display_title' => $title
    );

    if ($staging_only) {
      $row['staging_only']['data']['#attributes'] = array('checked' => array('checked'));
    }

    $options[$locale] = $row;
  }

  $header = array(
    'language_locale' => t('Language Locale'),
    'status' => t('Status'),
    'stage_url' => t('Stage URL'),
    'start_date' => t('Start Date'),
    'end_date' => t('End Date'),
    'staging_only' => t('Staging Only'),
    'display_title' => t('Display Title')
  );

  $form['table'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $options,
    '#empty' => t('No content available.'),
    '#attributes' => array('id' => array('locale-table')),
  );

...

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

  return $form;
}

where I'm basically manually added the checked attribute to the element when it's checked. It works, but it seems sort of hackish, since it's not using what would normally be used to set a form element value with Form API. Is there a better way to do this with the usual Form API settings?

CLARIFICATION It appears that my question wasn't clear, based on the answers I've received so far. The issue is not whether the tableselect row checkbox is checked by default; the issue is attempting to mark as checked the staging_only checkbox, which is a separate from api element within the tableselect row.

I remember struggling with this for a moment ! The documentation is not so explicit..

The tableselect element takes a #default_value array as a multiple select element would do, that is at the same level as the #options array, and with each selected option key being mapped to a truthy value, usually integer 1.

In the foreach, you would do something like this :

if ($staging_only) {
  // $row['staging_only']['data']['#attributes'] = array('checked' => array('checked'));
  $selection[$locale] = 1;
}

And then :

$form['table'] = array(
  '#type' => 'tableselect',
  '#header' => $header,
  '#options' => $options,
  '#default_value' => $selection,
  '#empty' => t('No content available.'),
  '#attributes' => array('id' => array('locale-table'))
);

Non present options in the selection array default to false so you can ignore unchecked values.


Cannot override template provided by contrib module in theme I'm leveraging the Superfish module for our menus but need to tweak the output a bit.
Normally I'd just copy the relevant template file (in this case superfish-menu-items.html.twig) into my theme and call it a day.
This isn't working in this case. Any ideas why that might be and how to get around it?

Before voting to close this issue, I'd ask that you request information you think would be valuable to providing additional specificity.
I can only assume that this issue is due to some issues with the construction of the Superfish module itself and its theming implementation, so I'm trying to figure out how to work around this.
Any solution would likely be applicable in similar contexts as well.

I've tried modifying the element in hook_theme() and hook_theme_registry_alter() to point to my theme's implementation of the template, but in both cases I end up hitting

  Twig_Error_Loader: Template is not defined errors.

EDIT: I'd already enabled debugging prior to posting. Please stop suggesting that I enable debugging. This is what is shown before and after copying the template into my theme. I've cleared caches and verified the template name in my theme.

For drupal8 you need to enable twig debug in the service.yml file. Then clear cache. After that, you will see in the browser inspector all templates name suggestion to override a part of the page.


Multiple forms on single page? Is it possible to put multiple forms on a single page?

I am trying to make a coupon offer page. I wanted to have two forms for two different offers on each side of a page. Each form has a text field for the coupon code and its own submit button. The first form works okay; however the second form's hidden values seem to be overridden by the first form's.

I'm using hook_alter to alter the second form to make it different, but it still has the same form_id as the first. Is this what's causing my problems, or do I need to look/think somewhere else?

The two forms have the same values for "form_id" and "form_token," but different values for "form_build_id."

If you want to add the same form multiple times, you need to implement hook_forms(). See node_forms() for an example.

This allows to use different form_id's, which all point to the same form builder function. For example, you can use yourmodule_some_form_$i and then use hook_forms() to point these to yourmodule_some_form.

See http://www.mohitsharma.net/content/how-show-same-form-multiple-time-page for an example