How do I display my products? I have managed to create a product type and import my product data, so I now have a list of products.

How do now go about getting the products to display? Do I have to build a content type from scratch and add the fields manually, or is there a way to generate the content type?

As pjskeptic mentioned, you can build a generic display mechanism using Views (or potentially Panels), but the primary way to establish one piece of content as a product display is to use a custom content type with a Product Reference field using the Add to Cart form display formatter. This has some distinct advantages:

Your product display node gets multiple view modes (i.e. teaser vs. full page vs. RSS) and can receive comments (i.e. user reviews and ratings if you set it up).
Product fields will be rendered and displayed in the node, including the product's Price field by default but also accommodating custom fields you add to products (i.e. an Image field).
A single product display node can reference multiple products through the Product Reference field, which turns the add to cart form into a product selection form and/or an Ubercart style attribute selection form. However, unlike Ubercart attributes, the product attribute selection form here accommodates dependent attributes, only shows valid attribute options based on the products you have referenced, and dynamically updates any product fields displayed on the node to show the currently selected product. This results in allowing unique images based on product or attribute selection, as seen in the mug product on the demo store.

There are some other advantages her, too, but it's worth noting that we understand this introduces complexity into the product display creation process. We made the decision early on to build what we thought was a sound architecture (separating the product definition from its point of display) and to simplify the store administration aspect through the use of installation profiles and contributed modules. To whit, you can use the Commerce Kickstart installation profile to create an installation of Drupal 7 + Drupal Commerce that includes a pre-configured Product display content type and adds an Image field to the basic product type. (Unfortunately, you'll have to know Git to grab this, as installation profile packaging is currently non-functional for Drupal 7 profiles.) Additionally, we're working on projects that allow you to bulk create products / product displays and to add / edit products directly in the node edit form using a custom Product Reference field widget.

To set this up manually, follow these steps:

Add a node type called Product display. Submit using the Save and add fields button.
Add a Product Reference field that uses an Autocomplete text field widget. Make the field required and allow an unlimited number of values (even if you only intend to use a single value for now).
Click over to the Manage display tab and ensure this field uses the Add to Cart form display formatter. You might also want to move around the product fields you see listed here.
Create a Product display referencing one of your products and examine the node's teaser and full page views. You may want to change the way product fields are displayed. To do this, you actually have to browse to your product type's Manage display page and update the display formatter settings there. You can only adjust the sort order and visibility of product fields through the content type edit pages, not the formatter settings.

There's more to it, but this should get you started. This process is actually the topic of an article I wrote for the first issue of Drupal Watchdog. I hope to be a regular contributor on the topic of Drupal Commerce, so I encourage you to get a subscription if you weren't at DrupalCon when the magazine was released. It may be the articles appear on the website eventually after printing.

For further support, I'd encourage you to browse the forum posts and documentation on this topic on DrupalCommerce.org and check out the #drupalcommerce IRC channel on irc.freenode.net. If you find any bugs or want to contribute to the usability discussion, we'd love to get your feedback as a site builder in pertinent issues in our issue tracker.

Oh, and if you're a visual learner, I walk through this process and explain how the architecture works in my session video from DrupalCon Chicago. It's the best video to date, though I'd love to see smaller screencasts targeting specific steps of Drupal Commerce site building get produced in the future.

Best of luck!


How to get all Taxonomy Term attached to Node? The Node has attached two terms.

Term::load($node->get('field_posts_category')->target_id); only returns first item. How to get all Taxonomy Term attached to Node?

Use the method referencedEntities() to get all terms:

$terms = $node->field_posts_category->referencedEntities();


How can I use the Add Product form as content in the main menu? I am using Drupal Commerce to add products to my site.
I would like to use the Add Products form as content in the main menu to make it more user-friendly to edit.
How can I do that?

Admin > Structure > Menus > Main Menu > Add link

Title: Add product
Path: admin/commerce/products/add/product

Keep in mind, that is for admins to create backend products for the inventory, not front end product displays.

It will also only be generated for admins with the relevant permissions.

To add a link for creating a frontend product display, the path would be something like

node/add/product-display


Using Entity Registration, how can I create a view that shows all the events that a user has NOT registered for? Using the Entity Registration module's built-in Views integration, I was easily able to create a view showing the events that the logged-in user has registered as attending.

Content type: Event
Date field
Registration field

I created a view of registrations with a relationship of registration to node.

Now, however, I would like to create a list of the content type event but only show those events for which the logged-in user has not registered.

I can add a relationship node to registration, but I don't know how to structure the filter to remove the events for which the logged-in user has registered.

I'm afraid it will be hard.

Seems like you are looking for something like this feature - sadly, it is not implemented (yet?). Problem is, SQL does not support anti-joins in any reliable generic way, so most of generic solutions built on top of SQL databases can't do it, either. Materials I used to code similar case (or similar ones) are still to be found under this search: http://google.pl/search?q=sql+anti-join

Maybe there is a way to create view like that. If you only want it to work when view is filtered by one user, you could implement hook_query_alter(). Use ->hasTag() to determine if query came from the view you want to alter, and then ->conditions() to make sure it shows results for just one user (to avoid things getting messy). Then you can outer join appropriate table and (if it's our usual many-to-many intermediate table), only select rows where registration entry ->isNull().


How should I go about placing the content of a field from a content type into a block? My case is this:
I have a content type called 'Test Type' with 2 fields: Body (text area), Slideshow (Unlimited list of images)
When I create an instance of Test Type and it renders, my goal would be to have the content of the Slideshow field go to a different region, let's say the header. First thought was to create a custom block that would hold a reference to the field content, but that does not seem to be an option. Is this possible to do through the UI with certain settings or would I be better off writing a module. The module Field as Block is pretty much exactly what I was looking for but it seems not work right now.

this can be possible by using views which is now in core in drupal 8

step 1 :: go to structure->views->add new views

step 2 :: Add new view ui will be opened

2.1.enter view name

2.2.under view settings select show content of type (the content type     whose field you would like to place in an block ex:your required content type)

3.only check the check box create a block under block settings

2.3.1.under BLOCK DISPLAY SETTINGS select the display format most likely
 (unformatted list) of fields

2.3.2 now save and edit and you are good to go...

step 3 :: now views ui is opened

3.1.on the top left hand side of the page under title

3.2. under fields select add (an pop up ui will open)

3.3. select type content ->select the field types of your content you want to display in your block ex-body and so on and so forth as required by you now apply and save..

3.4. configure field will now open configure as required..you can also rewrite the fields so better follow this link
rewrite fields

step 4 :: go to structure->blocks->place the block as per your required region->and find the block(it will be the same name as block name or view name unless changed)

4.1. place the block as per your wish there are many boundaries like selecting content type etc ...but for now select pages under visibility
leave the check box as default and inside pages type <front>
**remember to add less than and greater than sign as well

4.2.now save the block

step 5 :: in the block ui at the bottom also click save blocks and finally go back to the site

if all goes right you will see the content of a field from the content type in a block using views


Display custom form mode in twig with drupal_entity_form I am using the form_mode_manager module for creating new form modes.
I have currently a new edit form mode which is called applicant, but whenever I add the drupal_entity_form function in my twig template, it says:
The "node" entity type did not specify a "applicant" form class.
Does anyone know how to resolve this?

You need to create a custom module
Let say you call it module_name
In your module_name.module file you'll have to use the hook_entity_type_build()
/**
 * Implements hook_entity_type_build().
 */
function module_name_entity_type_build(array &$entity_types) {
  $entity_types['node']->setFormClass('applicant', 'Drupal\node\NodeForm');
}

Then enable your module_name module and flush the cache.


Is there a page listing all fields? I am wondering whether somebody has compiled a list of fields which are available for creating content types in Drupal. There are many lists of the most popular modules, but it would be great to have one focusing on existing fields, whether in core, or from third-party modules. I have looked around a bit, but always end up with lists of modules.

There is a page at admin/reports/fields that lists the field name (the machine name), the field type and which module it came from, along with all of the bundles (content types, in the case of nodes) that use that field.


How to resize  element within drupal block? I created a custom block with Full HTML format selected using the following code:

<img src="myimage.jpg" atl="myimage" width="xx" height="yy" />

However, Drupal seems to always display the image at it's actual size. Is there a way to achieve this in a block?

Is that everything that's in your block? I've tried to replicate this and it works fine for me.

Have you tried setting your CSS in the appropriate css file instead of adding it inline? Like:

#block-id-title img {
   height: 100px;
   width: 100px;
}

Or, try inspecting that img element in firebug or equivalent, and see how the css is being rendered. You might have a css styling set for all img tags which is unintentionally overriding your block image.


How do I replace a comma with a line break using feeds tamper? When trying to import a feed using Feeds and Feeds tamper, I want to insert a new line at the commas (for displaying address in a nice format).

The screenshot shows what I'm trying to achieve:

The result is \n appears in the output

Why is "\n" being inserted rather than a new line?

The problem is to do with single quoted strings and double quoted strings

'\n' !== "\n"

So when you enter \n in the settings it's getting passed to the preg function as a single quoted string and in php there's no safe way of changing the string from a single quoted to a double quoted string.

https://stackoverflow.com/questions/5241748/php-convert-single-quoted-string-to-double-quoted

Solved this using a plugin,

first make a custom module that adds a ctools feeds_tamper plugin directory

/**
 * @file my_feeds_tamper.module
 */
/**
 * Implements hook_ctools_plugin_directory().
 */
function my_feeds_tamper_ctools_plugin_directory($owner, $plugin) {
  if ($owner == 'feeds_tamper') {
    return 'plugins';
  }
}

Then within that module directory create the plugins directory and add the plugin code

/**
 * @file plugins/comma_to_newline.inc
 * replaces commas with comma linebreak on import
 */

/**
 * defines the ctools plugin
 */
$plugin = array(
  'form' => 'comma_to_newline_form',
  'callback' => 'comma_to_newline_callback',
  'name' => 'Comma to new line',
  'multi' => 'direct',
  'category' => 'Text',
);

/**
 * Even though there are no settings we still need the form
 */
function comma_to_newline_form($importer, $element_key, $settings) {
  $form = array();
  return $form;
}

/**
 * replaces a comma (followed by 0 or more spaces) with
 * a comma and a linebreak
 */
function comma_to_newline_callback($source, $item_key, $element_key, &$field, $settings) {
  $field = preg_replace("/, */", ",\n", $field);
}

I could have made a clone of the preg replace feeds tamper plugin, that replaces \n with "\n", for a more flexible (configurable solution)


Previewing another template online? Always when I want to check another template on my online site I have to download it to a local server, fix the blocks in that template, and set it as default. Only by that I could check it without changing the looks of the site online.

Let's say I want to preview this template online, without a local copy of the site, but also without switching the default template. Is this possible?

My final aim is to fix all the blocks in my new theme, and then preview it without setting it as default (So if visitors come in the same time they will see the site with the "old" template).

Thanks,

Yes, you can install the ThemeKey module. One of its features is to provide:

  content, user, or role -specific themes

So you can upload a new theme and try it out for certain users roles, without affecting what how the site looks for regular users.


How can I show help to a user one time only? How can I show help to a user one time only?

On my node form, I have some inline help under a few of the fields. I would either like the user to be able to close/hide the help or the help to be removed after a user has visited the page, so the user will not see the help again.

I have seen various modules for notification/messages which will only be displayed to an individual user once but this not suitable as I would like to have the help besides the field rather than the top of the page.

I have seen the qtip/tooltip modules also but as far as I'm aware these do not remember whether an individual user has closed the tip so next time the user visits the site the tips will be open again.

What would be the simplest way to display a tooltip/help message besides a field only once per each user. I know I can use php to check whether a user has seen the page or not, but unless I can some how use either the field help text or the tooltips with rules, I can only see this happening by writing a custom module. I was hoping that there was something which was similar to what I need already available though.

You need to track some where whether user visited a page or not. It should be database. Only module which does is statistics module. More over to integrate that with Field descriptions nothing but inline help you need to write custom code using a module. Since its very specific use case i can say that no contributed module available which can solve your use case out of the box.


template preprocess override not respected I'm using Drupal 7.

I have a template preprocess function overridden in my template.php as

It does not alter the output as desired.

When I comment out (or delete) the original preprocessor (template_preprocess_views_exposed_form(&$vars))
in the contrib module's theme.inc, the overridden preprocess function then takes effect as it should.

What do I have to do to get my preprocess to work without having to hack a contributed module?

Here is the offending code:

function ncmr_preprocess_views_exposed_form(&$vars){
  $form = $vars['form'];

  if ($form['ncmr_days_only']) {
    $form['ncmr_days_only']['value']['day']['#options'] = array(
      '' => 'Select Day',
      '5' => 'April 5',
      '6' => 'April 6',
      '7' => 'April 7',
    );

    $form['ncmr_days_only']['value']['day']['#printed'] = FALSE;
    $form['ncmr_days_only']['value']['month']['#value'] = 4;
    $form['ncmr_days_only']['value']['month']['#printed'] = FALSE;
    $form['ncmr_days_only']['value']['year']['#value'] = 2013;
    $form['ncmr_days_only']['value']['year']['#printed'] = FALSE;

    $vars['widgets_ncmr']['filter-field_session_date_value']->widget = drupal_render($form['ncmr_days_only']['value']);
  }
}

Try the following...

function THEME_preprocess_views_exposed_form(&$vars, $hook)
{
        if ($vars['form']['#id'] == 'FORM_ID')
        {
              // blah blah
        }
}

This way you shouldnt override the core stuff, thus not affecting your code either.


Views Rewrite Results Shows "Delete Comment" shows as text to anonymous users I'm using a views to show my comments.
I've  Rewrite Results and add a delete comment field.

When users login they can click on the link
and delete the comment

But when a user is logout
any user can see [delete_comment] token

How do I hide the [delete_comment]token from anonymous users please?

set the permissions for anonymous users that they can't see or delete the comment.


Drupal render form not rendering a form I have a cutom module which creates a page with a custom form.
the problem is that i don't print whole form at once like :

$form = drupal_get_form('custom_example_form', $adverts);
print render($form);

Rather my code is like:

$form = drupal_get_form('custom_example_form', $adverts);
print render($form['name']);
print render($form['descriere']);
print render($form['submit']);
print render($form['form_id']);
print render($form['form_build_id']);

The problem us that is second example drupal is not generating

<form id="" accept-charset="" method="" action="">

How do i generate  in second situation?

You should not print individual children elements of the form array, but render it completely (with render($form)).

If you want to fine tune the markup inside the <form> tag, you need to alter the form (using hook_form_FORM_ID_alter()) or provide a custom theme used for the form (i.e. in hook_theme() returns an items with the form ID as key).


menu_tree_output() not returning full menu array I'm building a function that takes a drupal rendered menu and removes the classes from it so that I can pass it to a jQuery function that'll build a menu from it.

The code i'm using for that is:-

<?php
     $tree = menu_tree_all_data("devel-frus");
     $menu = drupal_render(menu_tree_output($tree));
     $nocss = preg_replace('/class=".*?"/', '', $menu);
     echo($nocss);
?>

However menu_tree_output() seems to be only returning the first level of a six level menu when it should be returning the complete menu.

I've tried dsm()'ing $tree to see if all of the menu items are being returned by menu_tree_all_data() and that's fine, however when I dsm() the output of the menu_tree_output() function only the root and first level are returned in the array.

Am I doing something really obviously wrong here?

From what I understand about menu_tree_all_data() you need to supply it a link and depth to give it context (where in the menu tree am I at & how far do I go?). Also drupal_render() expects an argument passed by reference, so there will problems passing the output of function.

// Default to root link w/ a depth 5.
$link = menu_get_item();
$tree = menu_tree_all_data("devel-frus", $link, 5);
$tree_output = menu_tree_output($tree);

// Supply a variable for drupal_render to reference.
$menu = drupal_render($tree_output);

$nocss = preg_replace('/class=".*?"/', '', $menu);
echo($nocss);


How can we just apply the updates to a single module using composer without apply patches for other modules? We have the following composer.json file. When we want to update a module such as  Environment Indicator, we run the suggested composer command composer require drupal/environment_indicator:^3.7'.

In doing so it also applies the patches for core and other modules because the patches is defined in our composer.json file.

What we tried this as well but it had the same results.

composer update drupal/environment_indicator --with-dependencies

composer.json

{
    "name": "drupal/drupal",
    "description": "Drupal is an open source content management platform powering millions of websites and applications.",
    "type": "project",
    "license": "GPL-2.0-or-later",
    "require": {
        "composer/installers": "^1.0.24",
        "drupal/core" : "^8.6",
        "wikimedia/composer-merge-plugin": "^1.4"
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "config": {
        "preferred-install": "dist",
        "autoloader-suffix": "Drupal8"
    },
    "extra": {
        "_readme": [
            "By default Drupal loads the autoloader from ./vendor/autoload.php.",
            "To change the autoloader you can edit ./autoload.php.",
            "This file specifies the packages.drupal.org repository.",
            "You can read more about this composer repository at:",
            "https://www.drupal.org/node/2718229"
        ],
        "merge-plugin": {
            "include": [
                "core/composer.json"
            ],
            "recurse": true,
            "replace": false,
            "merge-extra": false
        },
        "installer-paths": {
            "core": ["type:drupal-core"],
            "modules/contrib/{$name}": ["type:drupal-module"],
            "profiles/contrib/{$name}": ["type:drupal-profile"],
            "themes/contrib/{$name}": ["type:drupal-theme"],
            "drush/contrib/{$name}": ["type:drupal-drush"],
            "modules/custom/{$name}": ["type:drupal-custom-module"],
            "themes/custom/{$name}": ["type:drupal-custom-theme"]
        },
        "enable-patching": true,
        "patches" : {
            "drupal/core": {
               "issuenumber1" : "path/to/patch.patch",
             },
            "drupal/eck": {
               "issuenumber2" : "path/to/patch.patch",
             },
        }
    },
}

Unfortunately, composer is always going to apply any patches you have defined that are not already applied whenever it runs. You can comment out the patches, run your composer command, and then uncomment them.


Apache Solr Search Integtation and the Default Drupal Search Form Apache Solr Search Integtation (apachesolr module) is dependent on the core Search module. I set this up at https://www.test.epcsite.com/search/content. I also setup display suite so that I can theme my search results.

I have a couple questions:

The Default Search form uses Drupal core search. If you go to https://www.test.epcsite.com/search it redirects to https://www.test.epcsite.com/search/content, I don't quite know why. I would like it to stay on "/search".
apachesolor setup a url at /search/site, which puts a tab on the search form. Clicking on the tab takes you to another search form, but it won't use Display Suite to theme the results. The tab itself is confusing and it would be nice to get rid of it.
Going to https://www.test.epcsite.com/search/content displays "Your search yielded no results" but I haven't run the search yet. How do I customize this message not to show? How do I customize the message so that it says what I want.

I'm assuming Drupal 7.

This is a limitation of the way core Search is implemented in D7. Try the Custom Search module; it can somehow change the way search paths are handled, although I have not used it.
One tab would be for core search, and the other for Apache Solr search. Go to /admin/config/search/settings and disable all search modules except Apache Solr, and also set it as default. Now the only available search path will be the one set up at /admin/config/search/apachesolr/search-pages.
I cannot replicate this on my Apache Solr & Drupal 7 setup. In general, to change strings that are hard coded into modules, use the String Overrides module.


Set default value for Enity Reference using View and Entity Reference View Widget Checkbox Basically i have a field (in line item(commerce custom product)) with Field type: Entity Reference and Widget:View. The view is a list of terms and has an aditional field type:Entity Reference View Widget Checkbox to provide a checkbox in so user could configure the product.

The whole chain works fine from user point of view but there is no option to set the default value (in UI) and the option to set the default value from hook_form_alter() is not giving the needed result.

This is hook_form_alter:

function test_form_commerce_cart_add_to_cart_form_3_alter(&$form, &$form_state, $form_id){

    $form['line_item_fields']['field_pesonal_data']['und'][0]['field_cover']['#default_value']=6;

}

Please provide a solution. Thx!

Did you try casting the value to a string?  I had to do that when I was setting default values for a user reference field type.  It wouldn't work otherwise. Something like

 $form['line_item_fields']['field_pesonal_data']['und'][0]['field_cover']['#default_value']=(string)6;

Also, I noticed that you had a spelling error.  You had 'field_pesonal_data' It should probably be 'field_personal_data'

Also, I was a little confused by your use of terminology.  You described that the user is configuring the entity reference field on the product.  Did you mean configuring the entity on the line item?  I just wanted to clarify, because if you are modifying the form that governs the adding of products (or product variations in Commerce Kickstart 2.0), you need to use a different form alter call because the product variation creation form uses the inline_entity_form module to manage the specific product variations.

That call is:

function hook_inline_entity_form_entity_form_alter(&$entity_form, &$form_state)

Look at the inline_entity_form.api in the contrib/inline_entity_form folder in Commerce Kickstart 2.0

for modifying a user reference on a product, I did the following:

function bh_vendor_inline_entity_form_entity_form_alter(&$entity_form, &$form_state) {
  global $user;
  if ($entity_form['#entity_type'] == 'commerce_product') {
    $entity_form['vendor_user_reference']['und']['#default_value'] = (string)$user->uid;
  }
}

My widget I used was a option list.
You have to have the ['und'] or it won't work either.


How to show users who have not flagged a node with any flag? Drupal 7. I have a content type that can be flagged with 3 different flags. I need to display a view of users who have not flagged any of them.

The users that are allowed to flag are listed in an entity reference field on the node. My view is a content view that has the relationship to the entity reference list to get the users, then I have a relationship to Flags: User's flaggings for each of the different flags. There is also a Contextual Filter for the current node.

When I add a filter for Flags: Flagged (False) related by the User's Flagging, it seems to check if the user has flagged any content with that flag, not just the current node.

Looking at the flagging table, it seems like I need to do some kind of combined column check. I need to know if the uid has any entries in the table with the same entity_id (node id in this case).

Will I have to alter the query in code? Any hints on that would be great too. Otherwise, if it can be done in the UI, that would be nice.

It's always tricky when trying to display "things that aren't" because Views rely on things that are, even when querying out empty fields.

I haven't tried to recreate your example, but here are some comments that might help start you up:

Do it for one flag first

Once you have a working example related to only one flag it's easy to repeat the steps adding conditions for other flags. This is difficult enough to figure out for one flag alone.

List NOT flagged

To display content that isn't flagged, you must untick the option Include only flagged content in the Flags: flagname Relationship, and then use the Filter Flags: Flagged set to Not flagged:

How to list content that is not flagged.

Users who aren't here please identify yourselves!

It's impossible to list users who "aren't". You can only list all of them and then filter out the ones who "are".

If you start with Content Views, you can list content that hasn't been flagged, and you can show which users flagged it, but you can't list which users haven't flagged it, because there is no relationship between nodes and users who haven't flagged it!

A better option might be to go with User View. You can add Relationhip to the relevant flag, don't limit only to users who flagged, and adjust to Any user. Add Contextual filter Flags: Entity ID and set the default value to Content ID from URL, but don't forget to Exlude under More. Add a Filter Flags:Flagged and set to Not Flagged, but this way you only get users that haven't done any flags on any nodes.

You need some additional module to combine and help with showing things that aren't. With Content Views you can't list usernames of people who haven't flagged, while with User views you can only show people who haven't used the flag at all, you can't show a user who hasn't flagged a node if that user flagged another node with that same flag.

Views Reference Filter module

This module has a cryptic explanation on its project page, but could be useful in your case to pass one views results to the main views display to combine the results so you get something meaningful.

Views Reference filter module can be used to filter a View with the results of another (Entity Reference) Views Display. It can pass arguments to the embedded view:

You can probably create one View listing all Users who are allowed to flag Content, create another view that shows the users that have flagged it, then filter the first view with the negative second one. Just remember that the Field type of the Views Reference Filter must match the type of ER Views Display type (uid-user).

Introduce Flags Relationship

You need to add a Relationship that contains information about the node flag status. I doubt you can do that with User's flaggings without another Relationship before it that connects to the user who flagged, which is a roundabout way.

Just use the Flags: flagname, don't limit to Include only flagged content, and do set it to Any user.

Later you can add more Relationships to display users names etc, first you need to focus on making the filtering work.


Adding javascript to a view? I have a view in Drupal 7 that displays a list of all the nodes of a content type in alphabetical order. What would be the best way to implement javascript that only displays nodes starting with a specific letter, say, all nodes starting with the letter 'A'? I would also like to add a list of letters as links at the top to trigger the show/hide effects.

It's probably worth noting that I currently have javascript to achieve this using data gathered from an external database and implemented via a custom module. Ideally, I want the same functionality but want all the data to be coming from Drupal nodes.

Why do you need a javascript way explicitly? Drupal can do these Filters and make the glossary view, an index by letters, at top for you already in the views administration area.


Adding a line item to an order from a module I'm trying to create a gift wrapping module for Drupal commerce. I have created the checkout pane that has a select box for the user to choose if they want their order gift wrapped (and a field to select the giftwrap price on the configuration form). I've also created a giftwrap line item type. In the pane's base_checkout_form_submit() function I would like to create a giftwrap line item that is added to the order alongside the products. This is what I've got so far:

/**
 * Implements base_checkout_form_submit()
 */
function commerce_giftwrap_pane_checkout_form_submit($form, &$form_state, $checkout_pane, $order) {

  $default_currency_code = commerce_default_currency();
  if ($balance = commerce_payment_order_balance($order)) {
    $default_currency_code = $balance['currency_code'];
  }

  // Create the new line item.
  $line_item = commerce_line_item_new('giftwrap', $order->order_id);

  $line_item->line_item_label = 'Gift Wrapping';
  $line_item->quantity = 1;
  $line_item->commerce_unit_price['amount'] = variable_get('commerce_giftwrap_price', '2.00');
  $line_item->commerce_unit_price['currency_code'] = $default_currency_code;

  commerce_line_item_save($line_item);
}

I haven't wrapped it in an if statement yet, I wanted to get it working first. This code is creating a line item in the database however it isn't adding the line item to shopping cart contents view on the checkout review page. I've altered the shopping cart view to include product line items and my newly created giftwrap line items.

Any help on this would be greatly appreciated.

You need to add the line item to the order itself. You can do this pretty easily with the entity wrapper:

$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$order_wrapper->commerce_line_items[] = $line_item;
$order_wrapper->save();


Form Block module usage in multiple sections While working a project i came across an issue with "Form Block" module. I used this block on a basic page in content section. Now my client also wants this same block in the right sidebar on the home page. Is there a way out to get the desired result.

You could use the context module to achieve this. With this module you can show the same block in different regions on different pages. You can add a condition (like path is "/frontpage") and a reaction like show block xy in region xy.


Setting managed file default value from ajax request I'm trying to create a form using the Form API with the following behavior:

For a custom slider module, users can choose to upload an image which is saved as a managed file. This works fine.
They also have the option to populate the slide content (slide title,link and image) from an existing node of a custom type. The node is selected from an auto-populated select field which on change calls an ajax function to auto-populate the title and subtitle fields. If the selected node has an image attached to it, a checkbox is displayed allowing the user to use the already uploaded image associated with node as the slider image as well.
The problem I have is that I can't get the manged_file field to accept the nodes file id (fid) and re-render as managed_file with a default_value before returning it from the callback.

Here's my callback:

function load_image_callback($form,&$form_state) {
    // Load node from the selected value
    $node = node_load($form_state['values']['slide_nid'];

    // Set the managed_file default value to the nodes main image file
    $form_state['complete form']['slide']['slide_image']['slide_fid']['#default_value'] = $node->field_main_image[$node->language][0]['fid'];

    // Return the updated slide image wrapper to replace the existing one
    return $form_state['complete form']['slide']['slide_image'];
}

So after digging through Drupal core code I arrived at this solution:

In my ajax callback I load the actual file, set some managed file settings in the managed_file array, and then physically call the file_managed_file_process() function to setup the managed file display field array elements.

function load_image_callback($form,&$form_state) {
    // Load node from the selected value
    $node = node_load($form_state['values']['slide_nid'];
    $file = file_load($node->field_main_image[$node->language][0]['fid']);

    // Set the managed_file default value to the nodes main image file
    $form_state['complete form']['slide']['slide_image']['slide_fid']['#value'] = array('fid' => $file->fid);
    $form_state['complete form']['slide']['slide_image']['slide_fid']['#file'] = $file;

    // Process the managed file field with the set element
    $form_state['complete form']['slide']['slide_image']['slide_fid'] = file_managed_file_process($form_state['complete form']['slide']['slide_image']['slide_fid'], $form_state, $form);

    // Return the updated slide image wrapper to replace the existing one
    return $form_state['complete form']['slide']['slide_image'];
}


How to remove block in colorbox? I'm currently doing recruitment system by using drupal 7..
I want to reduce the user redirect activity, so i've installed the colorbox module and colorbox node module..
I have job vacancy list (in views) which i link the job vacancy (content:title) to the node.
The colorbox work perfect which it can display all the job details..

My problem is the colobox also include all the "block" in my website..

My question is how i want to make the colorbox show only the job details?

Thank you in advance..

Is the block appearing as part of the view, or just in the Colorbox? If it's just showing in the colorbox, and you go into Structure > Blocks, you should see that "HR Admin" block listed - you can set it to show only on the pages where you want it to appear. You can read about the visibility settings in the Block documentation. If it is appearing in your view, you may have to give more details for troubleshooting.

This answer may help: How to disable a block on a certain view?


Remove label Search terms from Views exposed form On this site in the sidebar i have a views_exposed_form to search. I need this search functionality to show my search results for restricted pages.

How do i remove the label 'Search Terms'. Is it possible within
template.php with a hook?
How do i add a placeholder to the input field?

function views_exposed_form($form, &$form_state) {

if ($info = $handler->exposed_info()) {
          $form['#info']["$type-$id"] = $info;
          /**enter your code here  *****/

        }
/**for place holer**/

if (isset($form['title'])) {
        $form['title'][] = array('#placeholder' => t('Gemeente...'));
}

}


Removing duplicate content caused by node/nid/talk pages Recently I installed the talk module, didn't like it and uninstalled it.  After removing it I have noticed that I have duplicate content listed under both the node ID and the node id followed by talk.

For instance:  The page www.mysite.com/about-us is duplicated at the address www.mysite.com/node/4/talk as are all my pages.

In the talk.module file (which has been removed along with the entire talk module) I notice the line:

  $items['node/%node/talk'] = array(

To me this looks like the line of code that created these talk pages, however being that I have removed the entire module, flushed caches etc. I do not understand how these pages still exist.  Any help would really be appreciated as I have been working on this now for several days with no answer.  Thanks in advance.

So /node/4 is your about page isn't it? you just added a url alias. Which means you can access the same page with /node/4 or with /about-us

To quote Clive from Non-existent URLs in Views 3 in drupal 7

  That's the expected behaviour - Drupal automatically routes you to the
  'parent' if it can't find the 'child' part of the URL

when I go to mywebsite.com/node/1/talk it displays the /node/1 content to me; even though, the url in the web browser says mywebsite.com/node/1/talk, and I haven't even installed the talk module at all.

Try going to mywebsite.com/node/4/ijustmadethisup and you'll see you get displayed /node/4

Therefore, this is just the default Drupal behaviour, nothing to do with the talk module.


How to programmatically build a page and a form in the same page What I'd like to do is build a page with two things:

On one half of the page, custom markup with data from Drupal.
On the other half, a custom form also submitted to Drupal.

There are a lot of tutorials on how to programmatically build pages in D8 (create route, extend controller, return render array, etc.). There are also a lot of tutorials on how to programmatically build forms on D8 (create route, extend form base, return render array, etc.). However, I could not find any resource on how to build both onto the same page.

How would I go about doing this?

You must use the formBuilder, like this:

$render = [];
$render['elememt1'] = [
  '#type' => 'markup',
  '#markup' => t('Test'),
];
$render['element2'] = \Drupal::formBuilder()->getForm('Drupal\MY_MODULE\Form\MyFormClass');// The destination of your form.

return $render;


How to prevent a node being saved when using the Rules module? Is it possible to prevent a node from being saved with Rules? This is what I do now:

Create a rule Before saving content of type ''.

Condition: IF ...

TRUE => Redirect & set message

Create a rule After saving content of type ''.

Calculate & set value

So when a condition is true before saving I want to redirect the user, show a message and DON'T save node.

When it's not true I want to save the node and do the actions in the after saving content of type rule.

The problem is that when the condition is true in the first rule, the redirect and set message is performed. But directly afterwards the node is saved and the actions in the other rule are executed.

How can I make sure that the second rule doesn't get executed? Can I do this without custom code?

I would try to use the Conditional Rules module for this. Some more details about this module (from its project page):

  ... provides Rules plugins for conditionally altering execution flow directly inside a group of actions.

So create a rule in which you add these actions:

Conditional (which you add via the 'Add conditional' link at the bottom)
If Condition (which you add via the 'Add If' link to the right of the 'Conditional' action, and 'Condition' is what you mentioned in your first rule already).
Redirect & set message (which you add via the 'Add Action' link to the right of the 'If' action, and 'Redirect & set message' is what you mentioned in your first rule already).
Else (which you add via the 'Add Else' link to the right of the 'Conditional' action.
Calculate & set value (which you add via the 'Add Action' link to the right of the 'Else' action, and 'Calculate & set value' is what you mentioned in your second rule already).

Here is a screenprint of a rule with an action that uses Conditional Rules (though only with an "if"-part here, no "else"):


moving from test site to live I currently have a test Drupal site where I am testing the different modules and Views, display settings, etc that I would like to eventually use on my live site. But I am adding data to the test site as well, data that will also end up on the live site.

Because I am installing and uninstalling modules, would it be better to start the live site from scratch or can I safely move the test site to the live site without worrying about orphan code/settings slowing down or otherwise adversely affecting the live site?

One of the most common ways to move configuration data is to use the Features module.  However, this will move only configuration, not data (nodes/content).  Still, it's not too difficult to set up; you can take a look at this tutorial for an overview.

Moving data is much harder; the Migrate and Feeds modules are two common ways to do this but both are quite painful to set up and probably not worth the trouble.  For content, I just keep a list of the info in an Excel file and then cut and paste it in-- it's not a great solution, but in my case it saves a lot of time.


Add Option to Centre Images on Content Pages Currently, to align images only Right & Left options are available as shown in below image:

How to Enable full-width images similar to the link which is displaying images: https://medium.com/perspectives-from-the-economist-intelligence-unit/lake-chads-twofold-crisis-27545789e9d7

With CK Editor Module. Install CK EDITOR Image module, which enables the third alignment option to center the image also.

Here is the link to download the Module. https://www.drupal.org/project/ckeditor_image

Note: CK EditorImage only supports for Drupal 7 and its previous versions.


Image slider in content type based on selected images from another node (same content type) As a novice in Drupal php & hooks, I have a question about content type.
It is all about Drupal 7 with all up-to-date modules installed.

I have a content type for hotels (about 400 hotels). This content type has lots of fields. One of field is for image (unlimited values).  I have user request for image slider in this content type based on images from another node (same content type). Some kind of “We also recommend..:”

My approach was with Advanced Link module where user can enter link to node and this link is then show as field in view (I have view to catch this). Programmatically, I’m then able to take nid from that link and extract image I want from node. But now I’m stuck with putting this image dynamically  into this view. Is this approach good anyway?

In the beginning I was thinking about to add textarea field to content type and give a user ability to insert image from server (image that is already uploaded) with ckeditor uploader.  Only problem with this approach is that all images names from hotel node are in special format (TH-023.jpg…), so they would be in big trouble to find image.

My second thought was to write a module to push image into some kind of field inside content type, immediately after user get link from advanced link field (in edit state of content type node). Is this possible?

Anyway, what would be the best way to do this?

Thanks in advance.

I presume that the "We also Recommend" is manually entered by the user and that you are not using any specific logic to do it.

If that is the case then your approach would be to add an entity reference field in the content type and reference the nodes you want from there.

Once you have that setup you can create a view to get the images from the nodes related the current view using relationship.

If you don't want to add the recommendations manually the you can use taxonomy to categories the contents and then display the images from the nodes tagged with the came taxonomy term.


Need to force #default_value for AJAX tableselect checkboxes I built a drop-down ajax pager that replaces a tableselect with the requested page of rows. The array of selected item IDs is stored in a hidden field and that logic is working across entity load/save and AJAX replacements.

When the form initially loads, my tableselect #default_value operates correctly and checks the selected rows on the first page. But after AJAX paging through the big list to a different page and back, the checkboxes aren't checked again.

I think this has to do with #default_value only working before the form has been submitted. How can I reset the state so that my updated tableselect #default_value is used after AJAX?

Just before the tableselect's array in the form builder function, put the following code:

unset($form_state['input']['my_tableselect']);


Skip words/vary word order in search for autocomplete suggestions I'm using an Entity Reference field which searches taxonomy terms of type Person to suggest options for  autocompletion.

Let's say, i have the following terms (Persons):
 - Jason Jay Smith
-  John Jacob Andrews... etc.

When I input "Jason Ja..." in the field, the autocompletion works fine and suggests me the Smith guy.
But if i input "Jason Smi...", the term won't be found because the word Jay is skipped.
How can i fix this?

Or generally, how can i implement a better autocomplete search? My terms are composed of a number of words and searching by just one word or a fixed word order is definitely not enough

Doing this would require a different selection handler. Look at class Drupal\Core\Entity\Plugin\EntityReferenceSelection to see how the default selection handler works. In particular you need to create a different buildEntityQuery method. I don't know of any module that provides a handler to do this, and I'm not sure how I would go about accomplishing it myself. Sorry I can't give a more satisfactory answer.


Using hook_form_alter() to prevent free email addresses from registering on a Drupal 6 site I have been tasked with blocking specific email address domians from registering at our Drupal 6 site (gmail.com, aol.com & yahoo.com). I implemented some JQuery code to do this but the problem was that spammers with javascript disabled in their browser readily bypassed this prevention.

I also cannot use Drupal 6's Access Rules as we already have registered users on the site with those domains so this method blocks them from logging in so it's more of a going forward prevention that we would like to implement.

I found this code on Stack Overflow but the code was somewhat incomplete:

function example_data_form_user_register_alter(&$form,&$form_state) {
  $form['mail']['#element_validate'] = 'example_mail_validate';
}

function example_mail_validate($element, &$form_state) {
   if ( -- Whatever condition you like -- ) {
     form_error($element, t('Free email is not allowed.'));
   }
}

I thought it would be better to open a new question on this forum since it's Drupal specific.

I think what I need help with is filling in the gap where in the code it says: -- Whatever condition you like --

I am not a PHP guru so any help would be appreciated. I assume this is the spot where I would have some code that disallows the domains that I want to block.

A very simple example would be:

function example_mail_form_user_register_alter(&$form,&$form_state) {
  $form['mail']['#element_validate'] = array('example_mail_validate');
}

function example_mail_validate($element, &$form_state) {
   //block gmail addresses
   if (stripos($form_state['values']['mail'], 'gmail.com') > 0) {
     form_set_error('mail', t('Free email is not allowed.'));
   }
}

However you should lookout for more advanced solutions:

Simple email verification: email verify
http:BL

  http:BL can prevent email address harvesters and comment spammers from
  visiting your site by using a centralized DNS blacklist.
  Mollom which also prevent spam on all your content/comments forms.


Is it possible to get a clean url to be used in Views comment counts? I have a Views view of some news nodes.
Each of the news nodes has "Generate automatic URL alias" ticked in the "URL path settings" of the node. This is great and gives me nice clean URL's.

However in my comments field in the view when I go to "REWRITE RESULTS" "Output this field as a link" and set the "Link Path" I am unable to find a token that gives me the same clean url that my title field can have or even my Node: Link field.

Is it possible to use the clean urls for comments and if so what is the token?

I'm not sure this can be done through rewriting, it's quite limited and never has given me what I want. At any rate you could be better off if you used the row-theming technique, which is in turn powerful. Then you could build your own links the way you want, wrapping the URLs in drupal_get_path_alias to get nice-looking addresses.


How do customize settings.php during installation profile I'm creating an installation profile for my current company internal project.

During the installation process, one of the custom modules crashes during init(), since it tries to use one global variable defined on settings.php (that's current default behavior of the module)

Using system_form_install_settings_form_alter() I changed the settings form, by adding one input textfield for user's input, and on submit the value is appended to settings.php, but settings.php is rewrited before profile installation starts.

There is any way to prevent cleanup of settings.php by the installation process?

You may find it easier to use a settings.common.php

Often during team projects, we have local settings.php with db credentials etc.. and a settings.common.php with settings common to the install and deployment environments.

You can add settings.common.php with an include / require line in settings.php

require 'settings.common.php'; // same directory, e.g sites/default/settings.common.php

and then write to it as needed during install.


How to add CSS classes to buttons of Drupal Commerce checkout forms? How can I add a bootstrap btn-success class to the Drupal Commerce Checkout button in the cart form?

The Update cart button already has btn-info but I can't find btn-info anywhere in the code.

If would also like to adapt buttons in other parts as I expect btn-success buttons to lead to higher conversion.

Bootstrap has great classes, I don't want to fiddle with CSS to try and recreate that, I just want to use the Bootstrap classes.

I'm okay with adding some PHP code to my theme's template.php, probably _form_alter() and this is probably the way to do it. But how exactly?

According that you have default views_form_commerce_cart_form_default form for your cart, this should do the job. Put the following lines in a custom module:

function MYMODULE_form_views_form_commerce_cart_form_default_alter(&$form, &$form_state, $form_id) {
  $form['actions']['checkout']['#attributes']['class'] = array('btn-success');
}

If not ok, check the ID of your form with

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  drupal_set_message("Form ID is : " . $form_id);
}

and apply the same above snippet with function MYMODULE_form_FORM_ID_alter.

EDIT : to apply btn-success to Continue buttons of the cart, checkout, review pages:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {

  switch ($form_id) {

    case 'views_form_commerce_cart_form_default':
      $form['actions']['checkout']['#attributes']['class'] = array('btn-success');
      break;

    case 'commerce_checkout_form_checkout':
    case 'commerce_checkout_form_review':
      $form['buttons']['continue']['#attributes']['class'] = array('btn-success');
      break;
  }
}

To do it yourself next time : in your hook form alter() module, check the form_id, dsm($form); and browse the dsm tree to find your needle...


Allow user to edit commerce line item at checkout I have a line item type with a custom amount field that allows the user to specify the amount they pay for the product in the add to cart form.

I also want to be able to allow the user to update the amount at any stage up until they have paid.

How can I make it so that users can edit this line item on the checkout page?

Ideally I would like to just have the equivalent of the add to cart form with my editable amount field output on the checkout page but I'll settle for any way to edit the line item on the checkout form.

I would like to keep custom code to a minimum but am willing to do whatever it takes if my only option is to go very custom.

If it matters to the solution, orders that contain this line item will only ever contain the one product, with quantity 1 and the variable price.

These orders use Commerce NoCart and Commerce Checkout Multilane to skip the regular cart step.

[EDIT]

An idea I just had was to create a custom checkout pane with my form on it and a submit function that updates the line other on the order. Does anyone see any reason why that wouldn't work?

Or does anyone know if something similar already exists that I could modify/extend faster than writing something new?

Yep it seems my proposed solution should do the trick.

I somehow didn't previously see the Commerce Cart Form Checkout Pane module, which does pretty much exactly what I was asking for.

I also used the Commerce Line Item Cart Form module to add line item fields to the form.

[EDIT]
Turns out that those two modules I mentioned don't seem to play nice together so I'm just going to create a custom checkout pane with a custom form that updates the line item in it's submit function.


Filter Taxonomy reference field on Workbench Access permission i need some help with Workbench access based on taxonomy.

This is my use case:
I have this taxonomy structure for my site:
 - Term A
 - Term B
 - Term C

And i have 2 roles:
 - editor
 - editor C

Editor c users must be able to create or update only the term C nodes.

I installed Workbench, Workbench Access and Field Property to control this behavior.
I configured Workbench Access on Taxonomy.
In admin/config/workbench/access/roles i put Roles “Editor C” only in “Term C” Section.

I created in each content type a Taxonomy Reference field, based on Workbench Access (i checked “Workbench Access control field”).
So this fields has two purposes:
 - tagging the node on my taxonomy structure
 - Assign the proper editorial group

The problem:
When an Editor C user adds a content, he can select any term value, not only “Term C”.
In other words the  Taxonomy Reference field display all result.

How can i filter/limit the record of taxonomy reference on workbench access permission?

P.S.
If i check “Require a Workbench Access form element” in admin/config/workbench/access/settings the module add a “core” access control field in each content type.
This fields are filtered on Workbench access permission but i loose my first purpose (tagging the node on my taxonomy structure).

Can anyone help me?
Thanks in advance,
Matteo

You must install Taxonomy Access Control module. Follow this steps:

1) Enable the module.

2) Go to admin/config/people/taxonomy_access

3) Click configure link for role "editor"

4) Click "Add vocabulary" link. Then select the vocabulary where you have terms "Term A", "Term B" and "Term C" and press "Add" button.

5) Click "Add term" link. Select "Term A". Configure permissions for this role and term (you should select "Allow" in every case). Once done press "Add" button.

6) Do the same for Term B

7) Do the same for Term C, but this time select "Deny" in every case.

8) Press button "Save all"

9) Go to previous window and do the same but this time for role "editor c". However you have to do the opposite: Terms A and B should have "Deny" in every case and Term B should have "Allow" in every case.

I hope this helps you! If it doesn't, you should checkout the Organic Groups module too. In case you need Organic Groups notice you also have OG Vocabulary module.


Create a new revision automatically on edit When a node is edited I want to always create a new revision. I do not want people to be able to turn this off. How can I do this?

To enabled automatic revision creation go to the content type page (admin/content/node-type) and select edit for whatever content type you wish to have revision created automatically.

Under the workflow fieldset there's going to be an option "Create new revision" make sure you check that box and save your content type settings.

Now under your permissions (admin/user/permissions) be sure to not to give your users the "administer nodes" permission. This will prevent them from overwriting that option.


Enable storing of taxonomy term name instead of ID in views filter criteria Background
I use Features module to deploy the code to my stagging. For e.g. I have a feature which exports:

content type - Player
Taxonomy term on this content type of vocab - Medals
View which lists the Player with filter type: Content: Has taxonomy term (=gold)

Medals has three terms - gold, silver, and bronze.
In the feature the vocabulary is being exported while the terms are not. I need to add the terms manually again on the server.

Problem
The feature exports the term id of the term instead of the name (tid : 1). So, when I enable the feature on the stagging server, and if the term name for tid : 1 is silver. The views filter criteria is changed and it is conflicting with the use case.
I was just wondering if there is a way to export the views taxonomy filter name instead of id?

I couldn't find a solution for filtering via term name. However, I came up with a workaround where I was able to featurize the taxonomy terms too.
I'm using UUID Features Integration for the same:

  The UUID Features Integration module provides a mechanism for exporting content (nodes, taxonomy, fields) into a features module. What's that you say? You thought features was only for configuration? This module is meant to be used in the cases where certain pieces of content straddle the line between pure content and configuration.


No schema for my_module.global error on unit test I got an existing Drupal 8.2.x project with existing unit tests. When I run a sample unit test, I get the error (real module name redacted):

No schema for my_module.global

This doesn't seem to be related to the my_module.schema.yml file, or any DB schema that I can tell. Drilling down, I got this output for the $definition variable in \Drupal\Core\Config\TypedConfigManager.php, which the unit test calls up (among others):

array (
  'label' => 'Undefined',
  'class' => 'Drupal\\Core\\Config\\Schema\\Undefined',
  'definition_class' => '\\Drupal\\Core\\TypedData\\DataDefinition',
  'type' => 'undefined',
)

For core modules the class is Drupal\\Core\\Config\\Schema\\Mapping. Note that the error complains about a schema for my_module.global, which is one of the YAML config files for this module (can't tell how else it's related).

The question is, what does this schema mean exactly, and where do I set it for my module?

Turns out that it is related to the my_module.schema.yml. Looks like every YAML file under my_module/config/install must have a corresponding schema in the my_module.schema.yml file in order to set up a unit test, even if this is not actually required for the module to work. It needs to look something like this (assuming the config/install file name is my_module.global.yml):

my_module.global:
  type: mapping
  label: 'My label'
  mapping:
    property:
      type: text
      label: 'Property label'

If unsure which properties need to go there, running the unit test without them will give a list as part of the error. I'm sure there is a better way to find this, but that's the way I found so far.

Edit – the whole schema verification mechanism can be turned off: In drupal/core/lib/Drupal/Core/Test/TestSetupTrait.php, $strictConfigSchema needs to be set to FALSE.


Simple confirmation popup dialog box How is it possible to create simple confirmation popup dialog boxes in Drupal 7?

I've searched a lot, but I found tons of non-working suggestions and code.

I got it!!!

Here's a simple 100% functioning exmple:

$form['delete'] = array(
    '#type' => 'submit',
    '#value' => t('Delete'),
    '#attributes' => array('onclick' => 'if(!confirm("Really Delete?")){return false;}'),
);

I hope this helps.

Happy coding :)


Passing product info to PayPal using Comment1 and Comment2 We need to pass information to PayPal using their Comment1 and Comment2 fields for accounting purposes.  We have several units using the cart for different fees and our finance team needs to be able to see and sort by the units in question on the PayPal Manager website.  The Comment1 and Comment2 fields seem to be the ideal place to pass this information to PayPal, but we can't figure out how to populate and pass these fields to them in the module code.

How would you recommend accomplishing this?

I've been researching this very issue myself. I spoke with PayPal and they told me the following.

First, they recommend you use the PayFlow Pro Module.

Second, to add $comment1 and $comment2 variables to your code you need to:

Create the form fields for COMMENT1 and COMMENT2 to add to the Return Array at lines 293 (of commerce_payflow.module):

‘comment1’ => $_POST[‘your_form_field_here’],
‘comment2’ => $_POST[‘your_form_field_here’],

Note: You may need to build the form fields in the function starting at line 336.

This is really a half-solution, because:

Now, I'm still trying to parse out exactly how to do this myself but I'm pretty sure it involves a custom module that uses a hook to alter a function in that module (possibly commerce_payflow_link_settings_form or commerce_payflow_link_default_settings).


How to add a 3rd party library and call it using Libraries I've installed the Libraries module. How can I add a 3rd party PHP library in my Drupal 7 project. How do I use hook_libraries_info()?

The Libraries project page has good documentation on how to use version 2.x API. Essentially, there are 2 components to it.

You're defining an implementation of hook_libraries_info(), that returns an array that defines the library's machine name, resources to load, & a means to validate the library version (either an version arguments element that defines the array passed to libraries_get_version() or a custom version callback function).

/**
 * Implements hook_libraries_info().
 *
 */
function MYMODULE_libraries_info() {

  // Define 'simple' as the machine name of library
  // which will be stored in sites/all/libraries/simple
  $libraries['simple'] = array(

    // This gets passed to the $options array in libraries_get_version()
    'version arguments' => array(
      'file' => 'simple.js',
      'pattern' => '/Version (\d+)/',
      'lines' => 5,
    ),

    // Alternatively, MYMODULE_version_callback could be defined.
    // this function returns TRUE/FALSE if it finds a valid version of the library
    //'version callback' => 'MYMODULE_version_callback',

    // Defines the PHP,JS,CSS files to load for the library
    'files' => array(
      'js' => array('simple.js'), //this can be a path to the file location like array('lib/simple.js')
    ),
  );

  return $libraries;
}

The 2nd component is to load the library using libraries_load() wherever you need in your module.

//Load the 'simple' library
libraries_load('simple');

See the linked documentation for more information.


Views - Filter Dates/Years I'm stuck on a necessary component for a website I'm working on.

I've got a content type called "Photograph" which has a variety of fields including one for "Date", which includes a variety of entries including just the year, or the year and month, or the full date.

My problem is that I cannot select a date earlier than 2013, which is a problem because some of these photographs date from 1848 on up. That leaves me with the option of a calendar selection, or by entering the date itself, which doesn't work for ease to visitors. So I'd like to use the selection option (with a focus mainly on years), but how do I edit the select options to include the years that I need included?

By default, the Date field's Views integration sets a +/- 3 year range for date filters. If you want to expand this beyond this range, set the Starting year & Ending year settings to Other.

This option will let you enter an arbitrary year from which your select box will start and end.


Where is the entity ID stored? I have an installation which I am trying to upgrade from Drupal 6 without much success. I have decided to manually port the database over.

I realized that in a fresh installation of Drupal 7, node has entity ID = 1 whereas in another installation, node has entity ID = 2.

Where is the table storing this data located?

Check for hook_entity_info and entity_extract_ids. The former specified a base table and the id key, the latter allows to extract the ID from the entity.


jQuery Mobile in a custom theme I have built a Drupal 7 website that contains a mobile theme. What I want to do is run the newest version of Jquery Mobile - http://jquerymobile.com/ which requires Jquery 1.7.1. Drupal by default is using an older version of Jquery.

I want Jquery Mobile to load "last" and be used for all screen elements (it changes the way form elements, the way the page is scrolled etc). I've already excluded a bunch of the default Drupal js and css (that won't be needed in the mobile theme) and if I stick this in the html.tpl.php of my test theme.

<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.1.1/jquery.mobile-1.1.1.min.js"></script>

It works exactly the way I want it to, but this does not seem like a good Drupal friendly implementation. What is a better implementation of this that will work better with Drupal and reduce risk of conflicts?

I've tried Jquery update http://drupal.org/project/jquery_update/, and jQuery Multi modules http://drupal.org/project/jqmulti, but without modifications the theme won't load (it loads perfectly if I use those 2 lines above).

Also please do not point me to http://drupal.org/project/jquerymobile or to this
http://drupal.org/project/mobile_jquery

I have a site using that module and theme and I do not want / desire/ require, the extra functions thqat module works with (plus it uses an old version of jquery mobile) and the theme has lots of issues which make it not work for my purpose.

The issue with updating jQuery manually in Drupal is that the potential arises for parts of Drupal core (and contrib modules) to break because of the change in jQuery version. The main benefit of the jQuery Update module is that it corrects the things that break in Drupal core when jQuery is updated.

Thus, your best option is to utilize the 7.x-2.x-dev version of jQuery Update, which includes rudimentary support for jQuery 1.7.x. Keep an eye on the issue queue related to this version so that you can report and/or investigate any issues that may arise in utilizing jQuery 1.7.x in Drupal 7.


How do I use a views data with a paragraph? I have a content type with dynamic content block section. Each block section is managed by paragraph bundle.

Let's explain using an example to make more clear-

Content type name is Employee.
A paragraph field is added in the employee content type. Field machine name is field_body_contents
All paragraph bundle is showing in dropdown and admin can select the paragraph bundle to add content with the employee.
We have created the template for each paragraph bundle and these are rendering perfectly on the template file.

Now there is a new case that we need to embed the views data with the field_body_contents dropdown so that admin can section views from the dropdown to inject views data between paragraph bundle.

The way I've done this is to preprocess the paragraph and alter the $variables['content'] to contain the views data/render array you've retrieved programatically:

function HOOK_preprocess_paragraph(&$variables) {
  if ($variables['paragraph']->type->target_id == 'yourparagraph') {
     //code to get the view you want
     ...
     ...
     $variables['content']['view_content'] = $theviewdata;

  }
}


How to I add a node reference field using the Webform module? Is it possible to add a node reference field using the Webform module?

If it is, how can I add it in my webform?

I done this but for a user reference by creating a new module and a new webform component.

This new component effectively recreates the user reference functionality and allows you to choose it on the webform. You could try the same approach to do it for a node reference.

Also there are some good examples in the webform examples to help you with the basics in creating a new component with hooks like _webform_defaults_component().

The main thing which will help you is the '#autocomplete_path' => 'autocomplete/node', in _webform_render_component() which you will need in the component.

...In the module add something like the below (obviously change for node lookup):

//create a url path for the autocomplete
function hook_menu() {
  $items['autocomplete/users'] = array(
    'path' => 'autocomplete/users',
    'title' => 'Auto Complete Users',
    //page callback to a custom function
    'page callback' => 'hook_autocomplete_users',
    'type' => MENU_CALLBACK,
    'access arguments' => array('access content'),
  );
  return $items;
}

//custom function created to mimic auto complete functionailty
function hook_autocomplete_users($string = '') {
  $matches = array();
  $query = "SELECT u.name, u.uid FROM {users} u WHERE name LIKE LOWER('%s%%')";
  $result = db_query_range($query, $string, 0, 10);
  while ($user = db_fetch_object($result)) {
    $matches[$user->name.' uid:'.$user->uid] = $user->name;
  }
  //print drupal_to_js($matches);
  drupal_json($matches);
  //exit();
}

You will need to choose what you want in the node reference too as by default it would just be the nid which in an email would be pretty useless..


How to resolve the Composer related error shown using the Drush DL command? I am working on MAMP and I have already installed a Drupal 7 site in my local machine ( not using Drush or Composer ). Then I have installed Composer and Drush ( Installing Drush on MAMP ). Now my Drupal site is under htdocs folder and it's working. If I run "drush" from htdocs via the command line, then it's shown a bunch of help command list.

But if I am trying to install any module using drush dl Module_Name then it gives me an error like so:

  [error]  dl has been deprecated. Please build your site using Composer. Add new projects with composer require drupal/[project-name]. Use https://www.drupal.org/project/composer_generate to build a composer.json which represents the the enabled modules on your site.

Can anyone tell me what the problem is? Do I need to install a fresh Drupal 7 site via Composer?

using composer is rather for Drupal 8 than Drupal 7
You could remove your version:

composer global remove drush/drush

and install an older one

composer global require drush/drush:8.*


Multisite: Only Drupal Root recognized for subpath I am having a Drupal 8 multisite installation:

Hostname: example.com
1st Drupal site: in example.com
2nd Drupal site: in example.com/sub/path

I have configured this in sites.php:

$sites['example.com.sub.path'] = 'subpath.example.com';
$sites['example.com'] = 'example.com';

The directories example.com and subpath.example.com contain the corresponding settings.php, setting.local.php, etc files.

Additionally, I have added this to the apache configuration (apache 2.4):

DocumentRoot /var/drupal
Alias /sub/path /var/drupal
Alias / /var/drupal
  <Directory /var/drupal/>
    Options Indexes FollowSymLinks
    AllowOverride All
    Include /var/drupal/.htaccess
  </Directory>

The site example.com works as expected.
I could install the site example.com/sub/path, but I now can just go to the home page. Every sub-page goes instead to the example.com configuration and gives an appropriate 404 error.

What did I do wrong/overlook?

Any help greatly appreciated!

Adding a rewrite rule into the .htaccess file fixes the problem. Without the rewrite rule for this path, the default rewrite rule goes into effect, pointing to the example.com/index.php instead of example.com/sub/path/index.php.

Disadvantage: I will have to patch .htaccess every time I upgrade Drupal core.

RewriteCond %{REQUEST_URI} ^/sub/path/(.*)$
RewriteRule ^(.*)$ /sub/path/index.php [L,QSA]


Fetching specific node fields instead of whole nodes using EntityFieldQuery The standard for fetching specific nodes from the database in Drupal 7 goes something like this:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node');
$query->entityCondition('bundle', 'page');
$query->fieldCondition('field_category', 'value', $category_id);

$result = $query->execute();
$nids = array_keys($result['node']);
$nodes = node_load_multiple($nids);

For better performance, is there any way to specify that I want to load only certain fields (the title for example) of the nodes instead of loading all their their fields?

I prefer a solution that doesn't use SQL to benefit from all the goodies Drupal functions offer (reliability, caching results, future proofed, ...).

Thank you.

No, there isn't. EFQ can only return the entity id's.

While there might be ways around it, there is a logical reason for that: Modules might alter the values of those fields in various hooks, there is no guarantee that the directly returned values are the same as when loading an entity.


I save form data using hook_form_alter() but the data don't appear when editing the node from the UI I implemented hook_form_alter() to insert few fields. I implemented hook_node_insert() to save the field data, hook_node_load(), and hook_node_view().

Everything works fine, but when I edit the node, the edit form appears with no data.

How can I fix this?

function mymodule_form_ABC_node_form_alter(&$form, &$form_state, $form_id) {
  $options_first = _mymodule_get_first_dropdown_options();
  $selected = isset($form_state['values']['filed_1']) ? $form_state['values']['field_1'] : key($options_first);

  $form['field_1'] = array(
    // …
  );
  $form['field_2'] = array(
    // …
  );

  return $form;
}

/**
 * Implements hook_node_insert().
 */
function mymodule_node_insert($node) {
    db_insert('my_custom_table')
      ->fields(array('nid' => $node->nid, 'field_1' => $node->field_1, 'field_2' => $node->field_2,))
      ->execute();
}

/**
 * Implements hook_node_load().
 */
function mymodule_node_load($nodes, $types) {
  foreach ($nodes as $node) {
    $nids[] = $node->nid;
  }

  $result = db_select('custom_table', 'e')
    ->fields('e', array('nid', 'filed_1', 'field_2'))
    ->where('e.nid IN (:nids)', array(':nids' => $nids))
    ->execute();

  foreach ($result as $record) {
    $nodes[$record->nid]->field_1 = $record->field_1;
    $nodes[$record->nid]->field_2 = $record->field_2;
  }
}

/**
 * Implements hook_node_update().
 */
function mymodule_node_update($node) {
  if ($node->type == 'abc') {
    // Delete the existing values.
    db_delete('custom_table')
      ->condition('nid', $node->nid)
      ->execute();

    db_insert('custom_table')
      ->fields(array('nid' => $node->nid, 'field_1' => $node->field_1, 'field_2' => $node->field_2,))
      ->execute();
  }
}

You need implement hook_node_prepare. This hook is used to load additional data before a node object is shown on the add/edit form.


Why is the drush views-list command complaining (incorrectly) that views is not enabled? I am running drush version 5.3:

rob@drupaldev:/var/www/drupal$ sudo drush version
drush version 5.3

When I attempt to execute the views-list command it says that the views module is note enabled.

rob@drupaldev:/var/www/drupal$ sudo drush views-list
Command views-list needs the following module(s) enabled to run:     [error]
views.
The drush command 'views-list' could not be executed.                [error]

However, the module is already enabled:

rob@drupaldev:/var/www/drupal$ sudo drush pm-list|grep -i views
 Chaos tool   Views content panes              Module  Not installed  7.x-1.0
 suite        (views_content)
 Views        Views (views)                    Module  Enabled        7.x-3.3
 Views        Views UI (views_ui)              Module  Enabled        7.x-3.3

Any ideas what else could be causing this?

Greg suggested that it could be a permissions issue or an environment issue caused by the necessity of using sudo. After having fixed one of my permission issues, I can reliably run drush with or without sudo. In either case it returns true.

rob@drupaldev:/var/www/drupal$ sudo drush ev 'var_export(module_exists("views"));'
truerob@drupaldev:/var/www/drupal$ drush ev 'var_export(module_exists("views"));'
truerob@drupaldev:/var/www/drupal$

This is working just fine for me on a d7 site using Drush 5.4.  You are getting that message because module_exists("views") is returning false.  Your next example shows that views is enabled, which implies that module_exists("views") should be returning true.  Perhaps your site is not always bootstrapping cleanly under Drush?

Try:

drush ev 'var_export(module_exists("views"));'

Add on the 'sudo' as you do above, if you really need it.  The sudo does give me pause; I prefer to set up my permissions in such a way as to allow Drush to run without it.  Sometimes sudo changes your environment subtly (e.g. your $PATH may change), although I cannot think of a reason why it would cause you trouble in this instance.  In any event, if the test above returns 'true', then you've stumped me.  If it returns 'false', it indicates that there is something inconsistent or incorrect about your environment.  You'll have to dig deeper to find out what it is.

Edit: I'm wrong, there could be other reasons why you are getting that error, even if module_exists("views") returns 'true'.  It probably boils down to drush_bootstrap_to_phase() failing when called from _drush_bootstrap_and_dispatch(); however, I can't imagine why this would fail for views-list, but work for pm-list.  More data is needed.

Edit 2: Try again with Drush All-versions-5.x-dev (or check out head of master from git).  This is usually the first thing I suggest, but I thought that none of this code had changed recently. Turns out that enabling / disabling a module now clears the cache, but this feature was added after Drush-5.4 went out.  drush cc drush should do the trick in the interim, but you won't need to explicitly do this in the future.


Views and how to get calendar taxonomy legend In the below image example, the person has a taxonomy legend (lower right hand corner):

How did this person get the legend?  From his blog:

  After [adding taxonomy term fields] let's hop back to our Views settings for the calendar view. Go to "Format" and Calendar Items Settings. Here we have an awesome legend feature built right in.

Um, no we don't.  So how come he has a taxonomy legend feature (i.e. vocabulary legend types) in his Views and I don't?  See below from his blog:

All I see in mine is the below:

Notice that my term field pull-down is mysteriously blank. Something whacky is going on!

To see an option in the term field as above (e.g. field_event_type) make sure you add the Taxonomy field to your view and select Create a label in the Configure Field options. The label you create will then appear in the term field. If you do this with multiple term fields that are added to the view you can use the drop down to select.

Not sure at this stage regarding the Legend option however.


Why doesn't LinkFormatter::viewElements bubble cache metadata? I am trying to understand how the token system in Drupal 8 interacts with the cache bubbling system and in LinkFormatter I see $link_title = \Drupal::token()->replace($item->title, [$entity->getEntityTypeId() => $entity], ['clear' => TRUE]); doesn't pass in a BubbleableMetadata object to the token system. But why?

Is this causing a bug for you, or are you just trying to understand how it works at all?

Making the token system integrate with the cache system happened very late in the Drupal 8 development cycle (see https://www.drupal.org/node/2528662).

Note that if that optional Token::replace(…, …, …, BubbleableMetadata $bubbleable_metadata = NULL) argument is not passed, it does check whether this token replacement is happening within an active render context (see the hasRenderContext() condition in ::replace()) and if so, it bubbles it automatically, directly onto the render context. Since Linkformatter::viewElements() is only ever called during rendering, AFAICT it should actually be working fine already, thanks to that automatic bubbling. We should not be relying on that, but precisely because it was added so late in the D8 development cycle, we had no choice but to resort to such approaches to minimize disruption.


Add datepicker to view exposed filter I have a view and an exposed filter with a date field, I want to make this filter as a date picker, not a text field, I've used Better Exposed Filters but didn't find anything in view, I had used it much time in D7 but In D8 cannot find it in the view exposed form style. So what should I do to use this module

You can add the jquery date picker in for that page as dependency.

your_theme.libraries.yml

date-picker:
  js:
    script/site-datepicker.js : {}
  dependencies:
    - core/jquery
    - core/jquery.ui.datepicker

site-datepicker.js

Drupal.behaviors.customDatepicker = {
  attach: function (context, settings) {
    jQuery(function () {
      jQuery("#datepicker").datepicker({
        dateFormat: "dd-mm-yy",
        altField: "input[data-drupal-selector=edit-created]",
        altFormat: "yy/mm/dd 23:59:59"
      });
    });
  }
};

views-exposed-form--views-block-name.html.twig

{% if q is not empty %}
  {#
    This ensures that, if clean URLs are off, the 'q' is added first,
    as a hidden form element, so that it shows up first in the POST URL.
  #}
  {{ q }}
{% endif %}

<input id="datepicker" type="text">
<input data-drupal-selector="edit-created" data-msg-maxlength="This field field has a maximum length of 128." name="created" size="30" maxlength="128" aria-invalid="false" type="hidden">
{{ form|without('created') }}

There is also the Date Popup module, for Drupal 8. You can use that module and implement this functionality.


How do I limit access to a custom field type I have created so that it can only be attached to certain bundles of content? I have a custom field class. I would like to limit it to specific content types and bundles that I will choose when my custom module is installed and as other content types meet certain criteria. I don't want it to be available at /admin/structure/types/manage/article/fields/add-field
Is hook_form_alter on the add-field page form my only option or is there an Annotation or API I can use to mark my field as "not available to this content" similar to the way FieldWidgets can be marked as applicable to only certain field types?
Note: I was also planning to add a ConstraintValidator to the field so that it won't validate if added to the wrong content.

It is not possible to define field types which are only applicable to certain bundles. I think you need hook_form_alter for the form where the fields are chosen for a bundle to achieve that.


Department-based web site in which users can only edit content in their own department What would be the steps to build a web site with different departments in which the users with edit permission can only edit content in their own department? Content types would be shared, e.g. the "page" content type should be available to all of them.

I've read this can be accomplished with PURL + spaces, but I am not sure this is still the best option, as most posts about it are from a few years ago.

You should look at the Organic Groups (OG) modules.

With OG, departments (i.e. "groups") is set up and managed by means of the graphical user interface.  It simply provides a way to delimit a department in terms of content and members.  Unlike the Spaces module, there is no total separation between departments.  OG modules presents an evironment where departments appear to exist side by side within a single website. In other words, the groups are non-hierarchical, leverage the same theme and share common modules, etc.

Within this framwork, OG can provide multiple levels of privacy and membership.

It allows one to create content types that can associate any number of nodes to a group node. Then, developers and users can create pages that only display content intended for that particular department.

Note, however, that OG does not provide a base URL for a department namespace (e.g. http://example.com/startrek/ for a department named "Startrek".)  If you want this, the convention approach has been to install OG + Spaces + PURL to get this.

However, this article suggests an alternative approach building on a sandbox module named OG Token.  I haven't tested this tho'.  There is also another bridge module, named OG Purl that may do this for you.

Alternate, lightweight solution: If you can relax the requirement that all departments shall have access to the same content types, you can implement this with the core alone (i.e. without any external module), just using Drupal's built-in ability to clone content types and built-in role based access.

For instance, let say you want to have a department named "Startrek" (for fans of the classic TV-series).  Clone the Article content type and call the clone "StartrekArticle".  Now create a role named "StartrekEditor".

Navigate to Administration » People » Permissions and scroll down do the Node section.  Grant the role StartrekEditor the following permissions:

StartrekArticle: Create new content
StartrekArticle: Edit own content
StartrekArticle: Edit any content
StartrekArticle: Delete own content
StartrekArticle: Delete any content

Now, just give any user that is going to be editor in the Startrek department the role StartrekEditor.

Also note creating department-specific content types have no impact on the user's ability to view content.  The Drupal default is that any user may view any content, and users will not even be aware of the fact that they're viewing content in different departments that differ by name only.

To have a base URL for a department namespace using this lightweight solution, you still need to install PURL, but you will not have to deal with heavyweight modules such as OG + Spaces.


Hide fields from a view I am not sure how to explain this as I have very little experience with Drupal. I built a site with Drupal 7 and now I am trying to recreate it in Drupal 8. I have a problem with the Content area.

I have set up a view that looks like this.

The arrow points to a title name link.

When I click the link, I want to see additional detail not shown in the view. This works. However, there is as an additional view that looks like a “teaser” view that I do not want to be displayed. The area at the top in the rectangle I want and is part of the “Entity View (Content) with a category of Chaos Tools. The bottom part near the x is the teaser part and is a duplicate of the top part I don’t want. How can I remove the bottom part?

man. Have you solved yet? There's this custom module that even someone with basics of programming could do. But it is not perfect, you will have to make an extra view and stuff... https://atendesigngroup.com/blog/removing-duplicate-content-across-multiple-drupal-views


How can I set up the media file selector for an image with the image styles in the same row? What I want to do is this:

Thank you.

You can use the Formatter Field module to choose an image style per entity

  The formatter field module provides a mechanism for specifying a formatter and formatter settings to be used for displaying a field, on a per-entity basis. By default, Drupal provides formatters and settings per entity bundle, but in certain situations it is necessary to choose the formatter at the entity level.

But I don't think anything exists to choose a formatter per delta of a field. You'd probably need to look at coding that one yourself. The Formatter Field module would be a good place to start to get ideas for the code.


Translating contact forms Is there a way to fully translate the contact message forms in Drupal 8? In the content language screen, the contact message bundle is marked as translation is not supported.

Edit: To clarify, I would like to translate the fields of the form. As some answers note, the fields can be translated via the regular field translation, but I am running into an issue whereby translations are replaced by the English version when the cache is cleared. By going to /admin/config/regional/content-language and saving the form, the translations are back.

(Note that the default language on the site is not English.)

I think, content in contact messages is the user input. Then you cannot translate this, because it is not saved to the database. The form itself is config translation, similar to the field definitions in content types.


How to get the number of registrants (RNG module) from the theme layer In my theme I want to display not only the maximum number of registrants on the full view of a node but also the number of seats still available.

What is the easiest way to get the number of registrants? In Drupal 7 I retrieved this number by passing the node id into the registration_event_count() function, does RNG provide a similar function?

You can access the event manager service to grab an event meta object. The event meta object contains a bunch of helpers to manipulate registrations and registrants. In your template preprocess functions add whatever data you want from the event meta object.
function mymodule_preprocess_HOOK(&$variables) {
  $event_entity = $entity; // Provide your entity

  /** @var \Drupal\rng\EventManagerInterface $event_manager */
  $event_manager = \Drupal::service('rng.event_manager');
  $event_meta = $event_manager->getMeta($event_entity);
  $mydata = $event_meta->whatever();
   // See \Drupal\rng\EventMetaInterface for methods. e.g:
   // $event_meta->getRegistrants()
   // $event_meta->getRegistrations()
   // $event_meta->countRegistrations()
   // $event_meta->getCapacity()
   // $event_meta->remainingCapacity()
  $variables['myvariable'] = $mydata;
}

For nodes, replace mymodule_preprocess_HOOK with mymodule_preprocess_node and $entity with $variables['node'].


Add menu links to custom generated menu I am working on a custom Drupal 8 module which generates a menu. Refer Create a new Menu in Drupal 8 programmatically for details.

I have the menu now, but when I try to add custom menu links to it, following add a menu link, somehow it's not getting added to that custom menu.

Another weird thing is that the links are getting added to the wrong menu, i.e. they show under User Account Management menu.

The only reason I can think of is, when I install the module, Drupal tries to create the menu link first, before it has created custom menu. As the custom menu is not there yet, it tries to add the menu links to another menu. Is that right?

Here is my code, if that helps:

// system.menu.aeauth.yml // This creates the new menu on module install

langcode: en
status: true
dependencies: {  }
id: aeauth
label: 'AE Authentication Links'
description: 'Links related to AE Authentication'
locked: true

// ae.links.menu.yml // This adds menu links to menus

ae.admin_settings:
  route_name: ae.adminForm
  title: 'AE Configuration'
  description: 'Configure AE for your website'
  parent: system.admin_config_system

ae.register:
  title: 'Register'
  description: 'Register using AE Connect'
  parent: aeauth
  route_name: ae.regroute

ae.login:
  title: 'Login'
  description: 'Login using AE Connect'
  parent: aeauth
  route_name: ae.loginroute

The problem is that you're not specifying what menu your links belong to. Instead you are setting the parent, but I think the parent doesn't exist in your cast. This works for me:

custom_module/system.menu.my-custom-menu.yml:

langcode: en
status: true
dependencies: {  }
id: my-custom-menu
label: 'My Custom Menu'
description: ''
locked: true

custom_module/config/install/custom_module.links.menu.yml:

custom_module.custom_link:
  title: 'My Custom Link'
  weight: -10
  route_name: custom_module.custom_route
  menu_name: 'my-custom-menu'


How to get current language of node in twig? I have a tranlatable node, and I need to get its translation language. You know, I must to know is current node is in Polish or English. So... below there are my devel dumps from a node in Polish and a node in English. I see that there is a difference in #activeLangcode (x-default and en). But how to get that value? Or is there any better way to check current language of node in twig? Please help.

A more elegant Drupal way without typing code:

Go to the Manage display of the content type of your node (/admin/structure/types/manage/YOUR_CONTENT_TYPE/display/full). Select your display mode (or use the default). You will notice the field 'Language', move it to the upper side so it gets out of 'Disabled'.
Once you have done that, the language of the node is available in Twig. You can access the id this way {{ node.langcode.langcode }}; or you can access the whole Object to get other data like the name {{ drupal_dump(node.langcode) }}


How do I compare a field of a node with all nodes of a content type with rules? In Rules on Drupal 7, how do I set up a rule / ruleset so when a node is saved compares a textfield from the saved node with a textfield in all nodes of a content type and if match, not the saved node but the matching node should be unpublished?

I haven't found a solution using only rules yet, maybe it would be possible with rules and views bulk operations (vbo)? A custom module is what I did to solve it (thanks Oleg for pointing me to EntityFieldQuery). Here is the code:

<?php

/**
 * @file
 * custom_unpublish.module
 *
 * This module compares a field in a node when updated with a field in all
 * nodes of a content type and if match, the matching nodes is unpublished
 */

function custom_unpublish_node_update($node) {
  // Only check nodes of a certain content type
  if ($node->type == 'article') {
    $wrapper = entity_metadata_wrapper('node', $node);

    // Get the wanted field
    $id = $wrapper->field_id->value();

    $query = new EntityFieldQuery();

    // Check only a certain content type (bundle) and make a fieldCondition
    $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'accepted_article')
    ->propertyCondition('status', 1)
    ->fieldCondition('field_id', 'value', $id, '=');
    $result = $query->execute();

    if (isset($result['node'])) {
      $result_items_nids = array_keys($result['node']);
      $result_nodes = node_load_multiple($result_items_nids);
      foreach ($result_nodes as $result_node) {
        // Unpublish the node
        $result_node->status = 0;
        node_save($result_node);
        watchdog('custom unpublish', 'Match for ' . $id . '. ' . $result_node->title . ' was unpublished.');
      }
    }
  }
}


How to insert images into custom block type This might be a really stupid question because I am overlooking something really simple but here is my issue. I have created a custom block in the custom block library in Drupal 8. I would like to insert images into the block from the images folder in my theme (not upload images using ckeditor).

Normally in Drupal 7 I can manually insert the image using an  tag and all is good. In Drupal 8 this method is not working for me. Here is an example of the code that I enter into the source view:

<img class="socialmedia" src="/themes/custom/mytheme/images/social_media/facebook.png" />

However this does not work - no image is being displayed. I have verified that the path is correct, the spelling is correct, and tried with and without the leading slash. Nothing works.

I found a similar question, but the answers supplied don't address the question as they use php code.

What has changed between Drupal 7 and 8 in this regard? What am I missing?

Thanks

With twig you can use {{ directory }} to point your theme directory.