Adjust weight for menu items in different languages My site will be in English and Arabic. English reads from left to right and Arabic from right to left. Drupal 8 works great with this if you enable all 4 multilingual extentions.

The only problem I have is that I translated the main menu, but I can't find how I can add a different weight to the separate menu items, this since I want the menu to be mirrored on Arabic.

If you go to the separate menu items you can add a weight but above it it is written: Weight (all languages)

How can I adjust the weight per language per item?

UPDATE: the answer by Owais Alam does not handle the adjustment of menu-items-weight per language in Drupal 8

With Drupal 7 core alone, user-defined menu items are not translatable. The Menu translation module, part of the Internationalization (i18n) package, allows users to select a translation mode for each menu (Figure 1).

The following modes are available:

No Multilingual Options
Translate and Localize
Fixed Language

Translate and Localize Menus

For most use cases, and especially if the structure of your menus is consistent across languages, Translate and Localize is the preferred method of translating menus. You can create one menu for all languages, and translate or localize each menu item. There are two ways that menu items will be translated:

You can set a language when creating a custom menu item so that the
menu item will only show up for that language (Figure 1). Menu items
that link to nodes in a particular language will be treated this way.
You can localize other custom menu items without a language (for
example, menu items linking to Views pages). Use the Translate tab to
translate the menu item title and description (Figure 2). Translators
can also use the 'Translate interface' pages to translate these menu
items (Figure 3).

Figure 2

Figure 3

Fixed Language Menus

If you choose Fixed Language, you'll have to set up a separate menu in each language. This could become tedious if have a lot of languages enabled on your site, but is useful if the content or menu structure is different for each language.

Menu Items Linked to Nodes

Useful modules:

For Entity translation use entity_translation_i18n_menu submodule of
Entity translation.
For content translation use Menu translation - Node.

A menu item linked to a node will be displayed only when the node language matches the page language. This is due to how the menu system works and the 'Language selection' feature in i18n. Therefore, to get translated menus items that link to nodes, you first need translated content: see Translating content to different languages.


nav arrows AROUND the blog view? nav arrows AROUND the blog view?

I've finally gotten pretty close to what I was aiming for on the recent blog entries view..
I've posted my version above and what I'm aiming for next..
I still need to change the page numbers below for nav arrows on the sides. Is there still something in the views settings I need to be looking for. I saw a place for arrows, but they are always above or below. Is it CSS to push them to either side and let the blogs settle between them?

css

 #views_slideshow_controls_text_previous_slide_show_of_members-block_1_1 {
    background: url(../sites/all/themes/twodrop/images/comment-arrow.gif);
    /* shows image */

    /* Hide the text. */
    text-indent: 100%;
    white-space: nowrap;
    overflow: hidden;
}
 #block-views-the-blog-block h2 {
    text-align: center;
}

I did find this thread under similar questions, but it seems a bit excessive.. surely a better answer has bubbled up in 4 years?

.. additional question, so it may warant a seperate thread, but I'm also trying to aling each section. Should I look at moving the title into the header and the date into the footer? Or is this better handled in CSS?

You could create the effect you're after with some clever CSS applied to the default Views pager but it doesn't seem you're very proficient at CSS, and there is a way that may help you get further without coding.

Carousel Views Format through an additional module

There are some modules that you can use to change your Views Format to output views results in a way that resembles what you want, basically a carousel navigation for your views results:

jCarousel
Slick Carousel, Slick Views
Flex Slider

Better Pager through an additional module

If you don't think that the carousel solution is good for your case you can change the Pager directly with an additional module.

Pagerer is probably your best choice, but there are others if you want to search on your own and compare. Here is a tutorial about how to use it: How to Create Fancy Pagers in your Drupal Views with Pagerer.

Additional CSS

It's not clear which header and footer you're talking about - the HTML elements? This is CSS related and best solved by using Flexbox or Grid to get the layout with equal column heights but without limiting the column height so you're covered for all content "sizes".


Single Sign On Integration with NetCommunity I want to integrate Drupal with Net Community Black Baud single sign on.

The approach/process flow is same like FaceBook Connect or LinkedIn integration for single sign on.

NetCommunity is just another sign-on site and behaves just like LinkedIn users.

But I am stuck with from where to start the implementation of this.
I have seen LinkedIn module to login with LinkedIn. But I want to know whether it can be done using oAuth library or not.

The last time I looked into BBNC (which was two or three years ago), you had to do a two-fold approach.

First, you need to write an ASP.NET webservice on the BBNC side using their API to expose login.  This may have changed since I checked it out.  Poke around the BBNC forums to see what may already exists.

Two, you wire up authenticate against a non-drupal database.  This is actually fairly easy.  I would look at the LDAP module to see how it does things.  It essentially hook_form_alter's the user_login form to add some additional validation, which checks the external database.

I would also poke through the BBNC forums to see if anyone has an LDAP, OAuth, or OpenID solution for NC.  Then you can use one of the existing solutions.  Those three modules are also good to look through for ideas on how to  do the authentication.

The question that @indrock gives is also a good read about session management.


Content From Another Page Displaying on Current Page I created a piece of content called training that is supposed to display all training content offered. Instead of displaying only training content it is displaying articles, news content within the page.

Could someone steer me in the right direction in order to solve this issue? I'm a bit new to Drupal so I am still learning my way around. Thank You.

I think we might need a bit more detail to answer your question.

Is training really a content type or a view?  Normally content is displayed inside a view unless your are viewing the actual node page.  If you are really talking about a view that you could just add a content type filter.

Also, what version of drupal are you using?  My above response assumes 7.


Field as Block column not showing I installed the Field as Block plugin without problems, but when I go to Structure > Content Types > Basic Page > Manage Display, I still don't see the "Display as block" checkbox.

I tried googling but did not find anything else that what was written on the plugin page. What am I doing wrong? This plugin would really help me.

After some more research, I found a post by nicholasThompson who was having the same problem and found out the solution:

  Ahh you have to place the "Content field" block and configure it!

This solved my issue.


The Nivo Slider library could not be found This is the first time I use a CMS, and I'm trying to install nivo slider module into Drupal. I used the following commands

drush dl nivo_slider
drush en nivo_slider -y

Then I added some pictures to the slider but they are displayed without animation

And in the status report I have the following error message

  Nivo Slider jQuery plugin Not installed
  The Nivo Slider library could not be found.

Nivo Slider Requirements

Libraries API
jQuery Update

You need to download the Nivo Slider Plugin and extract it to sites/all/libraries. The extracted folder must be named nivo-slider.


Services Module Authentication with Username and Password in URL I have to match the following format when implementing Services to maintain some legacy APIs that were poorly written. I understand this is horrible practice and we're going to provide a new better OAUTH2 option going forward but that doesn't change my issue.

https://www.example.com/service/ServiceController.svc?username=YOUR_USERNAME&password=YOUR_PASSWORD&travelCode=TRAVEL_CODE

Short of writing my own authorization module that works with Services can anyone think of a method for getting this done using existing modules and Services.

I have tried Services Basic Authentication and Secure Services and either I am missing something or they don't do what I need.

Any help would be appreciated, I really don't want to customize something if I don't have to.

By adding the following argument entries to my retrieve operation for my custom service I was able to achieve the desired effect.

                'args' => array(
                    array(
                        'name' => 'none',
                        'type' => 'string',
                        'description' => 'Function to perform',
                        'source' => array(
                            'path' => '0'
                        ),
                        'optional' => TRUE,
                        'default' => '0',
                    ),
                    array(
                        'name' => 'version',
                        'type' => 'int',
                        'description' => 'Function to perform',
                        'source' => array(
                            'param' => 'version'
                        ),
                        'optional' => TRUE,
                        'default' => '0',
                    ),
                    array(
                        'name' => 'username',
                        'type' => 'string',
                        'description' => 'Function to perform',
                        'source' => array(
                            'param' => 'username'
                        ),
                        'optional' => FALSE,
                        'default' => '0',
                    ),
                    array(
                        'name' => 'password',
                        'type' => 'string',
                        'description' => 'Function to perform',
                        'source' => array(
                            'param' => 'password'
                        ),
                        'optional' => FALSE,
                        'default' => '0',
                    ),
                    array(
                        'name' => 'id',
                        'type' => 'string',
                        'description' => 'Function to perform',
                        'source' => array(
                            'param' => 'id'
                        ),
                        'optional' => TRUE,
                        'default' => '0',
                    ),


How to check if a database is set up in settings.php? I am creating a module for Drupal 8. One of the requirements is that you first add a new database in settings.php. On the admin page, I want to check if the user did this step and show a warning if he didn't. I tried this:

global $databases;

But doing a var_dump shows nothing.

How do I access the databases variable so I can check if the database is setup?

global $databases has been removed in favor of the preexisting static connection info management methods on the Database class.

Drupal 7

global $databases;
// Check whether we have a default connection.
$has_connection = !empty($databases['default']['default']);

Drupal 8

use Drupal\Core\Database\Database;
$has_connection = (bool) Database::getConnectionInfo('default');

More links

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

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


How can I exclude folders when updating drupal using drush? How can I use drush pm_update and exclude some folders? For example, I don't want to update Sites and Profiles folders.

If you want to update Drupal core without updating contrib, use drush pm-update drupal.  Always upgrade a copy of your site and test it before modifying your production site.

If you want to avoid updating just a specific contrib project, use drush pm-update --lock=skipthis.  The lock is persistent until removed with --unlock.


Why recurring order becomes completed immediatelly after payment (no fulfillment status)? I'm using Commerce datatrans module which originally supports only offsite payments. However I added extra functionality for recurring payment and it works well.
Only issue I have is that when method createPayment() I added is called by cron job and payment is made that order gets status "Completed".
For default types of orders (non-recurring ones) they have status "Fulfillment" so when all items are shipped order status can manually be changed to "Completed". I expected same thing with recurring orders.
In createPayment() function I added code I found on official documentation for that method:
$next_state = $capture ? 'completed' : 'authorization';
$payment->setState($next_state);
$payment->setRemoteId($transaction["uppTransactionId"]);
$payment->setExpiresTime(strtotime('+5 days'));
$payment->save();

Not sure should I change order status from that method. But again some other code is changing it form "Draft" to "Completed".
So my question is why it's not changed to "Fulfillment" but to "Completed" as soon as payment is done?

So my question is why it's not changed to "Fulfillment" but to
"Completed" as soon as payment is done?

Because you're setting it to completed, the code you found is just an example.
For your case, it needs to be:
$next_state = $capture ? 'fulfillment' : 'authorization';


Using Profile 2 with Entity Reference--How to display the user name and not the "Profile Name" I've reviewed the threads similar to this, and can't seem to find a definitive answer. I have a Content Type in Drupal 7 where I want to be able to associate multiple users to a content item. For example, I have a "Music Ensemble" content type, and I want the ensemble leader to be able to select all of their ensemble members from the list of user profiles.

I've been through all the steps to configure a view with the Entity Reference Widget, and add / configure the Entity Reference field on my content type. When I go to create a content item, the View loads, displays the correct profile fields and allows me to select users.

However, when I submit the view form and return to the content UI, I get the following:

The "Main profile" text is displayed for every member I select. What I really want to display on the content item is the user's name from their profile.

I can't seem to find a way to configure around this. Is this simply a limitation of the Entity Reference / Profile 2 relationship, or is there something I'm missing that could solve this? I can figure things out on the front-end display with Views, but this is rather challenging for someone unfamiliar with content authoring (which most of my authors are).

Thanks in advance for any help.

You can use Entity View Modes to create a User view mode, and then set the fields for display on that view mode. Then select the view mode in the field formatter for the Entity Reference field.


Get field value and label for a content type using REST API I need to create a REST API endpoint with GET operation in Drupal 8. The API should return all fields of a given content type. Right now I am only able to fetch the title.

Also, I am not supposed to use the REST Export option in views module but the expected output is same as what we get using the Views REST Export option.

This is the code I have written for the get() method and right now only title is being displayed. I want to output the remaining fields as well.

public function get() {
    if (!$this->currentUser->hasPermission('access content')) {
        throw new AccessDeniedHttpException();
    }

    $query = \Drupal::entityQuery('node')
      ->condition('status', 1)
      ->condition('type', 'schemes_funds_nav')->execute();

    $nodes = \Drupal\node\Entity\Node::loadMultiple($query);

    foreach ($nodes as $entity) {
        $result[$entity->id()] = $entity->title->value;
    }

    $response = new ResourceResponse($result);
    $response->addCacheableDependency($result);

    return $response;
}

Any help is highly appreciated. Thanks in advance.

In the foreach you add just title so it's normal to have only title displayed:
you should populate your array result with the values from your entity, something like:

  foreach ($nodes as $entity) {
    $result[] = [
      'nid' => $entity->id(),
      'title' => $entity->title->value,
      'FIELD_NAME_1' => $entity->FIELD_NAME_1->getValue(),
      'FIELD_NAME_2' => $entity->FIELD_NAME_2->getValue(),
       // And so on with other fields.
    ];
  }


Adding multiple nodes at once I have created for a mobile site a form to collect daily readings using a content type and that is working like a charm. The question is:

Is there a method, way, module or hack where I can setup some sort of form where the same content type form will be display 7 times (one for each day) and the common fields be merge into one?

The reason for my question is that the regular form make sense to be fill using a mobile device, but if someone wants to use a desktop computer it will make more sense to enter the 7 days of data at once.

Multi Node Add module could be very helpful for you. With this module you can add multiple nodes at once.

  This module provides a new interface for creating nodes where the users are able to select the fields what they want to use for creating the nodes.
  It is designed to create multiple nodes in one round, it's possible to add more node input rows on-the-fly.


Theming of a webform node i would to theme a specific webform page and i achieve this with devel themer help but i find it not logical.
Usually i use ID to specify a template for a page, node or other element.
Then in my case i use the node-419.tpl for my node 419.normal
For my page it's a bit more complicated because this the hierarchical applied template :

page-infos-profil-élève.tpl.php < page-webform.tpl.php < page-node-419.tpl.php < page-node.tpl.php < page.tpl.php

so why a template called page-webform-419.tpl.php doesn't work instead of page-infos-profil-élève.tpl.php ?
Could i do this with php in my template.php file ? if yes how ?

thanks

This depends on your template suggestions.

Open template.php in your theme folder, and look for a function named YOURTHEME_preprocess_page, if it does not exist, create it like:

function YOURTHEMENAME_preprocess_page(&$vars)
{
    debug($vars['theme_hook_suggestions']);
}

And see what suggestions (and in what order) you have.

EDIT: this is a preprocess function I used in a theme of mine, in theme's template.php:

/**
 * Implementation of hook_preprocess_page()
 * @param $vars
 */
function THEMENAME_preprocess_page(&$vars){
    // I like to store templates in different folders inside the theme dir
    foreach($vars['theme_hook_suggestions'] AS $i => $ths){
        $vars['theme_hook_suggestions'][$i] = 'pages/' . $ths;
    }
}
/**/

In your case, simply do debug($vars, 'preprocess page vars!'); to see what variables you have a dispostion (please note: flush the cache after editing/creating this kind of function, and the output of debug($vars) can be very big!) and then add your template suggestion.

Maybe this can help: theming d7 webforms


PDO Deadlocks Galore on the Semaphore table I experience frequent deadlocks on the semaphore table that look like this:

  PDOException: SQLSTATE[40001]: Serialization failure: 1213 Deadlock found when trying to get lock; try restarting transaction: DELETE FROM {semaphore} WHERE (name = :db_condition_placeholder_0) AND (value = :db_condition_placeholder_1) AND (expire <= :db_condition_placeholder_2) ; Array ( [:db_condition_placeholder_0] => variable_init [:db_condition_placeholder_1] => 298999494f343fc583c3e2.30542255 [:db_condition_placeholder_2] => 1328824262.5293 ) in lock_may_be_available() (line 181 of /var/www/drupal/includes/lock.inc).

This site sees fairly heavy traffic. Is the load the cause of this? Is this due to a faulty module? Is this something in Drupal core?

Most importantly, are there precautionary measures I can take to avoid this?

It appears that once we implemented memcache the problem began to dissipate. It appears the database was writing very frequently to the cache tables, specifically the cache_form table. These deadlocks would appear when there were just too many commands running on the box.


Hook menu item not Showing I have two hook menu items:

function myid_print_menu()
{
    $items = array();
    $items['user/%user/myid_print_settings'] = array(
        'title' => 'ID Print Settings',
        'description' => 'Configuration options for the myid_print module',
        'page callback' => 'myid_print_admin_settings',
        'page arguments' => array(1),
        'access callback ' => 'myid_print_user_access',
        'type' => MENU_LOCAL_TASK,
        'weight' => -9,
    );

    $items['user/%user/myid_print'] = array(
        'title' => 'Print an ID',
        'page callback' => 'myid_print_user_page',
        'page arguments' => array(1),
        'access callback' => 'myid_print_user_access',
        'file' => 'myid_print.pages.inc',
        'type' => MENU_LOCAL_TASK,
        'weight' => -10,
    );
    return $items;
}

function myid_print_admin_settings()
{
     return drupal_get_form('myid_print_settings_form');
}

function myid_print_settings_form()
{
     $form = array();
     $form['summary'] = array(
         '#type' => 'fieldset',
         '#title' => t('ID Summary'),
         '#description' => t('Summary of ID printed, submitted and reset on a specific range of time')
     );
     return $form;
}

The 'ID Print Settings' was not showing, but Print an ID was showing. I tried clearing my cache, it was still not visible. Why?

I have a feeling with the access callback. Either your function is wrong (which you haven't posted) or something is up with your permission setting for this module.

Try temporarily updating your access callback to true to verify that it is causing the issue:

'access callback' => TRUE,

and clear your cache.

I think you may be better off creating a permission using hook_permission and using access arguments instead of access callback.

/**
 * Implement hook_permission()
 */
function myid_print_permission(){
  return array(
    'administer myid_print' => array(
      'title' => 'Administer myid_print'
    ),
  );
}

/**
 * Implements hook_menu().
 */
function myid_print_menu() {
  $items = array();
  $items['user/%user/myid_print_settings'] = array(
      'title' => 'ID Print Settings',
      'description' => 'Configuration options for the myid_print module',
      'page callback' => 'myid_print_admin_settings',
      'page arguments' => array(1),
      'access arguments' => array('administer myid_print'),
      'type' => MENU_LOCAL_TASK,
      'weight' => -9,
  );

  $items['user/%user/myid_print'] = array(
      'title' => 'Print an ID',
      'page callback' => 'myid_print_user_page',
      'page arguments' => array(1),
      'access arguments' => array('administer myid_print'),
      'file' => 'myid_print.pages.inc',
      'type' => MENU_LOCAL_TASK,
      'weight' => -10,
  );
  return $items;
}


Is there a way to display an 'All' link following the alphabetic glossary with Views 7.x-3.x? I have an existing feature in a Drupal 5 site I'm trying to reproduce in Views 7x3x, but I didn't find a way to make it happen.

I have the glossary functionality working in Views 7.x-3.x but the 'All' link functionality is eluding me. This selector needs to work in combination with a filter (taxonomy) so this limits the obvious workarounds because the Views module needs to be aware of the filtering.

How do I display an 'All' link following the alphabetic glossary?

I have it working using a jQuery snippet, but would love an elegant server side solution.

I found these solutions on drupal.org.

I haven't tested any but if anyone does; please post your experience as an answer for this question.

Altering views-views-summary-unformatted.tpl.php is certainly the way forward. Don't be lazy and use the header if you can't get the template file to register initially, it's worth it in the end. That way you can add --view_name on the end and target all displays without having to copy bits of code around, or symlink the file to target another view or specific display so that you don't have to edit twice.

As I mention in the post we both linked to, the HTML doesn't validate if you use any exposed filters but it's fixable with regex.

The post has recently been updated; there is a version for 7 that includes 0-9 and ALL which works as described, if that answers your question?

Additionally you refer to the glossary as a filter but it is actually an argument selector. On my site I have it working with two taxonomy filters.


Use Media Youtube with File Field Type I have set up a Feed Importer than gets a YouTube Atom Feed and processes it into "YouTube Video" content type. This is working great so far but what I want to do now is have the actual YouTube video embedded in my website rather that linking to the youtube website.

I downloaded and installed the Media YouTube module and went to set up a field in the YouTube Video content type to hold the video url. The Multimedia Asset field type is deprecated and I found somewhere that said to use the File field type. So I created the "Video" field as a File field with the Media File Selector widget. Then I set up the mapping in the feed importer. I am using the Feeds: YouTube Parser module to parse the Atom Feed. I set the Source to Video URL and the Target to my new Video field.

When I went to import the feed I got a bunch of errors that look like this

Download of http://www.youtube.com/watch?v=tag:youtube.com,2008:video:xm6Jv3BhdS4 failed with code 404.

I'm not sure where the "tag:youtube.com,2008:video:" part is coming from otherwise the url is correct. Anyone know what my problem is? Is it the way the YouTube Parser is getting the url or something else?

Thanks a lot!

In your feed importer mapping, change the Source to Watch page.  It seems Video URL is broken.

I have it working right now with the following modules:

Feeds (feeds)  7.x-2.0-alpha7
Feeds: YouTube (feeds_youtube)  7.x-2.0-beta1+7-dev
Media Feeds (media_feeds)  7.x-2.0-alpha1+9-dev
Media (media)  7.x-1.2
Media Internet Sources (media_internet)  7.x-1.2
Media: YouTube (media_youtube)  7.x-2.0-rc1

All dev versions were as of today (Dec. 1, 2012).  And for anyone that's trying, I found Embedded Media Field (emfield) to not work with Feeds at all.

Using the File field type (the widget type doesn't matter for feeds imports), set the display to Rendered file.


How to create a commenting system for ECK entities, similar to node comments as exposed field under the body? I have done quite some research to accomplish comments under ECK entities, but all the tried solutions and modules appeared to hamper or be incompatible.

The idea is to create an exposed field for directly entering comments. It should allow for multi-level commenting (replies to comments).

I will update this question with the tried solutions.
If you have actually tried or implemented a commenting solution for ECK entities yourself, please post your answer.

If you have suggestions but have not tested it yourself, please post it as a comment to this question, and I will try your suggestion.

Option: module Comments Entity.
I can't get beyond a bug I posted in the issue about "Cannot save comments".

As an alternative to the Comments Entity module, and the bug you reported about it, you may want to give the Reply module a try. Some more details about this module, from its project page:

Reply is a D7 answer to entity comments.
Reply is basically a fieldable entity so you can create a 'review', 'comment', 'forum post' or whatever you like by creating bundles and attaching fields to them. Such bundles can be attached to any fieldable entity by 'reply field'.
You can set access for reading and writing, position the form to the same page as entity or to a custom page, allow or deny replying to replies(= no hierarchy), choose threaded or flatted list. Such settings can be set for bundle, field, instance and entity with build-in inheritance which makes if a four level hierarchy settings system.
Most common usage of this module is comment replacement and reviews.

Even though this module only has an alfa release for D7 (as compared to a beta release for the Comments Entity module), the issue queue statistics seem to be more healthy:

Reply:  66 open, 166 total (about 40% open issues).
Comments Entity:  10 open, 10 total (= 100% open issues).


How can I add a "weight" functionality to nodes? I would like to be able to specify a "weight" for the article nodes published in the homepage. What is the best way to do this?

You could for example use Nodequeue to create  fixed list of nodes and then show that as the front page (as a view I guess).

Or, you could define your own weight field (for example a simple integer field, or a select with options from -50  to 50) and then create a view of nodes which you sort based on that field.


How to make form update/rebuild every page load? Part of my custom form that gathers petition signatures includes some markup saying "last signer: Bob, 3 minutes ago", looked up from a database.
But if the user does not submit the form, eg they reload the page, or look elsewhere then come back to the page, the form is rendered from cache and so it still says 3 minutes ago.
What can I do?
Notes:

I am not using varnish or memcached or anything else fancy that might interfere with caching. It's a very simple sure. The behaviour is seen for anonymous users. The form is used in a block, and the block is defined with DRUPAL_NO_CACHE.

The form has AJAX submission (although it must work for non-js-enabled browsers, too). I have since learnt that:

cache: ... ajax_process_form() enables form caching for all forms that include an element with the #ajax property. (The Ajax handler has no way to build the form itself, so must rely on the cached version.)
no_cache: If set to TRUE the form will NOT be cached, even if 'cache' is set.

So the question seems to point to: how can I force a form cache reset for a page load that is NOT ajax-related, e.g. in hook_block_view()? As this would mean caching was ON (required by ajax), and can stay there for form submissions, but a page load without user input will regenerate the form?

If you are not using Varnish or other server caching, first, I would try CacheExclude Module or something similar to prevent the page that the form resides on from being cached. In this way it should reload every time.


How to show the webform submission page as pop up? I have created the webform with two fields. When I submit the webform, its redirecting to the submission page.

Now, I want to display the webform submission page as pop up.

Thank you message and the "Back to form" should display in the pop up.

I have tried up with the NG lightbox to display the message. But its redirecting to the page with the pop up function.

How to achieve this thing, Please guide me.

It is very difficult (but not impossible) to target a lightbox/modal when submitting a form because the posted database has to be sent to the server.

I recommend following the below ticket on Drupal.org which could help you solve your problem using Ajax.

Allow Webforms to be submitted using AJAX


Site gives 500 error or malformed page in place of WSOD and useful error reporting I don't think I have encountered this before. Generally if there's a php error on page, I'm met with a WSOD. With error reporting on, the error, file, line number, etc are displayed on the page.

With this site, the site either returns a 500 error (if the error is in hook_form_alter, for example), or the page will load partially up to the point of the error and display sans stylesheet/other resources (if the error is in a template file).

Any ideas why this might be and how to change it over to expected behavior?

Fixing such errors is a panic, as in comments you have tried php debugging.

Below tries may help:

1- Try to install new drupal site locally to ensure that your machine and required programs for drupal "If you don't have any working drupal site" works fine, If you faced problems in the installation fix them till you have successful installation.

2- Try to flush cache and running cron from the admin interface if it works or using drush by drush you can see latest log messages using commands "wd-list, ws".

3- Implement hook_init in any custom module and print any message after that call drupal exit to see tha messages in the browser.

4-disable "without uninstall in order not to loose configurations" last enabled custom or contributed modules, If you have drush installed try

  drush dis Module_name -y

Or from phpmyadmin

  Delete from system where name='Module_name';

I used these steps before to solve similar situation and I remember it was from one the contrib modules.

If you still have the problem these guides may help.

Fixing white screens step by step

Blank pages or "white screen of death" (WSOD)


Panels: Show sub terms and child nodes I've just used panels to display child terms on taxonomy pages. For example If my heirarchy is like this...

Catalogue
--Category 1
----Sub Cat 1 (contains nodes)
----Sub Cat 2 (contains nodes)
----Sub Cat 3 (contains nodes)
--Category 2
--- Sub Cat 4 (contains nodes)

...the 'Category 1' page shows links to Sub cats 1, 2 and 3. That's working fine.

The problem is that once you get to one of the sub categories that contain nodes, the node teasers are not displaying. Is there a way of making these display?

Either:

Build a view, taking a term argument, and returning the tagged nodes. Output it in Panels. This will give you the greatest flexibility.

Or:

Look for a "Term to Node" relationship under "Context" in the relevant variant. There might a suitable relationship to pull in the nodes that way, but you may find it hard to control what the nodes look like.


Organic Group Content type name I am using the Organic Groups module and am following the readme file. I am on step 2:

  Create a new content type via admin/structure/types/add. Call it
  "Group", and define it to be of Group type.

Just curious, can I call it another name rather than " Group"? like "Site", or something else...

Thanks!

Yes, you can call it whatever you want. It's a regular content type like any other, i.e Page, News, Event, Blog post, etc.

Perhaps this will help: Absolute Beginner's Guide to Organic Groups (OG)

Cheers,


Separating contextual-links CSS, out of the CSS of menus and other associated markup The following problem happens when you style menus in Drupal, using CSS. The problem is especially dominant when you edit the <a> tags of a menu, but happens in regards to all of the menu markup.

The following images describe problems for two different menus, in which CSS directives I gave to my #navigation selector and its <a> tags, such as height: 60px, display: inline-block, and color: #fff, are inherited by the contextual links markup and thus destroy its appearance and making it impractical if not nonfunctional.

Thus, the solution I need is to separate the contextual links CSS from the themes', loading it afterwards or hardcoded somehow.

I dedicate this question to experienced themers: How can one load the contextual links with "hardcoded" CSS code, so they won't inherit anything from CSS directives I write in any theme-dependent CSS.

Code information:

Twig data:

{{ menus.menu_links(items, attributes, 0) }}

{% macro menu_links(items, attributes, menu_level) %}
  {% import _self as menus %}
  {% if items %}
    {% if menu_level == 0 %}
      <ul{{ attributes.addClass('menu') }}>
    {% else %}
      <ul class="menu">
    {% endif %}
    {% for item in items %}
      {%
        set classes = [
          'menu-item',
          item.is_expanded ? 'menu-item--expanded',
          item.is_collapsed ? 'menu-item--collapsed',
          item.in_active_trail ? 'menu-item--active-trail',
        ]
      %}
      <li{{ item.attributes.addClass(classes) }}>
        {{ link(item.title, item.url) }}
        {% if item.below %}
          {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
        {% endif %}
      </li>
    {% endfor %}
    </ul>
  {% endif %}
{% endmacro %}

Mobile-first responsive CSS:

#navigation {height: auto; padding: 10px 0 10px 0; background: #0a97b7}
    #navigation ul {display: none} /*For JS conditioning: if none than...*/
    #navigation li {display: block}
        #navigation a {color: #fff}
            #navigation a:hover {text-decoration: none}
    .navtoggle {display: block; padding: 10px 25px 10px 0; font-size: 24px; background: none !important}

Desktop level CSS:

@media screen and (min-width: 1080px) {
    #navigation {height: 60px; padding: 0}
        #navigation ul {display: block}
            #navigation li {display: inline-block}
                #navigation a {height: 60px; line-height: 60px; padding: 0 15px 0 15px; display: inline-block}
                /*<a> must be either block/inline-block to have its height changed.*/
                    #navigation a:hover {background: #55cfd6; text-decoration: none}
    #navigation .menu-item {display: inline-block; float: right}
    #navigation .is-active {background: #55cfd6}
    .navtoggle {display: none !important}
}

Complete reset of the contextual links class as follows, isn't effective (nor it is adequate) and is overridden by more specific codes:

.contextual ul       {background: #fff !important}
.contextual li       {display: block !important}
.contextual a        {color: black !important; height: auto !important; line-height: 1.3em !important; background: #fff !important}
.contextual a:hover  {background: #f4f4f4 !important}

Every in-place menu seems better with this compelete reset, but it still don't cover all menus.

All contextual links are wrapped in a div.contextual, whereas navigational menu items are usually wrapped in a li.menu-item.


MySQL error when creating field schema I have a problem when adding a new field to a content type. The schema installer for the specified field always causes the following error:

  Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'NULL DEFAULT NULL, PRIMARY KEY (entity_type, entity_id, deleted, delta,' at line 12.

Here is the hook_field_schema() implementation:

function google_directions_field_schema($field)
{
    return array(
        'columns' => array(
            'lat' => array(
                'type' => 'float',
                'size' => 'big',
                'not null' => false,
            ),
            'lng' => array(
                'type' => 'float',
                'size' => 'big',
                'not null' => false,
            ),
            'mapTypeId' => array(
                'type' => 'varchar',
                'length' => '15',
                'not null' => false,
            ),
            'zoom' => array(
                'type' => 'integer',
                'size' => 'small',
                'not null' => false,
            ),
        ),
        'indexes' => array(
            'lat_lng' => array('lat', 'lng'),
        ),
    );
}

I hope somebody can point out my mistake here. If some informations missing, please comment.

Thank you in advance.

I fixed this problem by myself. Please note the mistyped column type name integer which is now int:

function google_directions_field_schema($field)
{
    return array(
        'columns' => array(
            'lat' => array(
                'type' => 'float',
                'size' => 'big',
                'not null' => false,
            ),
            'lng' => array(
                'type' => 'float',
                'size' => 'big',
                'not null' => false,
            ),
            'mapTypeId' => array(
                'type' => 'varchar',
                'length' => '15',
                'not null' => false,
            ),
            'zoom' => array(
                'type' => 'int',
                'size' => 'small',
                'not null' => false,
            ),
        ),
        'indexes' => array(
            'lat_lng' => array('lat', 'lng'),
        ),
    );
}


Custom migration source plugin not enabled in source site error I'm trying to write a custom source plugin for a d7-d8 migration. I want to extend the Drupal\node\Plugin\migrate\source\d7 Node.php plugin.
I'm getting the following error when I try to run the migration from the UI:

Migration my_node_page did not meet the requirements. The module
my_xtra is not enabled in the source site. source_module:
my_xtra.

When I run drush ms I get a different error

No database connection configured for source plugin variable

The database connection key is specified in the group yml and works for other migrations which don't use the custom source plugin.
Here's my yml file
id: my_node_page
label: Node Basic Page
audit: true
migration_tags:
  - Drupal 7
  - Content
migration_group: my_group
source:
  plugin: my_xtra_node
  node_type: 'page'
process:

Here's my custom plugin.
    <?php

    namespace Drupal\my_extra\Plugin\migrate\source;

    use Drupal\node\Plugin\migrate\source\d7\Node;

    /**
     * Drupal 7 node source from database.
     *
     * @MigrateSource(
     *   id = "my_xtra_node",
     *   source_provider = "node",
     *   source_module = "my_xtra",
     *
     * )
     */
    class NodeXtra extends Node {

      /**
       * {@inheritdoc}
      */
      public function query() {
        // Select node in its last revision.
        $query = $this->select('node_revision', 'nr')
          ->fields('n', [
            'nid',
            'type',
            'language',
            'status',
            'created',
            'changed',
            'comment',
            'promote',
            'sticky',
            'tnid',
            'translate',
          ])
          ->fields('nr', [
            'vid',
            'title',
            'log',
            'timestamp',
          ]);
        $query->addField('n', 'uid', 'node_uid');
        $query->addField('nr', 'uid', 'revision_uid');
        $query->innerJoin('node', 'n', static::JOIN);

        // If the content_translation module is enabled, get the source langcode
        // to fill the content_translation_source field.
        if ($this->moduleHandler->moduleExists('content_translation')) {
          $query->leftJoin('node', 'nt', 'n.tnid = nt.nid');
          $query->addField('nt', 'language', 'source_langcode');
        }
        $this->handleTranslations($query);

        if (isset($this->configuration['node_type'])) {
          $query->condition('n.type', $this->configuration['node_type']);
        }

        return $query;
      }
}

Thanks!

Your source module should be "node" since that's what you're extending.
/**
* Drupal 7 node source from database.
*
* @MigrateSource(
*   id = "my_xtra_node",
*   source_module = "node"
* )
*/


How do I reverse the order of submit and preview button? I need to change the submit and preview button order in the node edit form in Drupal 7.
By default the submit button shows first the preview button, But I need vice versa.

How can I achieve this?

One solution is to use hook_form_alter() in a custom module to make the submit button heavier than the preview button:

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

  if($form_id == 'MYNODETYPE_node_form') {
    $form['actions']['preview']['#weight'] = $form['actions']['submit']['#weight']-1;
  }
}

Just change the module name and form id accordingly.


How do I pass a context filter to a block loaded by ajax? There is a block created in views that displays the values of the taxonomy term fields.
This block should be loaded when selecting a term from the select field in a custom form. Accordingly, the block needs to somehow pass the tid of the term selected in the form.
The Select field in the form is formed as follows:
$form['rq_program'] = array(
       '#type' => 'select',
       '#title' => t('Program'),
       '#options' => GetProgramNameArray(),
       '#required'=> TRUE,
       '#ajax' => array(
          'callback' => 'GetTermInfo',
          'wrapper' => 'form-ajax-content',
          'method' => 'html',
          'effect' => 'fade',
        ),
    );

callback function:
function GetTermInfo($form, $form_state) {
    $tid=taxonomy_term_load($form_state['values']['rq_program']); //value from select

    $block = block_load('views', 'views_program_block');
    $content = _block_get_renderable_array(_block_render_blocks(array($block)));
    $output = drupal_render($content);
    return render($output);
}

I can't understand how to pass $tid to the block, how to set up a context filter in this block to receive this $tid?

If the block you generated uses a contextual filter, maybe this could be the answer: https://drupal.stackexchange.com/a/205731/98697


Test class could not be found, namespace/autodiscovery issue? I've got the following tests written for /core/modules/migrate_drupal_ui/src/Controller/MigrateController.php with
a new test file /core/modules/migrate_drupal_ui/tests/src/Functional/MigrateControllerTest.php.

<?php

namespace Drupal\Tests\migrate_drupal_ui\Functional;

use Drupal\Tests\BrowserTestBase;

/**
 * Provides a base class for testing the Migrate Controller.
 */
abstract class MigrateControllerTest extends BrowserTestBase {
  /**
   * {@inheritdoc}
   */
  public static $modules = ['migrate_drupal_ui', 'views'];

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();
    $account = $this->drupalCreateUser(['administer views']);
    $this->drupalLogin($account);
  }

  public function testRedirectDestination() {
    $this->drupalGet('admin/reports/upgrade');
    $this->assertUrl('admin/reports/dblog?type%5B%5D=migrate_drupal_ui');
  }

  public function testRedirectDestinationWithoutView() {
    // Delete the watchdog view
    $this->drupalGet('admin/structure/views/view/watchdog/delete');
    $this->assertResponse(200);

    $this->submitForm([], 'Delete');
    $this->assertResponse(200);

    $this->testRedirectDestination();
  }
}

Following https://www.drupal.org/docs/8/phpunit/phpunit-browser-test-tutorial, an existing test runs as expected with ../vendor/bin/phpunit --filter testMigrateUpgradeReviewPage modules/migrate_drupal_ui/tests/src/Functional/MigrateUpgradeFormStepsTest.php.

However, when I do the same for my above test -- ../vendor/bin/phpunit --filter testRedirectDestination modules/migrate_drupal_ui/tests/src/Functional/MigrateControllerTest.php -- I get

PHP Fatal error:  Uncaught PHPUnit\Runner\Exception: Class 'modules/migrate_drupal_ui/tests/src/Functional/MigrateControllerTest' could not be found in '/Users/MrWeiner/Sites/DockerSites/testing/web/core/modules/migrate_drupal_ui/tests/src/Functional/MigrateControllerTest.php'. in /Users/MrWeiner/Sites/DockerSites/testing/web/vendor/phpunit/phpunit/src/Runner/StandardTestSuiteLoader.php:102

It looks like a namespace issue but I do not understand why it'd be looking for Class 'modules/migrate_drupal_ui/tests/src/Functional/MigrateControllerTest' instead of Class 'Drupal\Tests\migrate_drupal_ui\Functional\MigrateControllerTest'. Do I need to register my test somewhere or do something else to ensure that it's autodiscovered?

Original Question: We've got https://www.drupal.org/files/issues/2019-04-12/adding-custom-access-2904546-24.patch posted in https://www.drupal.org/project/drupal/issues/2904546 with the request "for a functional test with and without that view enabled". The patch itself is very simple so I'd assume that the test would be very simple as well. I just don't have any experience writing tests so I don't really understand what I'd be testing for/asserting here or how to test for both the view existing and not existing.

It turns out that the issue was that MigrateControllerTest was defined as an abstract class. Defining it as a regular class cleared this up.


How to theme regions in non-standard themes like Consilium? So I'm stuck with a theme that is very difficult to work with because it is nonstandard. It seems like it would like to be Omega and put lots of functionality into the admin UI and out of template files but it seems they forgot to actually add that functionality in there.

So the goal is to add regions and edit existing ones. Normally I would do this in page.tpl.php but this theme does not define region order and html inside a template like this. They've provided a Layout section in their appearance settings but there's no way to actually do anything in this section. No drag, no select, nothing.

So my question is that somewhere in some file, these regions have to be defined in a specific order so where? It's not in page.tpl but it has to be somewhere or else drupal wouldn't know what to do with these regions or how to structure their html.

I know a few suggestions would be to contact the theme maintainer but they are horrible on support. Another suggestion might be to choose another theme but my company picked this one and so I have no choice. I also have a Friday deadline and just got to start this week so figuring out this silly theme has been taking up all my time.

regions are normally defined in the [theme_name].info file in the theme directory. Here is an example from the Bartik theme:

  name = Bartik

  description = A flexible, recolorable theme with many regions.

  package = Core

  version = VERSION

  core = 7.x

  stylesheets[all][] = css/layout.css

  stylesheets[all][] = css/style.css

  stylesheets[all][] = css/colors.css

  stylesheets[print][] = css/print.css

  regions[header] = Header

  regions[help] = Help

  regions[page_top] = Page top

  regions[page_bottom] = Page bottom

  regions[highlighted] = Highlighted


How to create a rule to send email to users of a role that belongs to a country? I'm using Profile2 module to assign a Country to a Role. For example I have:

User1 | Role: "International Members" | Country: "UK"
User2 | Role: "International Members" | Country: "Poland"
User3 | Role: "International Members" | Country: "Japan"
User4 | Role: "International Members" | Country: "US"

My content also has a field Country.

I have this Rule:

Events:

After saving new content
After updating existing content

Conditions:

Content is published

Actions:

Send mail to all users of a role (International Members)

That is sending email to all users in Role "International Members".
I would like to:

Lookup the Country of the content
Send email to only those "International Members" whose profile Country matches the one of the content.

So If I publish a content with Country set as "US" it should only send an email to User4.

Any idea?

You need to use the action "fetch entity by property" and then use the country field and supply the country.

That will create a list to loop through so you can send mails.


How to convert a unix timestamp field in views I'm keeping a Unix timestamp in a text field.  In Views, I want to convert it to a readable date.  This is a commerce view, and the field is a custom field of an order.

Can I use hook_field_formatter_view() to use as my own formatter?  Something like:

function mymod_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {

    if ($entity_type == 'commerce_order') {
          // figure out field type and instance
    }

}

If that is a way to do it, I want to look at the params through Devel, so what can I return until I'm ready to operate on them?

You can use hook_views_pre_render to change the output of your field..

  This hook is called right before the render process. The query has
  been executed, and the pre_render() phase has already happened for
  handlers, so all data should be available.

  Adding output to the view can be accomplished by placing text on
  $view->attachment_before and $view->attachment_after. Altering the
  content can be achieved by editing the items of $view->result.

function MYMODULE_views_pre_render(&$view) {

   if ($view->name=='viewyouarelookingfor') {

      // do whatever you want

   }

 }


What's the best way to get the email of the author of a referenced node I'm looking to use a combination of Mailhandler with either Rules or Notifications. When a volunteer creates a "note" (a node that references another node), I want to notify the author of the referenced node. The use case here is a volunteer helpdesk where a volunteer logs a note on a ticket, and the ticket's author receives an email.

It seems like a custom token to locate the ticket author's email would be useful in either situation. Is that the right approach? If so, are there any code samples of creating a D7 token that does something like this?

With Rules:

Create a new Rule that reacts on event After saving new content.
Add a condition Content is of type to the rule and select the note content type in the content types section.
Add an action Fetch entity by id to the rule.

As entity type, select Node.
In the Identifier section, press button Switch to data selection (unless you already see an input field labeled Data selector).
From the Data selectors section, find the selector that references the ticket that is associated to the note. Copy that value into the Data selector input field.
In the Fetched entity section, set the variable label to "Referenced ticket" and the variable name to "referenced_ticket"
Save the action.

Add an action Send mail to the rule. You can now use referenced-ticket:author:mail as data selector for the recipient.


Deployment using Composer replacing old style install but issues with legacy Drush I took a Drupal project that was created awhile back via downloading a tar file and recreated it on a local via composer with drupal-project.

The recommended files were committed to git (i.e. no contributed modules, etc.) and cloned on the server. The composer install was clean.

At the point of doing a $ drush sqlc to load the database, it became evident that there was an issue - Drush error message below. I believe the issue is that Drush was already installed.

$ which drush outputs /home/me/.composer/vendor/bin/drush.

The error message when I attempt to run drush sqlc or drush status from the project, even with --root, is the following.

  PHP Warning:  require(/var/www/html/drupal/d8/vendor/composer/../../load.environment.php): failed to open stream: No such file or directory in /var/www/html/drupal/d8/vendor/composer/autoload_real.php on line 70
      PHP Stack trace:
      PHP   1. {main}() /var/www/html/drupal/d8/vendor/drush/drush/drush:0
      PHP   2. require() /var/www/html/drupal/d8/vendor/drush/drush/drush:4
      PHP   3. include_once() /var/www/html/drupal/d8/vendor/drush/drush/drush.php:56
      PHP   4. ComposerAutoloaderInit6220513682b217c143f76d07878222a3::getLoader() /var/www/html/drupal/d8/vendor/autoload.php:7
      PHP   5. composerRequire6220513682b217c143f76d07878222a3() /var/www/html/drupal/d8/vendor/composer/autoload_real.php:60
      PHP Fatal error:  require(): Failed opening required '/var/www/html/drupal/d8/vendor/composer/../../load.environment.php' (include_path='/var/www/html/drupal/d8/vendor/pear/pear_exception:/var/www/html/drupal/d8/vendor/pear/console_getopt:/var/www/html/drupal/d8/vendor/pear/pear-core-minimal/src:/var/www/html/drupal/d8/vendor/pear/archive_tar:.:/usr/share/php') in /var/www/html/drupal/d8/vendor/composer/autoload_real.php on line 70
      PHP Stack trace:
      PHP   1. {main}() /var/www/html/drupal/d8/vendor/drush/drush/drush:0
      PHP   2. require() /var/www/html/drupal/d8/vendor/drush/drush/drush:4
      PHP   3. include_once() /var/www/html/drupal/d8/vendor/drush/drush/drush.php:56
      PHP   4. ComposerAutoloaderInit6220513682b217c143f76d07878222a3::getLoader() /var/www/html/drupal/d8/vendor/autoload.php:7
      PHP   5. composerRequire6220513682b217c143f76d07878222a3() /var/www/html/drupal/d8/vendor/composer/autoload_real.php:60

In addition to Drush being in both ~/.composer/vendor and <root>/vendor, I note that ~/.composer contains

autoload.php
composer
phpdocumentor
phpunit
symfony
bin
doctrine
phpspec
sebastian

How do I go about cleaning this up so that the project root is the sole repository of these files and Drush can find what it's looking for?

As @Jaypan commented, globally you only need the Drush Launcher as phar file. And remove the old globally installed Drush version, this install method via composer global require is no longer supported. If you still need a legacy Drush version for other Drupal sites, download it the same way as phar file, see http://docs.drush.org/en/8.x/install. Which then can act as launcher by the way, so you don't need the Drush Launcher in this case.


Unlimited text field type and unordered list with links I'm continually amazed at how powerful drupal can be. Im using Drupal 7 and right now I am curious to see if its possible to create a field for a custom content type where I enter text that becomes links via an unordered list. I would love if I could enter this into the CMS without having to go into the code.

I managed to find a way of creating the unordered list by customizing the field template file (field.tpl.php) which is great, but curious if there is a way to wrap the text items in an href.

Link 1

Link 2

Link 3

Thanks all!

I found out a perfect module to do just what I wanted called Link.


How to validate file using hook_file_validate? I want to validate my file, I'm using

  hook_file_validate

function test_file_validate($file) {
  $errors = array();

  if (empty($file->filename)) {
    $errors[] = t("The file's name is empty. Please give a name to the file.");
  }
  if (retstrlen($file->filename) > 255) {
    $errors[] = t("The file's name exceeds the 255 characters limit. Please rename the file and try again.");
  }
  return $errors;
}

But, when I am going to print_r($file) I am not getting any values, please let know how to use this function

In Drupal 7 just use drupal_set_message

/**
 * Implementing hook_file_validate
 * @param type $file : Object
 * @return type : array of error messages
 */
function hook_file_validate($file) {
    drupal_set_message("<pre>" . print_r($file, 1) . "</pre>");
    $errors = array();
    if ($file->source == 'field_article_file_und_0') {
        if ($file->filesize > 290081) {
            $errors[] = t("The file's exceeds upload limit. Please try again.");
        }
    }
    return $errors;
}


Where should libraries be copied to sites/all or sites/all/modules? I currently have it in both locations, but figure this is incorrect. The problem is, when I try to remove it from sites/all/modules the superfish module complains, and says that it's needed.

What am I doing wrong?

You must create a directory libraries inside sites/all folder.


How can I output the Devel query log? Is it possible to output the Devel generated query log in some way? By default, it prints to the bottom of the page which is fine until I need to send the results to someone else to review.

The devel module has an option to log the query times into the database, and you can then run your own analysis on this and do whatever you like with it.

This is something to be careful about as it is a lot of data and can add up quickly. However, for more sophisticated/aggregate analysis, it's quite useful.

After enabling query logging, you can see some results at http://yoursite.com/devel/queries


Why do we duplicate field data in the field_revision_* tables when revisions are disabled? Even with revisions turned off for a given content type, the field_revision_* tables for the fields each contain a single record that matches the corresponding record in the corresponding field_data_* table.

I've always been aware of this, and previously, I've never had a reason to question it. However, now I am dealing with an extremely large database, and almost 50% of the database size is made up of this duplicated data in the revisions tables.

Why do we duplicate all the field data in the revision tables when revisions are disabled for a content type?

That's a great question - I wonder if it's any different in D8.

The field_data tables, and node table also track the "current vid" which is the current revision id, I guess they felt there had to be at least one.  But it does seem like there should be another way to do this. Maybe they could just store a 0 or something as a flag in the field_data tables current_vid column to indicate there's not a revision.


Features are sweet but what about content? I used features successfully to restore my VIEW and content type...but the data for the content type didn't make it? Did I miss the option or is this something you typically bring over manually?

Features are useful to export (and import) configurations, but is not useful for "entities": users, nodes, files, terms, and so on.

A great module to export and import is Node Export


When to use BaseFieldDefinition instead of hook_schema While creating a new information for Drupal 8, I came across 2 approaches to create a new column on the entity table on database:
* use hook_schema() (as I was used on Drupal 7) (https://gist.github.com/pedrorocha-net/3ed63f33b513d9c9ff86)
* extends ContentEntityBase and use BaseFieldDefinition (https://gist.github.com/pedrorocha-net/70d6a84c3ddba1c5939d)

Both alternatives creates the table for me, with the data, but I think the latter already provides me more integration with other Drupal components e.g. Views module. By the other hand, being an "Entity" I believe brings some "weight" to the data, as it works with some wrappers(on Drupal 7 at least).

What i'm doing is port the Voting API module, so this question about extra weight can really impact on sites with more content.

Any thoughts?

The question that you are really asking is if you should be using the entity system or not. You only have one option depend on the answer to that.

Yes, there is considerable overhead especially when using content entities. But things like nodes and comments are entities too, and you can have hundreds of thousands of those. It doesn't really depend on how many are stored but how many are accessed and processed on typical requests. If it's common to load a large amount of them (not just calculate aggregates like how many votes but actuall load the whole thing), then entities might not be such a good match.

Drupal Core only has two primary types of entities, content and config entities. You could also define your own lightweight entity type that is completely custom, but then you again need your own storage class, table creation and so on.

But as you said yourself, being a (content) entity gives you a lot functionality, like CRUD, views integration, REST and many more that you possibly don't need for your use case.


feeds_ex module tests returns me fatal error When I am running feeds_ex test i got an error that says:

PHP Fatal error: Class 'TUnit' not found in /sites/all/modules/contrib/feeds_ex/src/Tests/FeedsExUnitTests.test on line 11

I am looking around in google and forums but nothing similar found.

Any solution appreciated!

Per the instructions for the Feeds extensible parsers module:

  To run tests locally, the TUnit module is required.

So you need to install the TUnit module, which contains the missing class.


Modify a Module's output from a theme I'm really pulling my hair out about this one and wonder if someone can help?

Is it possible to override a module's output from the theme's template.php file?
Basically, I wan't to modify the output of the Geolocation Module without updating the module output itself.

if so, how would I go about it?

thanks a lot

Dave

Your question is somewhat vague, what specifically is the "output" you want to override?! Is it drupal Field output, a theme variable such as $vars['geolocation-something-foo'] ... or something else?

There is likely a preprocess or process Hook you can implement to slide in your changes. Or using Devel Themer you can probably override their template file with one of your own easily.

Something I did yesterday was override the implementing function of another module with a (local copy) of my own version of that function in a custom module -- tweaked to add HTML attributes and tags that I needed and were'nt provided by the raw HTML (non render array) output of the other module.

I followed the good example from this Snugug: Overriding Drupal Theme Functions from your Module and used HOOK_theme_registry_alter() using the following logic:

/**
 * Implements hook_theme_registry_alter
 */
function mymodule__theme_registry_alter(&$theme_registry) {
  $theme_registry['ORIGINALMODULE_function_name']['function'] = 'MYMODULE_function_name';
}

I think took the body from the original function, copied, tweaked and pasted it into mymodule_function_name. I believe this hook is callable from a theme as well ...


How do I filter by date is null in a View I have a View of contacts including the date of birth and want to filter by the date not being set.  When I add a filter on the date it provides a range of options (greater than, less than etc), but not one for "is null".

How can I add that?  Is there some configuration or another module to provide this functionality?

I do not know the answer, but did a quick Google: https://www.drupal.org/node/2107633
I would recommend you ask the question on the Drupal Stack Exchange site https://drupal.stackexchange.com/ as it is more of a Drupal than a CiviCRM question.


Remove Workflow from Features I'm trying to remove a Workflow instance from a Feature. But every time I uncheck the workflow and recreate the feature, the workflow gets deleted.

Now I know that with Views, Panels and other entities, all you have to do is to edit it, and it will be shown as overwritten (meaning it is using the database instead of code from the feature), and you can then safely remove it from the feature.

If I edit and save the workflow, it gives me a Revert link in the workflow menu. Yet if I then remove it from the feature, the workflow still gets deleted.

I've tried exporting the workflow and re-import it after removing, but then is just added with a new id (WID), which opens another can of worms on my site.

When I edit and save the workflow, I see in the workflow table in the db that the exportable status change from 2 to 3. I don't know what all the allowable statuses are. But this might be something to look into.

It looks like you've tried alot of possible solutions with mixed success.

A method I'm not certain you've tried is to apply a patch to Features 2.x for Drupal7 that Provides a way to Import Views/true exportables back to the database.

This patch creates a new tab in the Features Admin area called Import if you select the items in the selected Feature to import back to the database, it will then attempt to import the exportable back to the database. Unfortunately as some users note in the thread -- you may not receive a confirmation message that it was successful or not. Recent versions of this patch may have addressed this lack of a status message -- I used this module months ago to move about a dozen features out of Features and back into plain/simple database configuration.

There is also discussion in the thread about Drush Ctools Export Bonus. But I found this module difficult to use and produced an error with (i think) field_group stuff at the time.


If theme folder contains no html.tpl.php file, which html.tpl.php would Drupal default to using? I’ve taken over a site wherein the theme folder does not contain any html.tpl.php. In this case, which html.tpl.php would get used?

I found it, it's in

mysite/modules/system/html.tpl.php


How to programmatically code a block to show taxonomy vocabulary as an unordered list? I'm trying to build a menu using a taxonomy vocabulary with its hierarchical structure.
I don't want to use any module to do it.

In this page I see that I can grab the terms for a given vocabulary and do it programmatically http://drupal.org/node/113651

But I need some help to star coding it.

I have a Taxonomy called: Products (the tid is : 2)

Products has the following terms and hierarchical structure:

--Cars
----Volvo
----Ford
--Games
----Football
----Rugby
----Videogames
------Pacman
------Call of Duty

PHP CODE to generate:

Cars

Volvo

Ford

Games

 Football

 Rugby

Cars

 Pacman

Call of Duty

That's something I have put together for myself in the past. I posted the code on the Drupal taxonomy_get_tree() API page where you can get a copy for yourself. The core part of the code is usable with Drupal 6 as well (some smaller modifications are needed to make it work though).


Failed patching both manually and with Git in Ubuntu terminal I am very new to both Patches and Ubuntu and I try to run this patch which fixes RTL problems for Admin_Toolbar module (8.x-1.11).

I've downloaded the patch file and putted it in the module's folder.

When I tried to run it manually in the terminal i didn't succeed:

Later, similar situation occurred with Git:

Where my commands accurate? What can cause it to fail? For the creator of this patch it did work... Please give me a clue or any advice you can how to solve it... Is there even anything I could do in my end?

The patch you have doesn't apply to the version of the module you have.

You either need to get a version of the module that the patch applies to, or look for/create a patch that applies cleanly to the version of the module you have installed.

Might be worth checking the patch and target files manually, the patch may well have been applied and just not have fixed the problem in the way you were expecting. I can't tell what order you've run commands in/what you've done to clean up after each and so on so it's just a guess, but the "Reversed (or previously applied) patch detected!" message suggests the patch has already been applied at some point.


How to fully localize popup calendar field Strangely my popup calendar is localized, showing day names and so on in correct language, but not the date in the textfield neither in the description, which remained Y-m-d formatted.

.

This should be french format : d-m-Y . And I also need to change default value from today to next week. So, as per this answer :

  (For date popup) Branch 7.x-2 :
  Implementing hook_date_popup_process_alter() you could remove the description...

I tried these diff snippets :

function vts_commerce_date_popup_process_alter(&$element, &$form_state, $context) {
  $element['#date_format'] = 'd-m-Y';//no effect
  $element['date']['#date_format'] = 'd-m-Y';//no effect
  $element['#default_value'] = date('d-m-Y', strtotime('+1 week'));//no effect
  unset($element['date']['#description']);//works but I need to display it with correct date format instead
  dsm($element);
  return $element;
}

From which snippets 4 changes the form element. Instead, snippets 1, 2, 3 changed $element into dsm() returned values, but change nothing in the form. So my questions are:

How to display date into the textfield and in its description in french format ? how to change the default value that will be shown on page loading ?
What is the difference here between $element['#foo'] and $element['date']['#foo'] ?

Many thanks for your replies.

Well I'm a bit ashamed :( No need to do such complicated things. In the edit field page, there are some advanced settings and values I had never paid attention to :

Date entry options : control the order and format of the options users see.

Default date : Relative default value (Describe a time by reference to the current day, like '+90 days' (90 days from the day the field is created) or '+1 Saturday' (the next Saturday). See strtotime for more details.


What's the easiest method for migrating content from Drupal 7 to another Drupal 7? I have two drupal 7 sites and one of them has about 21 content types that does not exists in the other drupal 7 site. It's not a data merge so it's more of a data copy. I know there is the migrate module, but that seems a bit overkill for something like this as I am not merging data into an existing content type. It should just create a new content type on the new site and import all the fresh datas in.

What's the best approach or modules that should be used in this scenario?

I have never used migrate module before, so I'm assuming it's pretty complex as it can deal with many types of data. I remember there was a module which let you copy content from one site into the other.

The only complexity here is that these content types have node references and entity references associated to them. What issues might arise from that?

You should use the Features module to export the configuration for your content types (and any related things - taxonomies and the like).

To move content between the sites, I'd recommend looking into the Deploy module, which will allow you to "push" content from one site to another. It requires some configuration to get it all set up, but it works really well, particularly with nodes that have dependencies on other entities (via entity reference or taxonomy term reference or things like that).

If you want to use Migrate (which is probably not a bad idea, depending on your data). You could also look into the migrate_d2d module, which has a UI that let's you just point at another Drupal site, and then press "Go" and it'll pull in all your content.

tl;dr: There's lot of ways to do it, but the "best" way depends on the data in your sites.


How do I change the Date module to get 'days back and forward'? I want to restrict the dates a user can select when using past dates. I want a pop-up message when he tries to select a day +1 month from current date.

How can I do this? Do I need to override the module? If so, how?

You need to implement hook_form_alter() to add a new form validation handler. To avoid any conflict with the existing validation handler, you should probably remove the existing one added from the Date module, if there is one.


Alter taxonomy autocomplete value I need to alter the element value of a taxonomy autocomplete field before it is processed and can't seem to find a way of doing so.

taxonomy autocomplete fields have an element validator attached, that replaces the String value with an array of terms:

[$form] (array)
  [field_myautocomplete] (array)
    [und] (array)
      [#element_validate] (array)
        [0] => "taxonomy_autocomplete_validate" (string)

I need to alter the String before the validator taxonomy_autocomplete_validate() // taxonomy.module:1747 passes it to drupal_explode_tags() // common.inc:7416. Thus I attach my own element validator via hook_form_alter():

[$form] (array)
  [field_myautocomplete] (array)
    [und] (array)
      [#element_validate] (array)
        [0] => "MYMODULE_validate" (string)
        [1] => "taxonomy_autocomplete_validate" (string)

My validator is executed first and uses form_set_value() to update the value (exactly what taxonomy.module:1782 does in its validator).

However, this only updates the value for $form_state and not $element which is the value used by taxonomy_autocomplete_validate(). Thus, the altered value is completely ignored and gets overwritten by the second validator, based on the original string.

Any suggestions beyond hacking core (make taxonomy_autocomplete_validate use $form_state) are most welcome.

the simple solution to this issue, is to pass $element by reference to the first element validator:

function MYMODULE_validate(&$element, &$form_state) {
  (...)
  form_set_value($element, $new_value, $form_state);
  $element['#value'] = 'new_value';
}

This way, the $element['#value'] (used by the taxonomy_autocomplete_validate) can be modified and the following validators will.

The form_set_value() is not required, but since the form value has changed, it makes sense to update the state as well.

* many thanks to @ciss for helping troubleshoot the issue on #drupal and suggesting the pass by reference.


How to add descriptions to quicktabs I would like to know I can add descriptions to quicktabs. Ideally, every tab would have it's own description that gets displayed.

Thanks

You can render quicktabs programmatically and where title field, you can add your descriptions. Here is link to manual: Creating QuickTabs programmatically not working


Block doesn't show up in blocks listing Custom block doesn't show up on block listing and pages allowed to display that block.
After switch theme everything is ok, so it is not module layer issue.

I check template.php everything seems to be ok. I check CSS (display: none, etc), it seems that it's not CSS issue.

I asked about other idea's, why that block doesn't show up? I am struggling few hours and starting to have no new idea's to solved that issue

Make sure the region variable is getting printed in page.tpl.php which is associated with your block.
Make sure there is content for your block. If $block['content'] is set to empty in hook_block then the block does not appear at all.
Check block visibility condition as well


Translatable strings not appearing in the translation interface I've recently started working on a custom D8 module. I've used $this->t() (or t()) wherever I had to output a text so that this text would then be translatable.

My module works correctly, but when I visit Drupal's "User interface translation" (admin/config/regional/translate) page, those strings are nowhere to be found.

Two examples:

_1. in the mymodule.module file, I have implemented the hook_help() function to display a help page in the admin:

<?php

/**
 * Implements hook_help().
 */
function mymodule_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    case 'help.page.mymodule':
      return t('
Here is the (much longer) help text.
');
  }
}

?>

The help page is visible in the admin and shows the text; however this text cannot be found in the "User interface translation" page.

_2. the module has a configuration page in the admin, with several fields and a description for each field. This configuration form is defined in src/Form/mymoduleForm.php:

<?php

namespace Drupal\mymodule\Form;

use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;

class mymoduleForm extends ConfigFormBase {

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    // Form constructor.
    $form = parent::buildForm($form, $form_state);
    $config = $this->config('mymodule.settings');
    $form['field1'] = array(
      '#type' => 'textfield',
      '#title' => $this->t('The first field:'),
      '#default_value' => $config->get('mymodule.field1'),
      '#description' => $this->t('
Description for this field.
'),
      '#required' => TRUE,
    );
    // and so on
  }
  // other code
}
?>

Here again, the configuration page works, all the fields are visible, but none of the strings in the code above appear on the "User interface translation" page (neither the title of the string, nor the description).

The same goes for strings declared in the *.yml files: they're supposed to be picked up automatically by Drupal, but I don't seen any of them in the interface... (e.g. the module description in the *.info.yml file.)

What am I missing?

As suggested by @prkos in the comments, visiting the pages (both public and admin) in the target language caused the corresponding strings to be discovered by Drupal and therefore become available in the interface translation. For each string, you have to visit the corresponding page (or block).

If you have custom error or confirmation messages, you apparently have to trigger them before they appear too. (? not entirely sure)

(I thought the "updating translations" progress bar that you see during the module installation was precisely Drupal listing all translations available in the module, but apparently that's not the case.)


how to get the size and last modified date of file with fid Hi I have the filename and fid of the uploaded file in a media entity, how can I programatically get the size and last uploaded date in my module?  This is with D8
thanks

This is the code to get the size:

 $tid=$fileupload[0]['target_id'];
 $file = File::load($tid);
 $size = $file->getSize();


Relationships in Views always 4 results also if no reference for the field I have two content types :

meals
wine

In my content-type "meals" I have a entity reference to "wine".

Now I wanna create a views to show all meals, with a reference to wine.

I have create a views with following settings:

  FILTER CRITERIA

  = Content Type (= meals)

  = (Content entity referenced from field_wine) Content: Published (Yes)

  RELATIONSHIPS

  = Entity Reference: Wine

In my view I get all results for that. So if a wine was tagged in 2 meals, I get a view with that two meals.

My Problem now: I always wanna show 4 meals. So I want to show the 2 meals + 2 others.

If i have a wine with 1 meals. So i want so show the 1 meal + 3 others.. and so on.

Do any know how to fill the results if the missing some meals?

I think the best way to do via https://www.drupal.org/project/views_field_view . So, below is the steps:-

Create a view for the meal which shows all meals and add one more field "nid" as a hidden parameter(just tick exclude from display) so that we will have an available token for nid.
Now, create another block of wine and pass meal's nid as a contextual fitler. so, it will give you all wine as per single meals.
The next step do the trick. Go back to block #1(meal's view) and and add global:view field and pass "[nid]" of the meal as a contextual filter in that field(you will find an option don't worry) and select the view and display of the #2(wine's block).
That's it, here you have all the meals with wines. :)

Hope it will solve your problem.


Panels, Diff and nodes Does the Diff module work with nodes that are displayed using the Panels template? I go to /revisions and I get a "Page not found".

A panels display for a node should not affect diff/revisions.

Is there a revision tab for the node?  "node/NID/revisions" also were any revisions created for the node for diff to even compare? By default they won't create a revision.


How to rearrange views PHP sorting criteria? Usually, it works fine when I rearrange two or more sorting criteria within a Views (simple drag and drop) but in my case (Content fields grouped by taxonomy terms), one of the sorting criteria is a Global:PHP (based on a PHP field) and it seems like it is always treated first whatever level I choose? And of course, I need it to be treated secondly.

EDIT1 : Here is the problem in details

I have a list of nodes with pagination (1-15, 16-28, etc.). I also have a taxonomy field to group the nodes (categories). I need to sort the nodes by taxonomy terms (according to the weight) and secondly by first page. I get the first page using a PHP field to extract the data from the pagination. If I use the pagination field directly, the sorting is wrong (page 100 will appear before page 11, "alphabetical order").

Finally, I need :

Term 1

Node 1 pages 1-15

Node 4 pages 78-100

Node 12 pages 167-184

Term 2

Node 2 pages 16-45

Node 10 pages 110-125

Term 3

etc.

Any idea?

Thanks.

Related posts :

Cant get desired results for multiple sort criteria in a view

Sort criteria is ignored in Views

Views: custom field for sort criteria

EDIT2 :
As suggested by Smalution, a custom module could help. I am thus working on the little code needed to sort my View using a custom PHP field. I am using hook_views_query_alter and add_orderby but I can not find the right way to write it since the custom PHP field is not stored in a table like any other standard Drupal fields (the PHP field is computed when the View is calculated). Could anyone help me to complete the code given by Smalution? Thanks for any tip. Tell me if more details are needed.

You can go for hook_views_query_alter.

  Alter the query before executing the query.

function module_name_views_query_alter(&$view, &$query) {
  if ($view->name == 'Viewname') {
    //dpm($view->query->orderby[0]);
   // put your modified sorting criteria
  }
}


List all users whose "member for" and "last access" are the same I have around 40,000 users on my site but around 20,000 of them are automated registrations (by comment spammers presumably) and I'd like to delete those.

It's very easy to spot them as their registration date/time is exactly the same as their last access date/time.

How do I filter the user list in Views so that I only get users whose "member for"=="Last access"?

These won't be exact matches.  It uses a timestamp value that will vary, even if only a few seconds.

I would suggest doing this in some custom PHP

that module, or writing your own custom functions.  you'd convert the timestamp difference to a reasonable value (say, within 1 hour?) and then user_delete()

I would also add a captcha and/or email verification to help prevent this.


Drupal search api custom sort order I am using search api solr and using views for search results. In my content type, there will be a multilingual field using entity translation and also a field representing language of the node. I am having three languages in the site.

I would like to sort the results by language.

Like, if the site language is set to english,

The search results should first list all english language nodes and then second language and then third. Suggest me a way to fix this.

I fixed this by using hook_search_api_solr_query_alter() and solr function. Here is my code:

function mymodule_search_api_solr_query_alter(array &$call_args, SearchApiQueryInterface $query) {
  if ($_SESSION['language'] == 'en') {
    $call_args['params']['sort'] = 'termfreq(ss_field_name,EN) desc';
  }
}


Request an Ajax form through Ajax [solved] I want to load a form through Ajax in a custom Javascript Event as it is explained in this tutorial. I receive the form, but its ajaxified behaviour is very strange.

My Javascript:

var address = $(location).attr('protocol') + '//' + $(location).attr('hostname');
var url_get_button = address + 'mymodule/get_button/';

Drupal.ajax.prototype.specifiedResponse = function() {
  var ajax = this;
  try {
    $.ajax(ajax.options);
  }
  catch (err) {
    return false;
  }
  return false;
};

var ajax_settings = {};
ajax_settings.event = 'onload';
ajax_settings.keypress = false;
ajax_settings.prevent = false;
ajax_settings.url = url_get_button;
Drupal.ajax['get_button'] = new Drupal.ajax(
  null, $(document.body), ajax_settings);

//the following is somewhere at the right js event...
Drupal.ajax['get_button'].specifiedResponse();

My php code:

function mymodule_menu() {
  $items['mymodule/get_button'] = array(
    'page callback' => 'mymodule_send_button',
    'type' => MENU_CALLBACK,
    'access callback' => 'user_is_logged_in',
  );
  $items['mymodule/next_ajax'] = array(
    'page callback' => 'mymodule_next',
    'type' => MENU_CALLBACK,
    'access callback' => 'user_is_logged_in',
  );
}

function mymodule_get_form ($form, &$form_state) {
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
    '#ajax' => array(
      'event' => 'click',
      'path' => 'mymodule/next_ajax/',
      'effect' => 'fade',
    ),
  );
  return $form;
}

function mymodule_send_button() {
  $form = drupal_get_form('mymodule_get_form');
  $form = ajax_pre_render_element($form);

  $commands = array();
  $commands[] = ajax_command_replace('#replace-this', render($form));
  $commands[] = ajax_command_invoke(NULL, "some_js");

  $button = array('#type' => 'ajax', '#commands' => $commands);
  ajax_deliver($button);
}

function mymodule_next() {
  commands = array();
  $commands[] = ajax_command_alert('works!');
  $message = array('#type' => 'ajax', '#commands' => $commands);
  ajax_deliver($message);
}

function mymodule_node_view() {
  drupal_add_library('system', 'drupal.ajax');
  drupal_add_library('system', 'jquery.form');
}

Well, if Drupal.ajax['get_button'].specifiedResponse();is called in the Javascript event, the button will be loaded, but if I click on the button, the page is reloaded with url_get_button (which was used to request the button) instead of getting the alert window with 'works!'.

But if I add another form builder function and call this function with drupal_get_form() within the hook_node_view() (without returning anything!!), it will work.

So I add:

function mymodule_get_another_form ($form, &$form_state) {
  //I have to add the following line in order that it works
  $form2['submit'] = array();
  return $form2;
}

and change my hook_node_view() to:

function mymodule_node_view() {
  drupal_add_library('system', 'drupal.ajax');
  drupal_add_library('system', 'jquery.form');
  $form2 = drupal_get_form('mymodule_get_another_form');
  //I don't return $form2...
}

Well, in summary: I want to request an ajaxified button through a custom Javascript event. I receive the button, but it is not ajaxified and on top the wrong url is linked. But if i call drupal_get_form() with another 'empty' form builder function during the page load, it will work and I will get the alert message after clicking on the button.

I use Drupal 7.

Does anyone have an advice for me? Why isn't it working without the second form builder function and why does it work with it?

I would welcome every advice.
Thank's a lot.

Daniel

I got it: In a sidebar, there was another form with a submit button provided by another module. This submit button has also the key 'submit'. In the form builder function I changed the key 'submit' to e.g. 'mymodule_submit' and now it works! So I don't need this strange second form builder function anymore.


How do I programmatically delete an order? My head is about to pop. I'm trying to figure out how to delete commerce orders programmatically. I created a rest export with the order IDs I want to delete. I've parsed that and put the IDs into an array. Now I want to loop through that array and delete the orders.

json parsing, and retrieving order_id work fine.

I'm so close but I can't figure out how to properly reference commerce_order_delete or commerce_cart_commerce_order_delete?

function afc_custom_node_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {
          if ($entity->id() == 803) {
            $url = 'my url';
            $jsonString = file_get_contents($url);
            $jsonDecoded = json_decode($jsonString, true);
            $object = new stdClass();
            foreach($jsonDecoded as $row){
            if ($row['order_id'] == 121) {
                $object->order_id = $row['order_id'];
                // $order = \Drupal::entityTypeManager()->getStorage('commerce_order')->load($row['order_id']);
                commerce_cart_commerce_order_delete($object);
            }

            }
          }
    }

Error:

TypeError: Argument 1 passed to commerce_cart_commerce_order_delete() must be an instance of Drupal\commerce_order\Entity\OrderInterface, instance of stdClass given,

UPDATE #2
New Code

use Drupal\commerce_order\Entity\OrderInterface;

  if ($entity->id() == 803) {
    $url = 'https://myurl.com/pull-ghosts';
    $jsonString = file_get_contents($url);
    $jsonDecoded = json_decode($jsonString, true);

    $object = new OrderInterface;

    foreach($jsonDecoded as $row){
      if ($row['order_id'] == 121) {
        $object->setOrderNumber($row['order_id']);
        commerce_cart_commerce_order_delete($object);
        print 'deleted';
      }
    }
  }

SAME ERROR:

error: Cannot instantiate interface Drupal\commerce_order\Entity\OrderInterface in afc_custom_node_view()

Loading it like a normal entity did the trick.

How to load and delete commerce order programmatically

$ord_id=121;
$order = \Drupal::entityTypeManager()->getStorage('commerce_order')->load($ord_id);
$order->delete();

Here is the entire snippet on my ultimate goal which was deleting abandoned orders in the cart.
How to remove commerce orders automatically

How to delete ghost commerce registrations in cart

Custom cron to delete commerce orders programmatically

Load a view programmatically loop through values and delete orders

/**
 * Implements hook_cron().
 */
 function my_module_cron() {
   //load a view showing orders still in cart
   $view = \Drupal\views\Views::getView('commerce_carts');
   //the name of your display, i chose a simple rest display with the order_id field
   $view->setDisplay('rest_export_1');
   $view->execute();

   foreach($view->result as $row){
     //load the order
     $order = \Drupal::entityTypeManager()->getStorage('commerce_order')->load($row->order_id);
     $oid = $order->id();
     //delete the order
     $order->delete();
     //log to dblog
     \Drupal::logger('afc_commerce_registration')->notice('Clearing ghost registration, deleted: @oid.',
       array(
           '@oid' => $oid,
       ));
   }
 }

You can add the Created date field to the view, and test time values before deleting. In my case, it doesn't matter.

Thanks for the help everyone


Update.php with errors in multisite (WAMP) I have 4 sites using the same features / modules and have the db main (general), and a "bd for each site." Sure, but the update modules / drupal core is made only once. During the execution of update.php I get the error:

An unrecoverable error has occurred. You can find the error message below. It is advised to copy it to the clipboard for reference.
Please continue to the error page
An AJAX HTTP request terminated abnormally. Debugging information follows. Path: http://LINK_OF_SITE.com.br/update.php?op=selection&token=ouRkHusqVcR48Xy0n-j8hc-C2pMOEc3ABwv7oMgHbzo&id=99&op=do StatusText: ResponseText: ReadyState: 4

What should I do? I'm using WAMP (localhost) with Apache (2.4.9) and PHP (5.5.12) and MySQL (5.6.17)

in the log, http://teste/mea/?q=admin/reports/dblog

  PDOException: SQLSTATE[42S02]: Base table or view not found: 1146
  Table 'teste_mea.backup_migrate_sources' doesn't exist: SELECT * FROM
  {backup_migrate_sources}; Array ( ) in
  backup_migrate_item->all_items() (line 923 of
  C:\wamp\www\TESTE\sites\all\modules\backup_migrate\includes\crud.inc).

probably an inconsistant module state. try to disable the migrate module in the database.

UPDATE system SET status='0' WHERE name='migrate';

for more details see here: How to manually uninstall a module?


Display suite 7.x-2.4, Drupal 7.22 I am a newbie to Drupal.

I have just installed display suite to increase layout control. I am now getting a lot of notices like this:

  Notice: Undefined index: title_value in link_field_update_instance() (line 1305 of  /var/www/vhosts/viovia.org/httpdocs/sites/all/modules/link/link.module).

What is even more of a nusiance is that I can configure customs fields for blocks and dynamic fields, but they will not display on my screen.

Can anyone tell me if this is linked to the index problem above, or is it anohter problem entirely?

The error message you quote has nothing to do with Display Suite.  It is caused by a bug in the Link module (as should be obvious from the error message you quote).

Here is a link to the relevant issue ticket.  If you read through the long list of messages, you'll see that the fix for this bug was commited to the dev branch of the Link module on May 23 2013. It is not in the "recommended" release.  The "recommended" release of the Link module is from February 9 2013, so it is quite old.

Try to install the dev branch of the Link module, and see if things improve.


Extra fields for edit form as opposed to front end hook_entity_extra_field_info() allows adding arbitrary elements to the Manage display tab that also appear on the rendered node.

I want to add some section headings that appear on the node edit form and can be re-ordered on the Manage form display tab.

Is there a hook like hook_entity_extra_field_info() but that adds an element to the edit form as opposed to the front end?

I realise that I could achieve something like this with field group but would rather use a lighter approach with less overhead.

hook_entity_extra_field_info() is invoked when either an entity is rendered, or when an entity form is shown to users. See user_entity_extra_field_info() as example.
function user_entity_extra_field_info() {
  $fields['user']['user']['form']['account'] = [
    'label' => t('User name and password'),
    'description' => t('User module account form elements.'),
    'weight' => -10,
  ];
  $fields['user']['user']['form']['language'] = [
    'label' => t('Language settings'),
    'description' => t('User module form element.'),
    'weight' => 0,
  ];
  if (\Drupal::config('system.date')->get('timezone.user.configurable')) {
    $fields['user']['user']['form']['timezone'] = [
      'label' => t('Timezone'),
      'description' => t('System module form element.'),
      'weight' => 6,
    ];
  }
  $fields['user']['user']['display']['member_for'] = [
    'label' => t('Member for'),
    'description' => t("User module 'member for' view element."),
    'weight' => 5,
  ];
  return $fields;
}

Any field that is part of the $fields['user']['user']['display'] array is shown when the User entity is rendered and can be re-orderer from /admin/config/people/accounts/display. (Member for is the label used from the code I previously shown.)

Any field that is part of the $fields['user']['user']['form'] array is added to the entity form and can be re-ordered from /admin/config/people/accounts/form-display. (User name and password, Language settings, and Timezone are the labels used from the code I previously shown.)

In the case of nodes, it's not different. You just need to remember that instead of $fields['user']['user']['form'] you need to use $fields['node']['content type']['form'], and replace 'content type' with the effective content type for which you need to add fields to the entity form. In the case you need to add fields to the entity form of every content type, you should use code similar to the one used in node_entity_extra_field_info().
foreach (NodeType::loadMultiple() as $bundle) {
  // Add the description for the extra fields.
  // $extra['node'][$bundle->id()][...] = ...
}