Adding values to referential entity using REST API POST I have 2 custom content type. One is movies and the other is actors. I am using REST API POST to add values into movies. Actor is a referential entity within movies. How do I add values into actors which are corresponding to a particular movie when I use POST?

An option that I am currently trying out is add multiple values into actors first and that POST will return a node id, use that node id value along POST values to movies. Is this the right approach?

You can see the article about create Custom Rest Resources for POST

You can reference below code below

$node_actor = Node::create(
      ['type' => 'actor',// the content type
        'title' => 'Actor Name',
      ]
    );
   $actor_id = $node_actor->save();

After you can use $actor_id had node reference to movie

$node_movie = Node::create(
   ['type' => 'movie',// the content type
    'title' => 'Movie Name',
   ]
  );
  $node_movie->set('field_actor_ref',['target_id'=>$actor_id])
  $node_movie->save();


Losing SSH access to Acquia Cloud: "permission denied (publickey)" Sometimes, when working on an Acquia Cloud project, I seemingly spontaneously lose git access on the AC server. This might be related to switching between multiple workstations while working on the project. When I try to run a git command, I get

Permission denied (publickey).
fatal: Could not read from remote repository.

I have not changed my keys related to this project.

I haven't determined the root cause of this issue, but I found a functional solution:

When I get this issue, rather than in my IDE I ssh to AC via the Acquia Dev Desktop interface (clicking the small terminal icon next to the SSH address). This runs a specific SSH connection with several options:

ssh -p 22 -i "/Users/username/.ssh/acquia_key_name" -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null sitename.dev@server.devcloud.hosting.acquia.com

After this command is run (in my case in Mac Terminal), I can access the git repo again via my IDE.


how do i get the groups which i have joined How can i display to my site users after joining into one group, need to display my Joined groups. suppose one person send invitation to his friend and he has joined in to his group after click link. then he has to see in his friend group he has joined using Views.

Like:
      My Joined Groups
      XXXXXXGroup

Thanks

There is a view that comes with OG 7.x-1.x (I'm using 7.x-1.4) that displays all of the groups subscribed to. If you have views running, you could  simply append /user-groups to your url and you should see it. After that, you can go into the view and modify it to meet your specific needs (e.g., make a block or whatever).


How to reorder the date in a view expose filter? I have created a view with date expose filter. Currently filter is working fine but i need to reorder the day and month.

From month/day/year

To day/month/year

Got the settings Home » Administration » Configuration » Regional and language


Exclude taxonomy term from select list on node add page I have a view that shows guest user generated articles grouped by taxonomy terms. There is just one taxonomy term which I don't want that users add articles with (only logged in users should). So how can I exclude this taxonomy term from the select list on the node add page? I suppose by some function in the theme file?

You need to implement hook_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) inside a custom module.

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Form%21form.api.php/function/hook_form_alter/8.2.x

Inside the form parameter you should be able to unset the specific option that you don't want to be displayed.


AJAX pagination with back button Drupal view I have one view of a multimedia page wherein I use AJAX for pagination. The view shows the result of a multimedia image. When I click on the image it goes to the inner content page. In the inner content page there is a back button. When I click the button, it goes back to the previous page from where I came.

When I click on the back button it always forwards me to the multimedia page. But I want it to forward me to pagination page 2 if I came from page 2.

There is a module views_ajax_history which uses https://github.com/browserstate/history.js to maintain the current state of page and push them into browse history with HTML5 history api. This library support fallback if history api is not supported by older browser.


Filtering comment by date range in Views I have created a view to filter comments by date range. For date range i am using between operator.

View type : Comment
Date : comment created (default field)

Issue : When i am trying to filter comment from 2015-11-01 to 2015-11-15

i am getting result from 2015-11-01 to 2015-11-14 only.

what i am missing ? may be some help me ?

Views uses in between operator i.e. BETWEEN min AND max expression.

This is equivalent to the expression (min <= expr AND expr <= max). Now the query that views create for date is:

(comment.created BETWEEN 1446336000 AND 1447545600)

Search for unix time value of 1447545600

The problem is with the date 2015-11-15, this is treated as 2015-11-15 00:00:00. So 2015-11-15 11:12:13 won't be included. Hope you get my point.


How do I set a cookie using $response->headers->setCookie() in a form submission handler? I read on Deprecate user_cookie_save() and user_cookie_delete(). that user_cookie_save() will be deprecated in Drupal 9 and that we should now use the Symfony's method, as in the following code.

$response = new Response();
$response->headers->setCookie(new Cookie('foo', 'bar'));
return $response->send();

If I use that code in a submission handler of a custom form, $response-send() just returns an empty page, rather than my site. What am I missing here?

EDIT:

OK, so I moved my cookie setting code to a controller method:

public function setusercookies($zip, $license){
    $destination = urldecode(\Drupal::request()->query->get('destination'));
    $response = new RedirectResponse(!empty($destination) ? $destination : '/');
    $response->headers->setCookie(new Cookie('zip', $zip, strtotime( '+1 year' ), '/'));
    $response->headers->setCookie(new Cookie('license', $license, strtotime( '+1 year' ), '/'));
    $response->send();
    return $response;
}

And in my form's submitForm function:

$form_state->setRedirect('mycontroller.setusercookies', [
      'zip' => $zip,
      'license' => $license
    ], [
      'destination' => $destination
    ]);

In both Chrome and Firefox inspectors, I can see that the cookies are set, but now I can't get them back out. I've tried both:

$zip = \Drupal::request()->cookies->get('zip', 'oops');
/* and */
$zip = $_COOKIE['zip'];

UPDATE 2:
Starting to think it's an environment issue ... lando with pantheon recipe.

SOLVED:
The entire time it seems it was a platform issue:

https://pantheon.io/docs/caching-advanced-topics/#using-your-own-session-style-cookies

You can't send a response from custom code in Drupal. You have to return it from a controller.

You can also set a response or add the cookie to an existing response in an event subscriber. In your case set the response in form submit, then Drupal does this for you in a core event subscriber:

$form_state->setResponse($response);

To avoid the empty page you probably want to fill the response with content or add the cookie to a redirect response to display a different page.

Don't $response->send()

To explain why not to send a response. When you find a code example for the Symfony component HttpFoundation sending a response, it isn't valid for custom code in Drupal. See the warning in this doc:

  This article explains how to use the HttpFoundation features as an
  independent component in any PHP application. In Symfony applications
  everything is already configured and ready to use. Read the Controller
  article to learn about how to use these features when creating
  controllers.

In addition the Drupal kernel is wrapped in stack middlewares using Stack/Builder. So sending a response can even be a security risk if you have for example installed a middleware providing security checks.


Which is the most performant way of overriding views field output This question sureley can only be answered by people with some drupal experience.
As I have quite different and complex views, which I need to control totally, I need to come to a design decision. Which way has the highest performance putting out view content?

Define the fields in the Views UI, don't output them and use them in custom text? Like described here: http://highrockmedia.com/blog/rewriting-drupal-views-output-custom-theming-css
Provide a views-view-field--field-machine-name-of-field.tpl, get the $row['_field_data']['nid']['entity']->{'field_machine_name'} and iterate over its contents?
Another or better way of which I'm not aware off?

Example, of how a result could look like:

  Dell UltraSharp 30" LCD Monitor

    87
    out of 100
    based on 24 user ratings

    $1250
    to $1495
    from 8 sellers
  Sellers:

     Save A Lot Monitors - $1250

    Jon Doe's Gadgets - $1350

I would go for Template based solution for the sake of maintainability and flexibility. For example, if you are using the same field in two different views, you can use a .tpl file that applies to all views that have that field. But if you depend on Views UI, you will have to configure each field in every view separately which may complicate things in the long run. Also, the fewer access to database to retrieve configuration the better.


How can I create a view that displays the most popular nodes based on an outgoing link? The link is a text field that's value is pulled directly in node.tpl:

<a class="list-parent-link" href="<?php echo $node->field_download_link['und'][0]['value']; ?>">

I'd like to be able to track how popular each node's link is, and display the 5 most popular nodes in a views block. Is that possible?

yes it can be done in a number of ways... some options:

1) add a JS onclick="" to the link which goes to a function that causes an ajax call to the server. The server would then take in node information and using something like the Flag Module:

  Flag is a flexible flagging system that is completely customizable by
  the administrator. Using this module, the site administrator can
  provide any number of flags for nodes, comments, users, and any other
  type of entity. Some possibilities include bookmarks, marking
  important, friends, or flag as offensive. With extensive views
  integration, you can create custom lists of popular content or keep
  tabs on important content.

to trigger a counter which can then be easily used in Views.

2) adjust the link direction to an internal proxy page:

<a href="/mymodule/proxy?url=<?php echo $node->field_download_link['und'][0]['value']; ?>">

The proxy page would have a callback function that again uses Flag or similar to track the click and then redirect the page to the provided url.

Option 2 is probably the better of the two, but it depends on the set up, and whether or not you want a redirect, etc.

I can give more specific guidance if you decide to go with one of these.


Calendar Views: Upcoming or Recent I'm currently using the default calendar views "Upcoming" block to display upcoming events on my homepage. However, because events are infrequent, its common for there to be no upcoming events. In which case, the block disappears and leaves a big blank spot in the home page.

Is there way to show either the next four events OR the last four events? For example, if there is only one upcoming event, it would add the last three events to the list and display all four in ascending order.

Thanks!

FYI, here is how I solved it. Thanks Rock, for the step in the right direction!

Overview: Used a custom module that creates a block that displays one of two view displays.

Programmatically created a view (hook_views_api, hook_views_default_views) with two displays: one that shows upcoming events (ascending order, up to 4 items without a pager), and one that shows the last four events in the database (descending order, 4 items without a pager)
Programmatically created a block (hook_block_info) that displays (hook_block_view) one of the two view displays based on the number of results in the "Upcoming" display ( $results = views_get_view_result('view_id', 'display_id');).
Created a custom template file (views-view-unformatted--view-id--display-id.tpl.php) for the second display, which reverses the order of results so that they are still displayed with earliest date first.


Rendering nodes and other content compatible with all themes With a group of several people we're creating a system for students.

Now, on that system we're going to have all kinds of modules that have output, e.g., content types with information about events, a page with a hierarchy of people and groups.

What is the Drupal way of rendering this output?

I know that rendering should be done by the themes. But the problem is that our users should be able to pick a theme they want. Creating separate output for each of those themes is just unfeasibly hard.

I know that rendering should be done by the themes.

That is not exactly correct. Theme functions are generally defined from modules, and themes can override them, or implement a theme function that is specific for a purpose.

theme_node_preview() is implemented by the Node module
theme_field() is implemented by the Field module
theme_rdf_metadata() is implemented by the RDF module
Other theme implementations are contained in the theme.inc file

If you are creating the output for a page, the code for generating it should be in a module. That is because it's a module that can implement hook_menu(), which is the hook that defines the menu callback used for pages.
That is what is done from Drupal core code with node_view(), which is the page callback for node/%node, and node/%node/view. The page callback is defined from the Node module, not from a theme; themes can eventually alter the output of node_view() through the node.tpl.php template file used from node_view() to render the node page.

As for outputting the result, there are two methods:

Returning a string containing the HTML output
Returning an array with a specific structure (it is called render array) that can be used from drupal_render()

As example of a page callback that returns a string, see aggregator_view(); as example of page callback that returns a render array, see node_view().


Need help with rules for shipping in drupal commerce I need help with rules to set shipping rate depending on weight and address, I have some rules but can't do work properly, shipping rate load but there is no change with different weight, can anyone help me?

Thanks in advance!

My rules looks like this, only change in each rule is the "Province" and the limits weight.

{ "rules_atacama" : {
"LABEL" : "Atacama",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [
  "rules",
  "commerce_physical",
  "commerce_order",
  "commerce_line_item",
  "commerce_shipping"
],
"ON" : { "commerce_shipping_calculate_rate" : [] },
"IF" : [
  { "data_is" : { "data" : [ "commerce-line-item:type" ], "value" : "shipping" } },
  { "data_is" : {
      "data" : [ "commerce-line-item:commerce-shipping-service" ],
      "value" : "costos_envio"
    }
  },
  { "OR" : [
      { "commerce_physical_rules_order_weight_comparison" : {
          "commerce_order" : [ "commerce-line-item:order" ],
          "operator" : "\u003E=",
          "value" : "0",
          "unit" : "g"
        }
      },
      { "commerce_physical_rules_order_weight_comparison" : {
          "commerce_order" : [ "commerce-line-item:order" ],
          "operator" : "\u003C",
          "value" : "1500",
          "unit" : "g"
        }
      }
    ]
  },
  { "entity_has_field" : {
      "entity" : [ "commerce-line-item:order" ],
      "field" : "commerce_customer_shipping"
    }
  },
  { "OR" : [
      { "commerce_order_compare_address" : {
          "commerce_order" : [ "commerce-line-item:order" ],
          "address_field" : "commerce_customer_shipping|commerce_customer_address",
          "address_component" : "administrative_area",
          "value" : "AT"
        }
      }
    ]
  }
],
"DO" : [
  { "commerce_line_item_unit_price_amount" : {
      "commerce_line_item" : [ "commerce_line_item" ],
      "amount" : "3350",
      "component_name" : "flat_rate_costos_envio",
      "round_mode" : "0"
    }
  }
]

}
}

If you're taking the pure rules route, you'll need a single rule per rate. So if you have two (2) zones and three (3) weight tiers, you'll need six (6) total rules. For example:

Northeast
Rest of the US

And

0-5 lbs
6-10 lbs
11+ lbs

Will be 6 total rules:

Northeast (0-5 lbs)
Northeast (6-10 lbs)
Northeast (11+ lbs)
Rest of the US (0-5 lbs)
Rest of the US (6-10 lbs)
Rest of the US (11+ lbs)

You may also find it worth your time to review Commerce Shipping Postal Code Weight and Commerce Shipping Weight Tariff.


How to manage reservations with a 2 hours duration without duplicate bookings? I want to make a calendar view that will show when music teachers are available, so that students can register online and attend a lesson. The courses have all the same duration which is 2 hours. For this, I created a content type called "Lessons" (Fields: title, description, teacher name, teacher email, date/time) and a content type using node reference module for registrations to each specific lesson. In that way students can register online for music lessons.

There are 2 problems with this:

How can I have a fixed 2 hour duration in the day of the calendar view that won't let students register for more or less time than the two hours? I can not just hide the time fileds because the system must show them the time that the lesson takes place?
I want to allow just one user register for each lesson and then the system must show that lesson as booked. To be more specific, I want the calendar to show the whole day seperated in 2-hour periods and which periods are free. When a user registers for a lesson, the lesson changes color (I can do this with css) and is marked as reserved so that the "next" user can only register for another of the open lessons and so on.

Any ideas?

If you don't want to re-invent the wheel, have a look at these contributed modules that are typically used for this (quotes are from their project pages):

Availability Calendars.

  ... allows you to add an availability calendar to entities. Example use cases are tourist accommodation, e.g. bed and breakfast, holiday homes or self catered apartments, and car or motor bike rental.

  An availability calendar shows your customers at what dates your accommodation is still available and at what dates it is already booked.

Simple Reservation.

  ... provides a simple and easy way to reserve items which can be created by the administrator. Examples for it's usage can be hotel rooms, boats, cars, airplanes, basically anything you can think of which can be reserved by one individual.

  The module provides the possibility to create reservations for other users (dependend on the permissions), and provides also restrictions in the maximum number of reservations a user can make and a maximum time a reservation can be made in advance.

  There is NO support for payment, booking and what ever one could imagine beyond the pure and simple reservation, and it is also NOT intended to create more than this simple functionality.


Deploying code to multiple front end servers We have a situation where we have multiple load balanced servers pointing to a common database.

In the normal run of things this works fine and gives redundancy, scalability etc.

However we are finding deployment to be a bit of a chore.

We are using features extensively and are trying to automate deployment. Deployment at the moment is not very reliable.

In a simplified form the deploy script for each server has two stages

Update Files
Revert Features (which
will manage dependencies, settings
changes etc)

Are there any best practices for deploying across multiple servers without causing them to be in an inconsistent state?

As far as I can see if you deploy steps 1 and 2 to server A it will cause server B to break, if you try step one on both servers before proceeding to step 2 they will both be broken for a while.

You should probably look into Aegir, which is by far the most flexible and powerful Drupal site management/deployment system. It is able to manage 'platforms' that span acros multiple web heads, or 'clusters', as well as a variety of other configurations.

I'd suggest having a read through of their community documentation which is generally pretty good, as well as reading through mig5's excellent overview and introductory article and some of his other articles like this one.

You can also get good support in the #aegir IRC channel.

It'll be a bit of a workflow change, which can definitely take some time to get your head around, but once you're there you won't look back.


How to create a responsive theme with Omega? How can I create a responsive theme with Omega?

So far when I wanted to theme, I unchecked the reponsive design because I don't know how to theme responsive in Omega!

Any suggestions about how to achieve this?

So, there's plenty of good documentation on both Omega 3 and Omega 4. Depending on what your background is and what your experience level is there are a number of ways to approach responsive design. I suggest defining your needs for a responsive website, and then seeing how Omega can help you. If not Omega, than the Zen and Adaptive themes are also well documented. There are free tutorials and videos on youtube, your question here is too generic to answer.


Drupal multisite on a shared hosting Is there a way to install Drupal multisite feature (it needs access to http.conf and http.vhosts) on a Shared Hosting with shell access? It also needs to hosts projects with different databases.

I know there is a module named: Domain Access for share Drupal database with affiliated sites but this is not actual I want.

There is no good answer for this, as it will vary host-to-host.

Sometimes, shared hosts use management tools that map domains to accounts to directories.  This makes it hard(er) to do the Apache ServerAlias settings.  I have worked with shared hosts that have let this happen.

Sometimes, hosts will map domains to user accounts and run Apache in FastCGI mode, which may complicate things.

You need to contact your host to see what is possible.


Views not respecting Contextual filter and Referenced Entity relationship This is driving me crazy because it's so simple in Drupal 7.

Scenario:

Basic page has a entity referenced field where you can type in Spotlights that should be shown at the bottom of the page.

View:

Relationships (in order) is the field_spotlights (which exists on the Basic Page) and field_spotlight: Content using the previous relationship.

Contextual filter is the ID of the node, based on current id of page. Uses the field_spotlights relationship

Fields are the fields that exist in the spotlight, each with a relationship with field_spotlight: Content.

So the above should show only 3 results if the basic page is viewed and only has 3 spotlights in the entity referenced field.

However 4+ spotlights are showing, it's including the 3 that should show but then duplicates some or shows more.

UPDATE:

I've tried using Aggregation too, by adding a Content ID to the fields, and setting the aggregation setting to Count, Count Distinct, and Max/Min.

Also tried setting Distinct in the query settings.

I think you want a View of basic pages (meaning filtered down to Content Type = Basic page) with a contextual filter narrowing down to the current Basic page using the Content ID (NID). Then add in a relationship to Spotlight through the entity reference field. And then for your three fields, make them use the Spotlight relationship.


drush cron fails: Drush command terminated abnormally due to an unrecoverable error $ drush -v -d cron
Bootstrap to phase 0. [0 sec, 1.65 MB]                               [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drush() [0 sec, 1.77 MB]    [bootstrap]
Cache HIT cid: 5.4-commandfiles-0-33f01882e55343a61f1cb10880b0da0f [0.01 sec, 1.78 MB]                                          [debug]
Bootstrap to phase 0. [0.02 sec, 4.16 MB]                                                                                [bootstrap]
Bootstrap to phase 6. [0.02 sec, 4.16 MB]                                                                                [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drupal_root() [0.02 sec, 4.17 MB]                                                  [bootstrap]
Initialized Drupal 7.28 root directory at ...htdocs [0.03 sec, 5.78 MB]                                [notice]
Drush bootstrap phase : _drush_bootstrap_drupal_site() [0.03 sec, 5.78 MB]                                                  [bootstrap]
Initialized Drupal site default at sites/default [0.03 sec, 5.79 MB]                                                           [notice]
Cache HIT cid: 5.4-commandfiles-2-c32acd775c18a90c5b41d0fc9accf5ab [0.03 sec, 5.79 MB]                                          [debug]
Drush bootstrap phase : _drush_bootstrap_drupal_configuration() [0.03 sec, 5.79 MB]                                         [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drupal_database() [0.03 sec, 5.8 MB]                                               [bootstrap]
Successfully connected to the Drupal database. [0.03 sec, 5.8 MB]                                                           [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drupal_full() [0.04 sec, 6.3 MB]                                                   [bootstrap]
Cache HIT cid: 5.4-commandfiles-5-21916586faf556c236c401ff89ea50f6 [0.18 sec, 33.52 MB]                                         [debug]
Drush bootstrap phase : _drush_bootstrap_drupal_login() [0.18 sec, 34.19 MB]                                                [bootstrap]
Successfully logged into Drupal as Anonymous (uid=0) [0.18 sec, 34.2 MB]                                                    [bootstrap]
Found command: core-cron (commandfile=core) [0.18 sec, 34.2 MB]                                                             [bootstrap]
Drush command terminated abnormally due to an unrecoverable error. [0.2 sec, 34.87 MB]                                      [error]

There's nothing showing up in admin/reports/dblog.

Note that heading to /cron.php?cron_key=... works fine from the web interface. But it fails when curling it from console.
(I also reported an issue at https://github.com/drush-ops/drush/issues/664 but was directed here.)

How can I find out what's wrong?

P.S. related: https://stackoverflow.com/questions/10014142/cron-fails-when-running-through-drush-and-calling-node-load

Apparently Elysia Cron was installed and in that case you have to

drush elysia-cron

And drush cron is an alias of drush core-cron.


Views XML Backend, Render URL as MP3 player I have a podcast feed that currently i am manually maintaining. I am planning to automate the xml generation in the near future from one site then have it displaying on another.

I am trying to get the displaying part to work now. I am using Views XML Backend to pull the feed (I don't want to import the content as nodes as there is no need to) which is working for me on the text stuff.

I have an enclosure tag and a guid tag in the xml that has the URL to the MP3 file. I want the url to change from being a link (which I had to use the rewrite to link feature in views) to an Embedded MP3 player that displays in a page or block.

Anyone got any tips or suggestions on how to do that? I've tried a few things and am yet to find anything that works.

Running Drupal 7

Guess you should have every mp3 path wrapped by a player instance somehow. jPlayer has a nice field formatter which maybe works with your Views setup. Otherwise you'll maybe have to try to accomplish this on template level.


How can I move a view from one feature to another? I have a view that I added to Feature A that I would instead like to move to Feature B.  I re-created Feature A using the admin interface, but even after re-creating the feature, clearing the cache, and reverting the feature, the view still appears in the database in code and I am unable to attach it to Feature B.

How can I remove a view from one feature and add it to another?

I was able to do this by editing the respective view and causing the feature to go overridden.

Once the feature is overridden (aka. view settings/config saved in DB) we can recreate the respective feature w/o the view and drop that feature back into our site. Revert it, clear the cache (although when I did this, I didn't need to do either...still never a bad idea).

If all went according to plan you will now see the view is available to use in another feature, add it in, drop it back into your site and off you go!

This can also be done solely in code...
Navigate to your feature module via the CLI, you will notice 2 files: .info and views_default.inc

Find the declaration in your .info file for the respective view and move it to the .info file of the feature you want it a part of.

Next you will want to find the section of code in the views_default.inc defining your view and move that to the views_default.inc file of your new feature. It will begin with $view = new view(); and end with $export['your_view'] = $view;

You will want to revert your features to put the ordering correct in the files.


Commerce - Alter quanitity widget I'm new to commerce and I have a question. I'm building a website for a butcher, and he wants products to be sold per 100gr. I have the price in kilo and I allow decimal values for quantity.

The quantity field widget is a text box by default. I did some googling and found some things but i'm unable to get it work. I assume I need the commerce_cart_add_to_cart_form() function :)

I want to have a drop down with pre-defined values per 100 gram for example.

100 gram - 1 euro
200 gram - 2 euro
300 gram - 3 euro
....

1000 gram - 10 euro

Add to cart button

Any idea's? Or is there an easyer solution for this?

Thanks in advance

Assuming that you allow decimal in the quantity field, you can use the hook_form_alter() hook. It is one of the most used drupal hooks.

/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {

  // add to cart form
  if (strpos($form_id, 'commerce_cart_add_to_cart_form_') === 0) {

    // Replace the text quantity field with a select list.
    if (isset($form['quantity']) && ($form['quantity']['#type'] == 'textfield')) {

      $product = commerce_product_load($form['product_id']['#value']);
      $price = commerce_product_calculate_sell_price($product);

      $select = array(
        '0.1' => '100grams '.commerce_currency_format(1*$price['amount'], $price['currency_code'], $product),
        '0.2' => '200grams '.commerce_currency_format(2*$price['amount'], $price['currency_code'], $product),
        '0.3' => '300grams '.commerce_currency_format(3*$price['amount'], $price['currency_code'], $product),
        '0.4' => '400grams '.commerce_currency_format(4*$price['amount'], $price['currency_code'], $product),
      );

      $form['quantity']['#type'] = 'select';
      $form['quantity']['#options'] = $select;
      $form['quantity']['#size'] = 1;
    }
  }
}


Can we have multliple routing.yml files in a single module? I have more than 50 menus which I need to create custom.
as per the module structure, we need to create routing.yml in root folder.
but I want to do something like this below:

   myModule
      -  products(folder)
              - routing.yml
              - src(folder)
                - productController
      -  brands(folder)
              - routing.yml
              - src(folder)
                - brandsController.php
      - myModule.info.yml
      - myModule.module

is it way to do achive something like this.

I just want to make code seperation and avoid to add all routes in routing.yml

Instead of adding multiple routing files, you can define products, brands as modules inside your main module and then can define routing file for each of them like what is done in aggregator module in core.


Allign block content next to title - CSS My goal is to display a button group to the right of the page title. Currently it resides in region-content, which wastes space.
I tried adding my own class to the div that contains btn-group class and use margin-top to move it up, but as soon as I save content, I get system help message that overlaps with the button group.

I also tried to add the block to other regions and get same thing if, say, I use breadcrumbs.

What's the best way or what are the classes I should use to position my block with button group to the right of the page title in main-container instead of region-content?

Okay, so after looking at your demo, there's a couple things you can do.

The easiest method is to simply float #block-block-16 right, float .page-header left, set #block-system-main to clear: both, and be done with it.

But that's not great because we are kinda circumventing div.region.region-content by doing that. It'd be better if the header and the buttons actually shared a common parent. That seems to be what you truly want to do here. We can accomplish that with some JavaScript. That will also help with the minor problem the first solution introduces of having your gray underline not stretch across the page.

$(function() {

  $('#block-block-16').insertAfter($('h1.page-header'));
  $('#block-block-16, h1.page-header').wrapAll('

');

});

From here, again we'll just float the buttons right and the page header left as before.

We can also take care of some details and clearfix the new div (included in the JS) and perhaps change our bottom border from being set on the h1 to being set on our new div, so that it stretches across the page, below the header and buttons.

You may also choose to remove the 9px padding-bottom on the h1 and instead change that to a 9px padding-top on div.region.region-content.

Hope that helps!


Semver, core_version_requirement and update hooks I have read a little bit about using semver for contrib modules in the updated documentation Transitioning from 8.x-* to semantic versioning and Drupal.org release version numbers allow semantic versioning. While I do understand that we need to tag these branches & releases incrementally based on your current 8.x version, how is this taken into practise?

My module for example is considered compatible for both Drupal 8 and 9, tagged with a release 8.x-2.1 on branch 8.x-2.x. So would I switch to a new branch 3.x and tag 3.0.0, or can this tag be on the same 8.x-2.x branch as they are essentially running the same codebase? Otherwise I have to apply all bug fixes and changes onto 2 branches.

How would this work in conjunction with the core_version_requirement key, as I believe semver is only supported starting from Drupal 8.7.7 core version?

And finally if I am able to use the same codebase for either semver or without, how would this work with update hooks or are they maintaining the same format?

I wouldn't use semantic versioning just for the sake of using it, especially since using it on drupal.org forces you to increase the major version number. Changing major version number means the new version is not compatible with the previous one, which also means the codebase diverges significantly (or it will diverge significantly).

core_version_requirement key require Drupal 8.7.7, while semantic versioning requires Drupal 8.8.3, as previous Drupal versions don't handle them, which means that if you are semantic versioning, you should also use core_version_requirement in the .info.yml file.
Using core_version_requirement doesn't change how semantic versioning works, and using semantic versioning doesn't change how core_version_requirement works, except that with semantic versioning I would set core_version_requirement to ^8.8.3 || ^9, at least.


Modifying CKEditor toolbar at runtime We have a requirement that our standard CKEditor toolbar omit a specific button on only one content type. It seems silly to create a brand new text format just for this. I'm able to modify the toolbar via a hook, but the modification gets saved and applied everywhere.

How can I programmatically modify the toolbar for just that content type?

I think you will have to do this at the CKEditor level.  See:

https://ckeditor.com/docs/ckeditor4/latest/guide/dev_configuration.html#defining-configuration-in-page

On the Drupal side, this JS could be added by altering the content type edit form to add the JS.


Webform draft share link I would like to create a webform which accepts input from two parties. First party fills out part of a form and share a link with second party to proceed with the rest.

I have found 'save draft' feature useful for this service but only loads pre saved info for the same person. Is there anyway I can share a link (based on sid) so that whenever the URL has a SID parameter, it loads pre saved info?

Thanks

I was thinking of creating a custom module that creates form 1 which saves the info in DB tables with a unique value of SID.

Form 2, which has url of /example/% the variable % being the sid.

loads info from db using the url parameter.

$sid = request_path(); // gets the current page url. ex: example/sid
$sid = str_ireplace('example/','', $sid); // removes the example/ from our variable, so we are left with sid

Now that you have the sid inside $sid, you can query the db to grab your fields.

EX:

$field1 = db_query("SELECT field1 from {table_name} WHERE sid = :sid LIMIT 1", array(":sid" => $sid))->fetchField();

PS: In case you are wondering why the mysql query looks the way it does, see Writing secure code and How do I get only one result using db_query()


Restrict delete operation on a node referenced by another node I am using References module to make a node reference in my course content type that reference to school content type (a course belong to one school and a school have many courses).

Now what I want is if I'm going to delete a school, the delete operation will not be completed if the school referenced by any courses.

I've read hook_node_delete() and hook_delete(), written them in my custom module, tried to dpm($node) but no use!

function mymodule_delete($node) {
    dpm($node);
}
function mymodule_node_delete($node) {
    dpm($node);
}

The school node still be deleted!

According to hook_node_info() , I create:

function mymodule_node_info() {
  return array(
     'school' => array(
      'name' => t('School'),
      'base' => 'school',
      'description' => t('A short description'),
    )
  );
}

  base: (required) The base name for implementations of
  node-type-specific hooks that respond to this node type. Base is
  usually the name of the module or 'node_content', but not always

And then in my mymodule.module:

function school_delete($node) {
    dpm($node);
}

The code still not working!

I believe you are invoking the hook incorrectly - according to the API page for hook_delete():

  This is a node-type-specific hook, which is invoked only for the node
  type being affected

Further disccussed on the Node API Hooks Page:

  Node-type-specific hooks: When defining a node type, hook_node_info()
  returns a 'base' component. Node-type-specific hooks are named
  base_hookname() instead of mymodule_hookname() (in a module called
  'mymodule' for example). Only the node type's corresponding
  implementation is invoked. For example, poll_node_info() in
  poll.module defines the base for the 'poll' node type as 'poll'. So
  when a poll node is created, hook_insert() is invoked on poll_insert()
  only. Hooks that are node-type-specific are noted below.


Block field to referene a view I am struggling to find a way for a custom block type of mine to reference a view. Basically I want a field of the block to show some of the newest articles.

Using the entity reference field and an entity reference view I must select the articles to show manually.

Is there a simple way to use the entity reference field to render the contents of a view or a view block? Or do I need to code it myself?
Thanks in advance.

You can use https://www.drupal.org/project/viewfield to reference views and even pass arguments.


Conditional mapping with Feeds Using Feeds, I am trying to import products from a source CSV.  One of the CSV columns contains the quantity of items in stock.  The goal is to map it to a product 'Stock Status' field.  If the quantity field is greater than zero, 'Stock Status' is 'In Stock'; if zero, 'Stock Status' is 'Out of Stock'.

I didn't see a Feeds Tamper plugin or combination of plugins that would work and my attempts to use Rules so far have failed.

Thank you in advance for any help.

The easiest is to just put a formula into a spreadsheet and alter your source csv.

Else you could write your own feeds tamper plugin.

Create an empty file called 'stock.inc' and place it into the feeds_tamper/plugins directory. Add this to it:

<?php
$plugin = array(
  'form' => 'feeds_tamper_stock_form',
  'callback' => 'feeds_tamper_stock_callback',
  'name' => 'Calculate stock',
  'multi' => 'direct',
  'category' => 'Other',
);

function feeds_tamper_stock_form($importer, $element_key, $settings) {
  return array(
    'help' => array(
      '#markup' => t('Sets the stock status'),
    ),
  );
}

function feeds_tamper_stock_callback($result, $item_key, $element_key, &$field, $settings, $source) {
  $field = $result->items[$item_key] > 0 ? 'In Stock' : 'Out of Stock' ;
}

Clear your cache.

I have not tested this but I believe it will get you close.


Changing user picture HTML output on user profile How do I customise the HTML output for the user picture on a user profile? I can output it in user-profile.tpl.php with <?php print $user_profile['user_picture']['#markup'];?>. However this still leaves the original user picture output there too. How do I remove this? The answer in Disable displaying user picture in page--user.tpl.php won't work as that deletes $user_profile['user_picture'], which I'm using.

For an example of this, see http://dev.effectivealtruismhub.com/user/tom-ash . The top, left-floated image is the one I've manually output with  <?php print $user_profile['user_picture']['#markup'];?>. But the right floated one is the one that Drupal auto-generates, in the wrong place in the HTML to be positioned right. How can I remove this auto-generated HTML?

Hmmm, it sounds like you likely left the following line of code in user-profile-tpl.php:

<?php print render($user_profile); ?>

Remove the above line of code.

The duplicate image will go away. And so will anything else in the profile.

You'll need to add back each individual item that you actually want via the same method you used to add just the pic, but for other fields in the profile:

<?php print $user_profile['user_picture']['#markup'];?>

If you are using the Panels module, this is trivial to do without touching any code or needing to dive into the $user_profile array.


Getting first the terms starting with the string I am searching for I am using Drupal 7. I add one vocabulary in taxonomy and I am using it as auto-complete in user's registration.

Now I have a problem with how it search.

When I enter y, it shows taxonomy terms containing y, but I wanted to first see the terms that start with y.

There is module to set this settings, but this module doesn't support Drupal 7.

How can get first the terms starting with the string I am searching?

The Taxonomy Autocomplete Settings module has now a Drupal 7 version, and an official release (7.x-1.0).


View for Organic Group CCK field I'm trying to create a View that displays a CCK Imagefield from an Organic Group node.

I have a content type called 'Subsite' that I'm using as the Organic Groups creation node. I've added a CCK Imagefield called "Banner" to this content type, so that each group has a banner image.

I'm creating 'Page' nodes and assigning them to Organic Groups.

Let's say I assign a page called "Page 1" to the OG "Group 1." How can I configure a View to display the banner on "Page 1"?

In your view, you only need to bring up the node's parent group and display its banner field:

Add relationships: Organic groups: Group node (post)
Add fields: Content: Group banner, Relationship: Group node (post)


Add exposed filter for user roles In Ubercart, the uc_order view (admin/structure/views/view/uc_orders) uses exposed filters for status and order ID.

I can add another filter, for example username, email and so on by clicking on Add filter criteria and selecting the criteria (user:username, user:email).

I need to add a filter to filter orders by the roles assigned to customers. There is no option such as user:roles in the filter criteria list to select.

How can I achieve this?

By configuring the Access: section on the Page settings, we can manage Page: Access restrictions.

Choose the Roles  and assign the required user role.


The best way to list persons information I am new to Drupal and have recently started using Drupal 8. I am creating a website to act as a business profile.
One of the main content of this website is the profiles of the team members. I'd like one of the items of the main menu to be 'team members' and it should drop down into list of members.
The link of the top menu item should show a page with a summary of all members and the sub-menu items each should show a full article about a single member.

What I've tried so far is:

1- Create a user for each member, and I've added some fields as full name, etc. I'v created a view to show all users.
The problem I faced with this solution is: The view to list users cannot be seen by anonymous. The other issue is I couldn't filter this view to only show team members, for example it also shows 'admin'

2- The second approach was to create a content type called 'Team members' with fields like full name, image, etc.
I am not sure if this is the correct approach. For instance the field 'Title' is an obligatory field that doesn't make sense for a team member.

What is the correct way to add such a feature to my website.

Stick with 1: In your view at the top where it says Access: Permissions. Click on permission and change that to Role; in FILTER, add a filter of Role.


How can I display content from tab that was active on save? I'm using Drupal 8, including paragraphs.

I have a content type with a paragraph field, and this paragraph contains a fieldgroup of two fields that display in horizontal tabs.

When adding content, on save only the content in the active tab should be set to display on the page. In other words, you choose one tab or the other, add content into its designated field and save. The content in that active tab is the content that will display when viewing the page (even if there is content in the other tab).

How can I display the content from only the tab that was active on save?

Add a text field OR boolean field to your content type, let's call it "Active Tab".

Using jQuery you can make it when tab x gets clicked, it auto fills the text field OR auto checkmarks the x boolean box. (You can hide this field with CSS if you want).

Use a template file to control the display/output. So simply in your twig template file perform an conditional statement

{% if content.field_active_tab.0 == 'x' %}
  {{ content.field_something }}
  {{ content.field_something_else }}
{% endif %}

{% if content.field_active_tab.0 == 'y' %}
  {{ content.field_something2 }}
  {{ content.field_something_else2 }}
{% endif %}


How do I save session data for the anonymous users? In my last project for Drupal 6, I did save the data using code similar to the following one:

$_SESSION['xxx'] = serialize($data);

In Drupal 7, it doesn't work.

How should I save the session data for the anonymous users, in Drupal 7?

It because drupal save session with key, this mean you should do something like

  $_SESSION['yourkey']['xxx'] = serialize($data);

You can try this.

function lists_session($key, $value = NULL) {
  global $user;

  static $storage;

  // If the user is anonymous, force a session start.
  if(!user->uid) {
    drupal_session_start();
  }

  if ($value) {
    $storage[$key] = $value;
    $_SESSION['lists'][$key] = $value;   // I use 'lists' in case some other module uses 'type' in $_SESSION
  }
  else if (empty($storage[$key]) && isset($_SESSION['lists'][$key])) {
    $storage[$key] = $_SESSION['lists'][$key];
  }
  return $storage[$key];
}

So, to save a variable in Session:

lists_session("xxx", serialize($data));

And to retrieve the value, just use:

$myVar = lists_session("xxx");

and aslo as MOLOT mentions sometimes session not stareted for anonymous users then you should drupal_session_start() manually.


Not_compatible_with_d7 after installing User Points Contributed modules does anyone know why it displays 'Not_compatible_with_d7' beside a number of modules in the User Points Contributed modules project after install as though it was a missing module even though they all say they are compatible with D7 (and they installed fine).

The reason you see that error message is that the content of the votingpoints.info file is the following one.

name = Votingpoints
description = Rules integration for users earning points as they vote on nodes. With the rules approach, the node author can be assigned userpoints too.
package = Userpoints
dependencies[] = userpoints
dependencies[] = rules
dependencies[] = not_compatible_with_d7
core = 6.x

not_compatible_with_d7.module is reported as dependency of the module, and Drupal tells you that module doesn't exist.

What happened is that a Drupal 6 module has been committed in the Drupal 7 branch of the project; in this way, who wants to port the module for Drupal 7 can easily create a patch for the Drupal 7 branch of the project. The problem is with the script creating the archives containing the code of a Drupal.org project adds the like "core = 7.x" overriding the "core = 6.x" line added to the votingpoints.info file. This would cause Drupal to think the module is compatible with Drupal 7, which is not true.

The only workaround the authors of the modules found was to add, as dependency, a module that doesn't actually exist. That is the only thing that can be done, until the packaging script used from Drupal.org overrides the line reporting the Drupal version with which the module is compatible.


How to create custom access permissions for entity form I am using Entityforms on my site. I want to be able to create custom access permissions, which would prevent users of role 'member' from submitting more than 2 submissions. I am fine doing this programatically, but I haven't yet found a good way of doing this.

I tried using the hook_entityform_access_alter, but I dont see where its called. I tried printing some dpms and they never showed up anywhere:

/**
* Implements hook_entityform_access_alter().
*/
function wai_scholarship_access_entityform_access_alter(&$access, $op, $context) {
 dpm($access);
 dpm($op);
 dpm($context);
}

The reasons the dpm()'s in your hook are not showing is that this hook function is not being called when you access the form as an administrator (administrators bypass all access restrictions). I tested this for authenticated users, and it does work. The hook is called as expected. (To test it yourself be sure to allow devel permission to the authenticated user so that you can see the output of the dpm).  The hook is being called when a user accesses the form.


Can a Drupal Site Administrator view contents of settings.php or some other file in file system? We are using Drupal 8.6.3.

I want to store some configuration in file system (in settings.php or some other file outside Web Root).

Can a Drupal Site Administrator view that configuration?

What parts of settings.php file can be viewed by a Drupal Site Administrator?

For brevity, it helps to think about this question in terms of roles/permissions (since "site admin" is an overloaded term):

Does the ____ role have an escalated permission to:

Write arbitrary files to the server?
Execute arbitrary code on the server?

If the first/second answer is "Yes," the answer would be:

____ role could probably come up with a clever way to read the entire contents of settings.php by injecting/running arbitrary code.

Generally, Drupal core tries to signal these potentially dangerous permissions with this warning:

  Warning: Give to trusted roles only; this permission has security implications.

However, there are many contrib modules out there that could have exploits (some known, some not) so you'll always have to take pro-active security steps like the principle of least privilege (if a role doesn't need a privilege to do the job, don't give it to them).

This also applies to your whole system (DB, web server, etc.), not just Drupal.


How to make Title Filed Required I have migrated my Drupal 7 website to Drupal 8. The content types are showing title as optional and when we save a node without adding the title it's giving the fatal error.

How can we make the title field compulsory?

Note: I know title field is required by default, and it is required by default in my Drupal 7 site. But after migrating the site to Drupal 8 it's not showing required. Is it possible if export content types configuration from my new site and edit the configuration and import them again to fix this issue?

You can indeed edit the exported config and then re-import it to make the title field mandatory.

Always be careful when editing config directly.

The config files generally follow the naming convention core.base_field_override.<entity_type>.<bundle>.title.yml.

There should be a required key which is set to false. Simply change false to true, save and then re-import your config.


Providing a vocabulary in a custom module I am about to create a module which provides a ready-to-use term vocabulary.

What would be the clean, Drupal way to do that? Is it just a matter of a bunch of queries in hook_install(), or should I perform some additional steps? Should I take any measures in order to make the terms translatable?

I am using Drupal 7.

You should make use of the taxonomy module's functions such as taxonomy_save_vocabulary() and taxonomy_save_term() (Drupal 6), or taxonomy_vocabulary_save() and taxonomy_term_save() (Drupal 7) to populate your custom vocabulary. Creating fields should be accomplished via the Field API. There really should be no need to directly interact with the database.

Term translation is not supported out of the box in Drupal 7, but I do believe that the internationalization module provides a module that has cobbles together support for it.


Problem In Adding Flexslider To Slideshow Hello i Have Create A Views Slideshow Using Views And Jquery Cycle But I Am Installing Flexslider Module But I Can Able To See A Slide Sidebar I Am Also Placing The Flexslieder Into Libriaries

Check My Link Adclof.com

Make sure you use the flexslider module with views integration, views slideshow and flexslider views style are different modules. They each provide a different style for your view!


What's the use of creating another CKeditor profile CKeditor comes standard with 2 profiles: one for filtered html, and one for full html. Now I added a third one, but whats the use?

There are only 2 text format.. So why is it possible to create a third ckeditor profile?

Because it's also possible to create as many/few text formats as you want...

If you had installed Drupal using a non-standard profile, you might not even have full_html and filtered_html as text formats, and the CKeditor profiles would be different.

If you don't know why you need to add one...don't add one :)


Drop Down Menu in Alphabetic Order I have a Drupal Website and a few Drop Down Menus in there which comprise of a list of products.
However , the list of products does not appear in alphabetic order.
I tired "reset to alphabetical" for setting them in alphabetical order, but it did not work .
Can anyone help ? !
Thanks !

In drupal 7 there are a view having name Taxonomy term (A view to emulate Drupal core's handling of taxonomy/term). Enable that view and sort that view result according to title of content.

Note:
Enable module View UI if already not installed.


Field twig template : override HTML output Still converting my D6 theme to D8 and I need to override the HTML output for a custom field in a node twig template.
After some readings, I don't find an example for this.
My field contain files and I want them to display in a HTML list instead of a div + span.
So I created a file named field--field-fichier-joint.html.twig and added inside the code from this post , but I get a WSOD.
This is my actually code:

{% extends "@stable/field/field.html.twig" %}

{# Create classes array #}
{% set classes = [] %}

{# BEM inspired class syntax: https://en.bem.info/
   Enable this code if you would like field classes like "article__tags", where article is the content type and field_tags is the field name.
{% set classes = classes|merge([
  bundle ~ '__' ~ field_name|replace({'field_' : ''})|clean_class
]) %}
#}

{% set attributes = attributes.addClass(classes) %}

{#
  Ensures that the visually hidden option for field labels works correctly.
  @todo: Remove when https://www.drupal.org/node/2779919 is resolved.
#}
{% set title_attributes = title_attributes.addClass(label_display == 'visually_hidden' ? 'visually-hidden') %}

  {% for item in items %}

{{ item.content }}

  {% endfor %}

If someone can help me.
Thanks

EDIT: 4k4 solution work fine but I need to add some classes and I saw a very smart solution but I need help to use it. This is here

EDIT2: adding classes work but how can specify which one to apply to an element ?
Then when I want to add some flexibility to the code with this:

{# Définition des variables et classes #}
{%
  set classes = classes ?: [
    'field',
    'field--' ~ field_name|replace({'field_' : ''})|clean_class
  ]
%}
{% set wrapper_element = wrapper_element ?: 'ul' %}

{% set element = element ?: 'li' %}

{# Mise en forme sortie HTML #}
<{{ wrapper_element }}{{ attributes.addClass(classes) }}>
  {% for item in items %}
      <{{ element }}>{{ item.content }}</{{ element }}>
  {% endfor %}
</{{ wrapper_element }}>

I get Multiple items like this, why ?:

< Un fichier joint pour test Autre fichier test > Un fichier joint pour test Un fichier joint pour test Autre fichier test > < Un fichier joint pour test Autre fichier test > Autre fichier test Un fichier joint pour test Autre fichier test >

2- Adding classes
I want to add classes to my HTML output, in particular, the odd/even and I found this code but only odd class is applied:

{%
  set li_classes =  classes ?: [
    'field__li',
    'field--' ~ field_name|replace({'field_' : ''})|clean_class,
    'ligne__' ~ cycle(['odd', 'even'], loop.index0),
  ]
%}

then, my li classes inherit from ul classes, how can I avoid this ?
This code work better but the cycle loop result is out of the class..

{{ item.content }}

render:

EDIT: the Final code

{# Les classes a jouter à la liste UL #}
{%
  set ul_classes = classes ?: [
    'field__ul',
    'field--' ~ field_name|replace({'field_' : ''})|clean_class
  ]
%}

{# Mise en forme HTML #}

  {% for item in items %}
      {# Les classes a jouter aux lignes LI #}
{%
  set li_classes =  classes ?: [
    'field__li',
    'field--' ~ field_name|replace({'field_' : ''})|clean_class,
    'ligne__' ~ cycle(['odd', 'even'], loop.index0),
    ]
%}

{{ item.content }}

  {% endfor %}

You only need the twig content between <ul> ... </ul>. The variables you set  are not used anywhere. And you don't need to extend the field template from the base theme to override it. Only if you want to replace twig blocks.

field--field-fichier-joint.html.twig

{%
  set classes = [
    'class1',
    'class2',
  ]
%}

<ul{{ attributes.addClass(classes) }}>
  {% for item in items %}
      {% set zebra = cycle(['odd', 'even'], loop.index0) %}
      <li{{ item.attributes.addClass(zebra) }}">{{ item.content }}</li>
  {% endfor %}
</ul>

If you still get an WSOD enable error reporting to see in which file and line number the error occurs.


getting a target_id value for for users in particular node drupal 8 i want to display a taget_id values for user in node's field but i can't print them , this is what I have done in the hook :

 $node = \Drupal::routeMatch()->getParameter('node');
  if ($node && $node->bundle() == 'MynodeType') {
    $members = $node->field_members->getValue();
    $members_ids = [];
    $current_user = \Drupal::currentUser();
    $user_id = \Drupal\user\Entity\User::load($current_user->id());

    foreach ($members as $member){
      $members_ids[] = $member['target_id'];
      echo $members_ids; // why this is not like (1,8,....)?
    }

Looks like this one has to be solved this way

  $members = $node->field_members;
  foreach ($members as $member) {
      $members_ids[] = $member->getValue()['target_id'];
  }


Is there a way to hook rebuild permissions? I'm working on a module that works with nodeaccess_userreference, I have to add some actions to the rebuild permissions function of the core.
Is it possibile?

For Drupal 7, the submit handler for admin/reports/status/rebuild is node_configure_rebuild_confirm_submit, which calls node_access_rebuild.  Just note that node_access_rebuild can take a while (and why it support batch mode).


Which drupal hook to implement to react on module installation? I have module A installed that defines some custom hooks. Module A wants to be notified when another module B is installed, so that it can inspect and see if module B implements its hooks (for building a cache of some info for example).

Is there a hook like "hook_module_enabled($module_name)" ?

You should do it the other way around.

When your module is enabled, it should check for other modules that has implemented it's hook and call them to build up the cache you need.

Then you could create an API function for other modules to call when their module is activated.

It makes more sense to build it like that. You never know when the cache is reset anyways, so you can never rely on having a complete cache data all the time anyways.

Another solution would be to build the cache when it's needed. It doesn't make sense to build the cache data before it's actually needed. The normal thing to do with cache in drupal is to check if the cache data is there, if it's not create it and save it in the cache for next time. That would spare you the headache of trying to know all.

To answer your question, there is to my knowledge not a way to hook into the process of modules being installed / enabled.

Update:
For Drupal 7 there have actually been created a hook to react on modules being enabled: hook_modules_enabled()


Composer installation of drupal console missing functions I've been attempting to install drupal console for the first time ever. I was looking for a means of creating boiler plate modules, blocks etc.

My issue is when I have finished the installation process, the following list of functions seems incomplete according to everything I have read online. Incomplete because there is only one generate function and nothing to generate blocks, modules etc:

Available commands:
  about                        Displays basic information about Drupal Console project
  chain                        Chain command execution
  check                        System requirement checker
  exec                         Execute an external command.
  help                         Displays help for a command
  init                         Copy configuration files.
  list                         Lists all available commands
  server (serve,rs)            Runs PHP built-in web server
 database
  database:add (dba)           Add a database to settings.php
  database:client (dbc)        Launch a DB client if it's available
  database:connect (dbco,sqlc) Shows DB connection
  database:query (dbq,sqlq)    Executes a SQL statement directly as argument
  database:restore (dbr)       Restore structure and contents of a database.
 debug
  debug:chain (dch)            List available chain files.
  debug:dotenv                 Debug Dotenv debug values.
  debug:settings (dse)         List user Drupal Console settings.
  debug:site (dsi)             List all known local and remote sites.
  debug:update:composer (duc)  Displays current updates available from the composer file
 develop
  develop:contribute           Download Drupal + Drupal Console to contribute.
 docker
  docker:init                  Create a docker-compose.yml file
 dotenv
  dotenv:init                  Add support and required config to work with an .env file
 generate
  generate:site:alias (gsa)    Generates a site alias.
 quick
  quick:start                  Download, install and serve a new Drupal project
 settings
  settings:set                 Change a specific setting value in DrupalConsole config file
 site
  site:install (si)            Install a Drupal project
  site:new                     Download a new Drupal project

I used the following command:

sudo composer global require drupal/console:@stable

Can anyone pleas advice me on how I can get a more complete list of functions?

UPDATE:

I don't know if this error showing as the first output when drupal is executed in my terminal, has anything to do with my issue:

 [ERROR] Class Drupal\Core\DrupalKernel does not exist.

So far my attempts to google that error have turned up no solutions.

I'm having the same issue.  Per some other posts, I've tried starting fresh

Deleted drupal/console from composer.json (in docroot)
Deleted composer.lock
Ran composer require drupal/console:~1.0 --prefer-dist --optimize-autoloader
Ran composer update drupal/console --with-dependencies

vendor/drupal/console/bin/drupal shows I've got 1.9.3, but the only generate command I get from list is gsa as shown in sisko's post.  I get the same thing in both Drupal 8.5 and Drupal 8.7.


Move code from template file to custom module I would like to move portions of code from template files to custom module. But i fail do find descriptive guide for such task. Idea is to migrate complex db queries and EntitiyFieldQuery out of the tpl.php files. For example:

$query = new EntityFieldQuery();
$entities = $query->entityCondition('entity_type', 'node')
  ->propertyCondition('type', 'predmet_clanak')
  ->fieldCondition('field_taxonomy_choose', 'value', 1 , '=')
  ->fieldCondition('field_vrsta', 'tid', 241);

$result = $query->execute();
$nodes = entity_load('node', array_keys($result['node']));
foreach ($nodes as $node) {
  print ('

');
  print drupal_render(node_view($node, 'teaser'));
  $nodelink = ltrim(url('node/' . $node->nid), "/");
  print ('
');

  $imageLink = '';
  print l($imageLink, $nodelink, array('query' => array('iframe' => 'true', 'width' => '800', 'height' => '700', 'format' => 'popup'), 'attributes' => array('class' => t('colorbox-load gumb')), 'html' => TRUE));
  print ('
');
}

This code fetches collection of nodes (when conditions are met) in custom tpl.php file. I have been advised not to create complex queries in tpl files, but do not know yet best practices to do so.

I guess, module will firstly need to know context where i want this to occur? And after i do  this in the module, do i need to pass this to the template.php first?

I think you should go through the module developer guide.

You can use hook_preprocess_HOOK() in your template.php. So if your code was placed in the node template, the hook will be themename_preprocess_node($vars) and then you can check for a particular node type and create a variable like $vars['custom_variable'] = 'the query stuff'; and this variable will be available in your template.


Problem with node_save within a loop Within an instance of hook_submit (for a custom form), I'm trying to iterate over a list of nodes, updating each of them. The general outline is

$x = node_load_multiple($nids);
$data = array(--some data--);

foreach ($data as $row) {
  $node = $x[$row['nid']];
  $node->field_some_field['und'][0]['value'] = $row['some_field'];
  node_save($node);
}

drupal_set_message('Nodes updated');

The problem I'm having is that rather than looping through the whole data array and then posting my confirmation message on the form page, Drupal updates the first node, exits the loop, and redirects to the user's home page with the message 'contenttype TITLE updated.'

Possibly relevant: I could have sworn this code block worked when the site was 7.2, but after updating to 7.23 I'm seeing this.

To summarize one of the comments, when you encounter weirdness with the API, you need to do two things.

First, look at the API call you are using, and see what hooks it invokes.  Then, check your code for any hook implementations that could cause the weirdness.  In this case node_save() invokes a few: hook_node_presave(), hook_entity_presave, hook_node_update, and hook_node_update for nodes that exist.

Second, you need to check any Rules that are attached to the the API call you are doing.  In this case, you would check for rules that run when nodes are saved.

Doing these two things will usually lead you to the problem.


$base_url not working when in anchor link to theme folder e.g. this:

<a href="<?php echo $front_page; ?>" title="<?php echo t('Home');?>" rel="home" id="logo">

is working.

But this is not:

<a href="<?php echo $front_page; ?>" title="<?php echo t('Home');?>" rel="home" id="logo">
        <img src="<?php echo $base_url; ?>/sites/all/themes/jamestheme/images/logo.jpg">

Can someone explain why?

I am using Drupal 7 and this code is in page.tpl.php

Try this...

In your themes template...

function YOURTHEME_preprocess_page(&$variables) {
   global $base_url;
   $variables['base_url'] = $base_url;
}

In page template...

$base_url;


Drupal Commerce Need Function To Retrieve Customer Profile Fields From Commerce Order I want to display some info from the Customer Profile (Customer Number, Contact Number) whenever the shopping cart view displays. I can see these fields in 'People' but obviously they are -extended- fields... when I run this:

$my_user = user_load( $user->uid );

...I get the field names for the data I want, but not the values.

I -thought- I could do this...

$order = commerce_cart_order_load($user->uid);

...and then somehow get to the customer_profile like so:

commerce_customer_profile_load ($profile_id);

...but I have no idea how to connect the $order or the global $user->uid with the $profile_id

How does one do this?

Again, I just need to retrieve the string values of Customer Number and Contact Number.

TIA,

---JC

There are probably a few different ways to bridge that gap but here are the first 2 that spring to mind:

Use commerce_customer_profile_load_multiple instead, and make use of the $conditions parameter, e.g.

$profiles = commerce_customer_profile_load_multiple(array(), array('uid' => $order->uid));

foreach ($profiles as $profile) {
  // Make sure this is the correct profile (users can have multiple profiles)
  // and extract the field values as you would with any entity (field_get_items())
}

But the $conditions array is deprecated for core entities so probably will be for commerce entities too at some point.
Use an EntityFieldQuery to get the profiles, e.g.

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'commerce_customer_profile')
  ->propertyCondition('uid', $order->uid);

$results = $query->execute();

if (!empty($results['commerce_customer_profile'])) {
  $profiles = commerce_customer_profile_load_multiple(array_keys($results['commerce_customer_profile']));

  foreach ($profiles as $profile) {
    // ...
  }
}


How to use the value of a field in a filter criterion? I created a comment view.

The parent content can be flagged and I want to display the comments posted since the date of the flag.

I added a hidden field "Date of creation of the flag".

I added a filter criterion (is greater than or equal to) "Date the comment was posted".

How to use the value of the flag in the filter criterion "Date of publication of the comment" ? there is no token and I have not found a module that can do that.

You could write a custom Views filter plugin to handle your use case, I have found WebOmelette's tutorials invaluable over the years, and he has a great one for D8 Views filters: https://www.webomelette.com/creating-custom-views-filter-drupal-8. This will allow you to fine tune the query to your needs and do any kind of filtering that isn't available out of the box.


A disabled module has a schema version of -1, how can I enable the module and then run DB updates using hook_update_N? The problem is, it seems when I enable a disabled module, the module's schema version in the system table is automatically updated to the latest version supplied by hook_update_N.

So my current module with the schema version -1 is modified to 7106 when I enable the module, and no hook_update_N functions are run.

So when I come to the next step of running database updates, no hook_update_N functions are run because the module thinks it's already the correct version.

The only method I can see is to manually set the module version in hook_enable, however I'll then need to update the module code to remove the hook_enable to make sure it doesn't run if the module is ever re-enabled in the future, so obviously this approach is a bit dirty.

I'm hoping there's a better solution?

Disabling a module should not set the schema_version to -1. -1 means SCHEMA_UNINSTALLED. As the constant says, it means this module has never been installed.

A module that has not been installed before is not supposed to run updates. hook_schema() is supposed to contain the current state of a module's schema. So this behavior is correct, and you should not mess around with the schema version manually.

If disabling (not uninstalling) a module really does set the schema_version to -1, then that's where things go wrong. But Drupal core isn't doing this, see module_disable().

Also, note that Drupal executes updates for all installed modules, no matter if they're enabled or not.


Modal forms dropping # in the address I have made neat comment link for anonymous users http://example.com/modal_forms/nojs/login?destination=http://example.com/comment/reply/NID#comment-form
However when I click it then the #comment-form is missing and it's very inconvenient because have to scroll to the comment form, how to fix it?

Here's the code responsible for opening login links in modal window:

Drupal.behaviors.initModalFormsLogin = function (context) {
  $("a[href*='/user/login'], a[href*='?q=user/login']", context).each(function () {
    this.href = this.href.replace(/user\/login/, 'modal_forms/nojs/login');
  }).addClass('init-modal-forms-login ctools-use-modal ctools-modal-modal-popup-small');
};

Unless you URL encode, the fragment (what you have after the # sign) is not sent to the server.

If you want to include the hash in the destination parameter, it has to be URL encoded.

  http://example.com/modal_forms/nojs/login?destination=comment/reply/NID%23comment-form

Note the %23 above. It makes the browser think that the fragment is part of the destination parameter.


How can I have two nodes of different content types update to each other? I have two different content types(A & B), and I want to be able to have a field in content type A that is a select list of all the nodes from content type B, and then I want to have a field in content type B that is a select list of all the nodes from content type A.
Is there a way that I can have those two fields update each other?

Ex: in node 'Atest' from content type A in the select list field I select the 'Btest' node from content type B, and then if I edit 'Btest' in it's select list field I can see 'Atest' already selected. (showing that 'Atest' has it selected)

Is that possible? if so, what would be the beat way to go about setting that relationship up?

You can try Corresponding node references.

I used this to sync up Events and Venues on one of my sites, and whenever I switch a venue for an event it automatically changes the node reference on the other node, so I only have to change the node reference once, instead of twice. Keeps things tidy, works with multiple.


Making an Entityform field required using jQuery I have an Entityform and defined dependencies to where if a particular value is selected from one of the drop downs, the resume field (file upload) should be required.

I don't know why, but it's currently not working. It marks the resume field as required, but still lets the application submitted with no error.

I noticed all the required fields (that do work) have a class of required in their markup. Is it possible I can do this in jQuery? Meaning that I check that dropdown and if a certain value is selected, I'll add the required class to the file upload (resume) field.

Javascript can only handle soft (client-side) validation, unless you start looking into AJAX validation.

You need to alter the form on the server side to ensure that the data is validated properly - never rely on JS validation, it should only be used for UI/display purposes, and form data can easily be overridden by the user.


What is the best way to track unique and overall clicks at my newsletters I send newsletters from my Drupal-7 website and I want to track how many times the links where clicked and how many unique click events I had.

I use Simplenews module and I use some basic GA utm parameters, but the results I get are not satisfying. What do you suggest I use. Is there a method, or a way to get that? Everywhere I search there is not a valid answer to my question.
Thanks in advance.

I would suggest checking out https://support.google.com/analytics/answer/1033867?hl=en as it will help you build a link you can put in your newsletter that when clicked takes the person to whatever page you direct them to, but has analytic code built into the link so that you can track how many and how often it is used. Total sessions and unique users will both be tracked.


How to handle pdo exception error gracefully for user experience Integer fileds can accidentally be entered with 'Out of range' error. This time a user has no other option but to click back button.
Any suggestions on templating these kinds of errors or for any other errors of the same nature?

What? ... add a custom FAPI validator to your forms so there is no out-of-range error.

You could build on, or start off by using:
http://api.drupal.org/api/drupal/includes%21form.inc/function/element_validate_integer/7


Drupal Views: Get all of x categorised by y Is this possible?

I have products and each product has a list of associated downloads. I would like to output all downloads (an index of downloads if you like) but split by headings of each product.

Product A
• Download A
• Download B
• Download C

Product B
• Download D
• Download E
• Download F

Can I get this through Drupal Views?

Update:

Just to give anyone seeking the same solution a helping hand...
In views Advanced turn Use Aggregation on.

Add the fields you would like to use.
The aggregation settings automatically pop up after adding a field. For Associated Product, I chose Group By.

Then in the Format (HTML List) settings, choose group by Associated Product.

I haven't learned how this works myself yet, so I can't give you an exact answer, but here's a video tutorial on Using aggregation in Views, which should answer this for you.


form submission in Drupal i have made a custom module for form in drupal using dupal API,and made a table in my database...now What i want is to save the value of drop down box instead of it's index into database...my .module file is:

<?php
function form_test_menu() {
$items['formtest'] = array(
'title' => 'Form Test',
'page callback' => 'drupal_get_form',
'page arguments' => array('form_test_form'),
'access callback' => TRUE,
);
return $items;
}
function form_test_form($form,&$form_submit) {
$form['name'] = array(
'#title' => t('Name'),
'#type' => 'textfield',
'#required' => TRUE,
);
$form['college'] = array(
'#title' => t('College/University'),
'#type' => 'textfield',
'#required' => TRUE,
);
$form['education'] = array(
'#title' => t('Education'),
'#type' => 'select',
'#description' => 'Select your higher education .',
'#options' => array(t('--- SELECT ---'), t('B.tech'), t('MCA'), t('MBA'),t('Graduate')),
'#required' => TRUE,
);
$form['percentage'] = array(
'#title' => t('Percentage/CGPA'),
'#type' => 'textfield',
'#required' => TRUE,
);
$form['application'] = array(
'#title' => t('Job Applied'),
'#type' => 'select',
'#options' => array(t('---select---'),t('Web Developer'),t('Web Designer'),t('SEO'),t('Marketing')),
'#required' => TRUE,
);
$form['submit'] = array(
'#value' => 'Submit',
'#type' => 'submit',
);
return $form;
}
function form_test_form_submit($form, $form_state) {
global $user;
db_insert('drupal')
->fields(array(
'name' => $form_state['values']['name'],
    'college' => $form_state['values']['college'],
    'education' => $form_state['values']['education'],
    'percentage' => $form_state['values']['percentage'],
    'application' => $form_state['values']['application'],

))->execute();
drupal_set_message("successfully saved data");
} ?>

any help will be appreciated. Thank you.

I think the easiest way to do this would be to make the key the same as the value.  For instance:

$form['education'] = array(
  '#title' => t('Education'),
  '#type' => 'select',
  '#description' => 'Select your higher education.',
  '#options' => array(
    '_none' => t('-- SELECT --'),
    'B.tech' => t('B.tech'),
    'MCA' => t('MCA'),
    'MBA' => t('MBA'),
    'Graduate' => t('Graduate')
  ),
  '#required' => TRUE,
);

You need to pass values in associative array


How do I detect whether any contact forms have been created? Context: On my Drupal 8 site I'm trying to add in a new section containing a view that lists out all forms. The user can then click on one of the form and it launches a download of all the messages sent through that form. However that section should only be visible if the user has created at least 1 form.
What I've tried: So far what I've discovered is that the contact forms are stored in the config table in the database, so I could theoretically run a query like "SELECT 1 FROM config WHERE name LIKE '%contact.form%'" or whatever the equivalent in D8 is. However, it seems like there has to be a quicker way to return either the presence of contact forms or the contact forms themselves programmatically.
Final question: How can I return either the contact forms themselves or at least a boolean representing the presence of contact forms programmatically?

You can use the D8 config factory interface to retrieve multiple contact form config keys and their corresponding config entities:
$contact_form_keys = \Drupal::configFactory()->listAll('contact.form');
$contact_form_configs = \Drupal::configFactory()->:loadMultiple($contact_form_keys);


how to found out if a custom hook_cron has been run? what is the best way to find out if a custom hook_cron which runs automatically , has been run?
I did use drupal_set_message and watchdog but they weren't suitable for automatic crons.

When Cron runs, it leaves a message in the next table: Reports -> Recent log messages.

If you want to know if a specefic hook has been run, you could try an experiment. For example, you could create a variable called module_variable with value 0 in your  database table and increment this value each time the hook is run.


Notice: Undefined index: main_profile in include() (line 54 global $user;
$user->uid ;
print_r($user->uid);
print "print out the user value" . $user->uid;

$uid =3;

$account = user_load($user->uid);

$profile = profile2_load_by_user($account);

$print_first_name =  drupal_render(field_view_field('profile2',$profile['main_profile'], 'field_first_name'));
print $print_first_name;

What I have attempted to do is to pass the $user->uid to the user_load function.
When I pass $uid = 3 to the user_load function it seems to work fine. I am wondering what approach I should try to fix this problem.

error message:

EntityMalformedException: Missing bundle property on entity of type profile2. in entity_extract_ids() (line 7562 of /home/td6/public_html//includes/common.inc).

Your mistakes is here main_profile , profile type always start with profile_name . just need change main_profile to profile_main

global $user;
$user->uid ;
print_r($user->uid);
print "print out the user value" . $user->uid;

$uid =3;

$account = user_load($user->uid);
$profile = profile2_load_by_user($account);

$print_first_name =  drupal_render(field_view_field('profile2',$profile['profile_main'], 'field_first_name'));
print $print_first_name;

If you want see all your profile type and correct name and it's contents print_r or var_dump $profile

$profile = profile2_load_by_user($account);
print_r($profile);


Multisite path issue Our multisite is having issues.

we have a subsite called /wikifix
some of the URLs in this subsite are /wikifix/wiki/...

now we have another subsite called /wiki.
as soon as we make our symlink, the pages on /wikifix that have wikifix/wiki/ in their path start giving drupal page not found errors.
Testing on another subsite in the multisite /kids shows similar issues, /kids/wiki also gives page not found errors

both sites work and are accessible, the issue is only when the path contains the name of a different subsite.

the two issues causing this were both in the .htaccess:

this line was commented out:

RewriteBase /

and then we had to add this per subsite:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteCond %{REQUEST_URI} ^/wikifix
RewriteRule ^ wikifix/index.php [L]

including the first 3 rules:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteCond %{REQUEST_URI} ^/wiki
RewriteRule ^ wiki/index.php [L]

since both subsites start with /wiki, it was also important to have the RewriteCond for wikifix BEFORE the RewriteCond for wiki


Child & Grand Child terms of Parent Term from URL I am looking for a way to display both the Child and Grand Children of a taxonomy term (found on the URL) on the same page.

Example Taxonomy called Food. Top root term called GRAPE has children and grandchildren like this.

-Grape

--Red

---Small

---Medium

---Large

-- White

How can we create a view (block in our case) that will always show the children and grandchildren of the parent term from URL?

I am guessing one or two contextual filter where the filter takes the taxonomy term ID Raw from the URL.

Example: doamin.com/fruit/grape/,

therefore, parent will be second in path. The parent term in this case is Grape.

So in the block we will show children and grandchildren of Grape:

--Red

---Small

---Medium

---Large

-- White

Ideally grouped by RED, WHITE.

Apply the contextual filter to a second filter? Not sure, I am just guessing.

You can create a Block that displays Child and Grandchild terms (in terms of hierarchy within a Taxonomy Vocabulary) on a taxonomy term pages with the use of an additional module Views Contextual Filters OR to tell the Views to show children OR grandchildren.

Contextual filters always work with the AND operator, so this module is necessary to loosen that circumstance.

Create View of type Taxonomy term
Filter it to show only the Food Vocabulary
To show Children of a term on that term page we can use the Parent term Contextual filter with these options:
When the filter value is NOT available
Provide default value
Taxonomy term ID from URL
Load default filter from term page
When the filter value IS available or a default is provided
Specify validation criteria
Taxonomy term ID
Food

Now if you enter a term ID into Preview you will see the Child terms of that term. This takes care of the Parent-Child.
To filter Grandchildren we have to introduce that level of connections into View. Add the Parent Relationship
Add another Parent Relationship and make it use the first one, this is how we get Grandparent info
Add a new Contextual filter Term ID and make it use the second Parent Relationship and other options the same as above.

Now if you enter all/[TID] you will see the grandchildren terms of the [TID].
To make the Contextual work with OR go to Query settings and enable Contextual filters OR option.

To test enter the term ID twice into Preview [TID]/[TID].
Add the Field Name from the Taxonomy term Category and make it use the first Parent Relationship (that is the Parent, not the Grandparent), you can Exclude it from display later
Under Format Settings set the Grouping field Nr.1 set the Parent field (you might want to use the HTML List as the Format)

The results will show the grandparent first and its children, then grandchildren under their parents.

If the grandparent showing their children is not necessary for you, which it probably isn't, because it will be implied from circumstances by being on the grandparent page, you can edit the Filter from step 2 and make it use the second Parent Relationship, this will only show Grandchildren grouped by Parents.

Place the Block in a region and limit the Pages to /taxonomy/term/*.

Alternatively you'd have to use Views Field View to insert one view into another, which can be performance heavy. I'm not sure how the above compares, it does use some LEFT JOINs too which aren't so performance friendly.


CSS and Js not loading with https I'm trying to put my entire website under https connexion, but my css and js are not loaded. I don't know why.

I had this code to the htaccess at the root of the website :

  # Force HTTPS and WWW
  RewriteCond %{HTTP:HTTPS} !on
  RewriteRule (.*) https://%{SERVER_NAME}/$1 [QSA,L,R=301]

And didn't touch anything else. If it's relevant, I'm using a hosting from online.net (french provider).

So after researches, everything work now and here is my configuration :

I putted this code into my sites/default/setting.php file :

$conf['https'] = FALSE;
if (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on') {
  $base_url = 'https://www.efficient-network.eu';
}
else {
  $base_url = 'http://www.efficient-network.eu';
}
$_SERVER['HTTPS'] = 'On';

And needed to add a custom module to load every line in <head> </head> with https :

function https_process_html(&$vars)
{
    foreach (array('head', 'styles', 'scripts') as $replace) {
        if (!isset($vars[$replace])) {
            continue;
        }

        $vars[$replace] = preg_replace('/(src|href|@import )(url\(|=)(")http(s?):/', '$1$2$3', $vars[$replace]);
    }
}

I don't know if it's the proper method, but it works.


Getting exception 1003 when importing images via feeds module I'm importing images via the feeds module from a csv file. In the field for images, I've added the public url like so:
public://path/to/my/image.jpg

I've verified that the image exists and is available. When I try importing the feed, everything imports fine but I get the following two db errors for every image:
First error:

exception 'Exception' with message 'Download of
public://path/to/my/image.jpg failed
with code -1003.' in
/srv/bindings/c09f123e774147dcaf40119f13d240c3/code/sites/all/modules/contrib/feeds/plugins/FeedsParser.inc:424
Stack trace:
0 /srv/bindings/c09f123e774147dcaf40119f13d240c3/code/sites/all/modules/contrib/feeds/plugins/FeedsParser.inc(483):
FeedsEnclosure->getContent()
1 /srv/bindings/c09f123e774147dcaf40119f13d240c3/code/sites/all/modules/contrib/feeds/mappers/file.inc(127):
FeedsEnclosure->getFile('public://images...')
2 [internal function]: file_feeds_set_target(Object(FeedsSource), Object(stdClass), 'field_y1_rankin...', Array, Array)
3 /srv/bindings/c09f123e774147dcaf40119f13d240c3/code/sites/all/modules/contrib/feeds/plugins/FeedsProcessor.inc(800):
call_user_func('file_feeds_set_...', Object(FeedsSource),
Object(stdClass), 'field_y1_rankin...', Array, Array)
4 /srv/bindings/c09f123e774147dcaf40119f13d240c3/code/sites/all/modules/contrib/feeds/plugins/FeedsProcessor.inc(746):
FeedsProcessor->mapToTarget(Object(FeedsSource), 'field_y1_rankin...',
Object(stdClass), 'public://images...', Array)
5 /srv/bindings/c09f123e774147dcaf40119f13d240c3/code/sites/all/modules/contrib/feeds/plugins/FeedsProcessor.inc(296):
FeedsProcessor->map(Object(FeedsSource), Object(FeedsParserResult),
Object(stdClass))
6 /srv/bindings/c09f123e774147dcaf40119f13d240c3/code/sites/all/modules/contrib/feeds/includes/FeedsSource.inc(399):
FeedsProcessor->process(Object(FeedsSource),
Object(FeedsParserResult))
7 /srv/bindings/c09f123e774147dcaf40119f13d240c3/code/sites/all/modules/contrib/feeds/feeds.module(191):
FeedsSource->import()
8 [internal function]: feeds_batch('import', 'y1_rankings_pro...', '109600', Array)
9 /srv/bindings/c09f123e774147dcaf40119f13d240c3/code/includes/batch.inc(284):
call_user_func_array('feeds_batch', Array)
10 /srv/bindings/c09f123e774147dcaf40119f13d240c3/code/includes/batch.inc(161):
_batch_process()
11 /srv/bindings/c09f123e774147dcaf40119f13d240c3/code/includes/batch.inc(80):
_batch_do()
12 /srv/bindings/c09f123e774147dcaf40119f13d240c3/code/modules/system/system.admin.inc(2384):
_batch_page()
13 [internal function]: system_batch_page()
14 /srv/bindings/c09f123e774147dcaf40119f13d240c3/code/includes/menu.inc(527):
call_user_func_array('system_batch_pa...', Array)
15 /srv/bindings/c09f123e774147dcaf40119f13d240c3/code/index.php(21): menu_execute_active_handler()
16 {main}

Second error:

Invalid enclosure public://path/to/my/image.jpg

The feed used to work, and I don't think I've changed anything to break the import. What could be going wrong?

The answer was that the image wasn't found, because my path/to/my/image.jpg was incorrect on my spreadsheet, path/my/to/image.jpg.


Form Redirect before submit? I have a form which has 2 values prefilled (values come from a few steps the user has to take to be given the chance to get to the form I'm talking about).
My question is, how do I redirect the user back to step 1 when the form loads if the values are not present?
I have a hook_form_alter() and I have the logic to check whether or not the session variables are set but I cannot seem to redirect. Tried return new RedirectResponse($url) and return new TrustedRedirectResponse($url) also I've checked with the debugger to see if the returns are called and they are but the redirect is not happening and I get to the form when I should not be able to.
If it helps, it is a group/add form (normal entity adding).
Any ideas?

I'd use an Event Subscriber here. See My First Event Subscriber for an example if you're unfamiliar.
In this case, you'd want to subscribe to the Symfony\Component\HttpKernel\KernelEvents::REQUEST event. For example, you might have a getSubstribedEvents() method that looks like:
public static function getSubscribedEvents() {
  // Include Symfony\Component\HttpKernel\KernelEvents with a use statement.
  return [
    KernelEvents::REQUEST => 'myCustomMethod',
  ];
}

Then define myCustomMethod() to check for your session variables and redirect if needed. For example:
public function MyCustomMethod(GetResponseEvent $event) {
  $route_name = $event->getRequest()->attributes->get('_route');
  // I'm not sure what the route name is here. (You also don't need
  // to check against a route name, thought it's probably a good idea.)
  if ($route_name == 'GROUP_ADD_ROUTE') {
    // Check whatever to see if you must redirect.
    if (myRedirectCondition()) {
      // Set these response headers so browsers don't cache the redirect.
      $response_headers = [
        'Cache-Control' => 'no-cache, no-store, must-revalidate',
      ];

      // Build your response.
      $response = new TrustedRedirectResponse(MY_REDIRECT_URL, '302', $response_headers);
      // You'll have to determine how your redirect should be cached and add
      // appropriate cache dependencies, tags, contexts, etc. There is a
      // session cache context, but I'm not familiar with that particulars of
      // exactly how it works. Alternatively, you could use \Drupal::service('page_cache_kill_switch')->trigger();
      // inside your route_name if statement.
      $response->addCacheableDependency();
      $event->setResponse($response);
    }
  }
}

Related: Disabling Page Cache for Redirect Response


Alter ctools_ajax_command_redirect() My problem is redirect after webform submission.
So I have a webform node and AJAX on this submit button (hello "Webform Ajax").
How I do redirect:
I'm just using hook_form_alter() and add to this webform "submit" special redirect function. It must be make redirect after webform submission.
In general it works if I doesn't use the "Webform Ajax" module.
But I need use the "Webform Ajax" (Do not ask me why) I'm catching a mistake.
In code I found how the "Webform Ajax" makes redirect: ctools_ajax_command_redirect() function.
Well the QUESTION: How can I "alter" this functionality?

Any Ideas how I can make redirect after submit, thanks!

You could use hook_form_alter and unset the $form['#submit']. Then you add your own submit handler by using $form['#submit'][] = '_my_callback'; THen in your callback just copy the code of the Ajax redirect and alter it to your needs.


Get all entities tagged with term taxonomy_select_nodes returns all the nodes tagged with a given tid. This function checks the taxonomy_index table.
That table stores the tid and the nids on which it is tagged.

Let's say I have some custom entities with terms on them AND a user entity with terms on it, how do I get all the entities tagged with a given tid? Can this be done in 1 query/function?

I'm afraid not. The taxonomy index table is maintained specifically for nodes. There is no equivalent for other entities. It would be possible to maintain an index of your own though.

A workaround would be reusing the same field on different fieldable entities. Then you would only need to query the data field table to get all referenced entities.