How to style an "all day event" to have it styled like any other event? I am on Drupal 7. Everything works fine in Calendar module, except when I add the all day event then the styling is changed, I wanted the same styling for all the events.

  "All day events" are created by "date_all_day" module which comes with
  "date" module.

As far as I understand it this is a CSS question. All you need to do is add styles to overwrite the color change. It is actually two different styles that need to be changed. The following code will set them back to the yellow and light grey color that is the default for the calendar module.

.calendar-calendar .month-view .full td.multi-day div.monthview,
.calendar-calendar .week-view .full td.multi-day div.weekview,
.calendar-calendar .day-view .full td.multi-day div.dayview {
  background: #ffc;
  color: #777;
}

.calendar-calendar .month-view .full td.multi-day .inner .monthview .continues,
.calendar-calendar .month-view .full td.multi-day .inner .monthview .cutoff,
.calendar-calendar .week-view .full td.multi-day .inner .weekview .continues,
.calendar-calendar .week-view .full td.multi-day .inner .weekview .cutoff {
  background: #ffc;
  color: #777;
}


Uncaught TypeError: Cannot call method 'extend' of undefined I'm trying to use a jquery ticker in my website and this is the code: http://cektkp.com/twittermarquee/twitmarquee.js and I'm getting these errors:

1) Uncaught TypeError: Cannot call method 'extend' of undefined:

window.twttr.bounds = window.twttr.bounds || {};
   $.extend(twttr.bounds, {
      Bounds: function (b, d, c, a) {
        this.x = b;
        this.y = d;
        this.width = c;
        this.height = a
      }
});

2) Uncaught TypeError: Property '$' of object [object Object] is not a function (line 37)

 function loadTrendDescriptions() {
    $("#trends a").each(function () {
        var A = $(this);
        var C = A.parent().find("em");
        if (C.length) {
            var B = A.text();
            var D = C.text().replace(new RegExp(B.replace(/([^\w])/gi, "\\$1"), "gi"), "<strong>" + B + "</strong>");
            var E = A.attr("title").length ? A.attr("title") : A.attr("name");page.trendDescriptions[E] = [B, D]
        }
    })
}

I've fixed many other problems I was getting but these are the ones I just can't understand how to fix. Please help me out!

You are attempting to use jQuery before it's loaded.

You should place that code inside your ready function:

$(document).ready(function () {
    // place code here
});

Although to be really Drupal-friendly, you should use Drupal's behaviors.


how to use hook_webform_submission_presave on a site with multiple webforms I've got a question on the use of the hook_webform_submission_presave function for D6/webform 6.x-3.4

I've got a multi-lingual D6 site that has one webform for each language, I'm trying to create a new module that will catch the submitted form info and send it to a third party email marketing company (the forms are newsletter signups and the third party is cheetahmail).

My specific question is:
Currently I have 6 webforms on my site, and I need to send info to identify which language the signup has come from.

Do I have to write a hook for each language/form ID?
or is there a way I can set up an admin panel and list the webform IDs that I'd like to hook?

Thanks for the help, please let me know if I need to provide more detail
Steph

Ok, So I've figured this one out:

function cheetahmail_webform_submission_presave($node, &$submission) {
Do something here
}

Without calling a specific form, will effect all webforms.
in my specific instance, i'm trying to catch the submitted/validated info before it enters the DB.


How do I provide multiple menu tabs for a view? I have a view to select many articles with a specific taxonomy term with a path of
     Example.com/materials/%
where the % uses a contextual filter to pick the correct material. The filter works.

Each article can be further subcategorized to discuss various subjects regarding the material and is given a path such as
     Example.com/materials/%/general or Example.com/materials/%/standards

I thought I would be able to display a default view for  materials/%   and have menu tabs defined by variations of the view to display /general or /scope parts.

I cannot get any menu tabs to display with the view.

Please respond with any questions, suggestions or alternative approaches that have worked for you.

Thanks

I have solved this problem using the Quicktabs module.

I use a panel to set a page where I can put a quicktabs block, then I call different views with each tabs, also you can even set arguments.


how to Insert form data in table i have an enquiry form and submitting the form using jquery/ajax method.

$.ajax({
          url:enquiry.php

I am able to insert records into database table using php mysql_query. When i use db_query in "enquiry.php" page, i am getting errors.

   Call to undefined function db_query()

i want to know how to use db_query to insert records in database table.

For that function to be available from outside Drupal, you need to first bootstrap Drupal. This means that, with Drupal 7, the first lines of enquiry.php needs to be the following ones.

define('DRUPAL_ROOT', getcwd());

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

I assume the enquiry.php file is in the same directory containing the index.php file that comes with Drupal.

I would rather suggest you to read the following questions, though:

Are there cases where a third-party module would need to use its own file similar to xmlrp.php, cron.php, or authenticate.php?
How should I implement hook_menu()?


How to display a BACK button but ONLY if the user came from somewhere else on my site I'd like to display a BACK button on my node--resource.tpl.php file but ONLY if the user came to the node from another part of my site. If they copied and pasted the URL for the node directly into their browser's address bar and got to it that way I do NOT want the button to appear.

Here' the button in my tpl:

<input type="button" value="Go Back" onclick="history.go(-1)" />

Anyone know how to do this with PHP (or another Drupal method)?

There are many ways to do this.
One of it would be to use $_SERVER['HTTP_REFERER'] to detect where the user comes from.

Put the following code in your template file.

if (strstr($_SERVER['HTTP_REFERER'], 'facebook.com') !== false) {
     // Facebook brought me to this page.
     print 'Go Back';  }


How to create language object from language string (e.g. 'en')? As in question, ofcourse I am asking about Drupal function for this job.

So I need function that get language string as param (e.g 'en','pl' etc) and returns me standard Drupal language object. Similar to global $language.

Use language_list() function:

<?php

function get_langugage_object($language) {
  $installed_languages = language_list();
  return $installed_languages[$language];
}

?>


Page redirect on login I want to redirect all the users to a specific page after login. It seems like an easy thing to do using rules.

Event
User has logged in

Action
Page redirect

There is a small problem though. Page redirection will also work on the first login/password recovery scenario which in practice disallows the user to set/change his password.

Any ideas how can I deal with this issue?

I have found that the Login Destination module seems to be able to solve my problems, but I would prefer not to add more modules if it is unnecessary (I have enough things to debug now).

Would something like the following work?

{ "rules_after_login_redirect_to_page" : {
    "LABEL" : "After login redirect to page.",
    "PLUGIN" : "reaction rule",
    "WEIGHT" : "0",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "user_login" ],
    "IF" : [
      { "NOT text_matches" : {
          "text" : [ "site:current-page:path" ],
          "match" : "^user\/reset\/",
          "operation" : "regex"
        }
      }
    ],
    "DO" : [ { "redirect" : { "url" : "your_page_url" } } ]
  }
}


Forcing file migration after deleting field I have a situation where I am working on Drupal 6 to Drupal 7 migration.  The migration is being done in stages, and stage one is now live.

I am working on stage 2, and have run into a snag file file migrations.

We had a content type 'foo' with field 'field_bar'.  It was originally created as File, but should have been image.  We ran migrations, and everything went OK (all files were part of original migration).

'foo.field_bar' got deleted and recreated as Image.  When we re-run migrations, the files aren't being attached.

As far as I can tell, is that the source/destination pair exists in {migrate_map_files} but the fid doesn't exist in {file_managed}, more than likely because it got deleted during garbage collection when cron ran.

What is the best option to force these migrations to run again?  Is there a way to do this with the Migration classes, or should I delete the bad rows from {migrate_map_files}?

My current solution is to use a query, and manually cleanup the {migrate_map_files} table

$fids = db_query('
  SELECT mmf.sourceid1 FROM {migrate_map_files} mmf
  LEFT JOIN {file_managed} f ON f.fid = mmf.destid1
  WHERE f.fid IS NULL
')->fetchCol();

db_delete('migrate_map_files')
  ->condition('sourceid1', $fids, 'IN')
  ->execute();

reset the watermark in {migrate_status} and then re-run my files migrations.


Drupal allows menu tabs on Views pages. Why, and why not on other kinds of content? In my question Most maintainable way to make page with one top half and alternative bottom halves selected by tabs?, I've asked about making a page with, as the title says, alternative bottom parts selected by tabs. There are various modules (Quick Tabs, Panels Tabs, etc.) that do tabs. But I have found that core Drupal itself has a feature for adding tabbed menus to Views pages. It's explained for example at Randy "Wilson" Brown's Drupal: How To Add A Tab To A Views Page. Why only to a Views page?

And — suppose I try to use these menus to select between things that really aren't views. For example, suppose I try to set up a page that has three tabs called "Photo 1", "Photo 2", and "Photo 3", each of which selects a different photo of my cat. I don't know whether I can make the views menus do this, but should I even try? Or is it likely to lead to problems, for example by being hard to do and maintain?

(Added a few days after posting) I'm adding the paragraphs below to clarify the spirit of what I'm asking.

I've coded with many languages and libraries where, to get a job done, you must "pervert" them because they lack the features needed to do the job cleanly. One example is passing primitive types by reference in Java. Suppose you want to write a method that takes an 'int' parameter and gives it a new value. You can't do that cleanly, because Java lacks call-by-reference for primitive types. But you can fudge it by giving your method an integer array parameter and passing your 'int' in an array. It works because arrays are compound entities, and Java passes those by reference. But it's bad, because arrays are intended for storing sequences, and you're misusing them for something else. It makes the code harder to read.

How does this relate to Drupal? I've come across several articles, in blogs and elsewhere, which appear to be doing the same kind of thing with views. For example, there's a post by Ron Golan at https: //www.urbaninsight.com/2013/11/01/views-menu-tabs-quick-guide which uses views to tab between different tabbed pages about a coffee grinder. One of these tabbed pages is a photo of the coffee grinder. In my mind, that's not a "natural" thing to use views for, because they are, in essence, database queries. And you don't need database queries in order to place one photo whose identity you know in advance.

Therefore, I suspect Golan is using views because he wanted their tabbed menus. When I see something like that, I have to think like an engineer and ask: somebody clever thought this trick worth using. Why? Why didn't he use a more direct technique? Is it because the trick, though perverse, is less risky than other techniques? For example, because it will not collapse if I update my Drupal or my jQuery. If I didn't ask such questions, I'd be betraying my client, because I'm ignoring information that might indicate dangers in some of my tools.

This functionality is built into the Drupal menu system but is not exposed as a configurable option through the web interface by Drupal core.  You would normally have to write some code that implements hook_menu to accomplish this.

Views happens to give a user interface for this functionality, so some people will take advantage of that to do things that maybe aren't best done in Views just because it lets them do it without having to touch code.  I should note that Page Manager and Panels also give you configuration that let you do this through the UI and that would be a better way to achieve this if you have pages that aren't naturally Views.


How to display a confirm box before submitting a form? On the node/%/edit form, when the user clicks the Submit button, I want to show a simple pop-up box with the text "Are you sure you want to save your changes?". When the user clicks Cancel (or No) then nothing happens. If the user clicks Ok (or Yes) then the form gets submitted.

I already tried out the A's in the following related Q's:

How to display confirm box before submitting an AJAX form in Drupal 7? but they already seem to assume the form has been AJAXified. I'm starting from scratch.
How to add a confirm dialog to node add and edit forms? is too complex since it adds extra validation options based on the user's input.
Use a custom JS modal to confirm changes made on node add/edit form before submit seems to be close but like the comments say: it doesn't actually work.

I also read some other A's that used the Rules module but that is totally overkill.

confirm_popup.info

name = Confirm Popup
description = Adds a confirm popup when saving all nodes.
package = custom
version = 7.x-1.0
core = 7.x
dependencies[] = jquery_update
dependencies[] = overlay

confirm_popup.module

<?php

/*
 * Implements hook_form_BASE_FORM_ID_alter()
 */
function confirm_popup_form_node_form_alter(&$form, &$form_state, $form_id) {

  $content_type = $form['#node']->type;
  if ($content_type == 'article') {

    $form['#attached']['js'][] = drupal_get_path('module', 'mymodule') . '/js/confirm-popup.js';
    $form['#attached']['css'][] = drupal_get_path('module', 'mymodule') . '/css/confirm-popup.css';

  }

}

js/confirm-popup.js

(function($) {
Drupal.behaviors.confirmPopUp = {
  attach: function (context, settings) {

    $(document).ready(function() {

      $("#edit-submit").attr("type", "fake");
      $("#edit-submit").attr("id", "fake");

      $(document).on("click", "#fake", function(){
        var box = $("
Are you sure you want to save your changes?
SaveCancel

");

        $("#overlay-content").prepend('

').prepend(box);
        $("#overlay-content").addClass('transbg');
        $("#overlay-titlebar").prepend('

');
      });

      $(document).on("click", ".save-btn", function(){
        $('#fake').attr("type","submit");
        $('#fake').attr("id","edit-submit");
        $('#edit-submit')[0].click();
      });

      $(document).on("click", ".cancel-btn", function(){
        $(".blackbg").remove();
        $(".popup-box").remove();
      });

    });

  }
};
})(jQuery);

css/confirm_popup.css

.blackbg {
   height: 100%;
   width: 100%;
   position: absolute;
   overflow: hidden;
   z-index: 10;
   background-color: rgba(0, 0, 0, 0.5);
}
.transbg{
   background-color: rgba(0, 0, 0, 0.0) !important;
}

.popup-box{
  width: 350px;
  height: 120px;
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  z-index: 20;
  background-color: white;
  padding: 10px;
  font-size: 20px;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  font-family: "Lucida Grande", Verdana, sans-serif;
  line-height: 1.2em;
}

.btns-wrapper{

   position: absolute;
   bottom: 15px;
   text-align: center;
   font-size: 15px;
   display: block;
   margin: auto;

}

.save-btn,
.cancel-btn{
  padding: 10px;
  width: 70px;
  cursor: pointer;
  border-radius: 5px;
  display: inline-block;
}

.save-btn{
  background-color: #6bc711;
  margin-right: 10px;
}

.cancel-btn{
  background-color: red;
}

#fake{
  width: 34px;
}

Result


How to override/implement a module's hook Is there a possible to override a module's hook? What I want is, write a search__query_alter() hook to restrict search results. But to achive this, I should write the hook in built-in module search's .module file.

This way, I'm hacking into core drupal files, which must be bad. Is there a way to write the hook for another module in my theme's template.php file or somewhere else, not touching the core drupal files? When I write search_query_alter() in my theme's template.php file it simply doesn't work.

From my question, you may understand I'm very new to Drupal! Thank you for helping.

You must create a custom module and add a custom hook function to it. The function name will be modulename_query_alter ().  Drupal maintains a list of all included hooks by searching the enabled modules for functions following that pattern.

Instructions for creating one are here.  This is the basic means for introducing custom behaviors to your site. The hook system is discussed here and you should look at using the hook_query_alter function here.

This will get you started and no doubt lead to further questions.


Render an item trough displaysuite? Admitted, I don't truly understand Displaysuite.

What I need, is, something of the following:

foreach (get_certain_nodes(), $nid) {
  $node = node_load($nid);
  $rendered_node = call_displaysuite_to_render_the_node($node, 'build_mode_foo');
  $output .= $rendered_node;
}

The missing link is how to render the node, using a predefined build mode. Or am I doing it wrong?

This is not a complete answer, but maybe it helps to have a look at the nd_views_node_helper function. If I understand correctly, it's the helper function that allows Views rows to be rendered through Display Suite.

You can also make your custom code dependent on views: create a view which takes node IDs as argument and renders the nodes through Display Suite.

Hope that helps!


Use of a function when importing a feed I have a Feed which imports data from a CSV file. I import data of products, namely title, price, category, etc. However, in order to provide a friendly URL, I send a customized field, which is in different languages and completely verbose, for example: Shoes for female scientists. I want to use this description as part of the clean friendly URL, so I would need to use some function like pathauto_cleanstring(). However, the update takes ages to complete. Is there a faster way, for example directly on import?

This code is executed on a call to mymodule_cronapi via Elysia Cron, and through curl PHP function:

   $results = db_query('SELECT nid, title FROM node WHERE type= :product', array(":product" => "product") );
    foreach($results as $row){
        $node = node_load($row->nid);
        $node_wrapper = entity_metadata_wrapper('node', $node);
        $node_wrapper->field_product_url->set(pathauto_cleanstring($row->title));
        $node_wrapper->save();
    } // foreach

You should be able to use Feeds Tamper to create your URLs based on values in your CSV: https://www.drupal.org/project/feeds_tamper


How some hooks works, if doesn't return anything and doesn't have any references In Drupal API documentation is an example:

function hook_user_view($account, $view_mode, $langcode) {
  if (user_access('create blog content', $account)) {
    $account->content['summary']['blog'] =  array(
      '#type' => 'user_profile_item',
      '#title' => t('Blog'),
      '#markup' => l(t('View recent blog entries'), "blog/$account->uid", array('attributes' => array('title' => t("Read !username's latest blog entries.", array('!username' => format_username($account)))))),
      '#attributes' => array('class' => array('blog')),
    );
  }
}

Noobie question is: how does it actually work? I mean, there is no reference being passed to the function, and it doesn't return anything. This is somewhat counter intuitive how function works. I guess $account data doesn't disappear with end of the function but how, if it's not a reference?

The $account variable is a PHP Object.

In PHP, Objects are (for the most part) passed by reference, so any changes you make to the variable passed in will be persisted to the object in memory.

The only difference syntactically is that you don't need the ampersand before the variable name in the function signature - it's implied.


Views Get Data from REST API without creating nodes I am consuming data via a 3rd party REST API (not a Drupal site). I'd like to minimize double-duty (importing nodes from the API and then displaying that data) and just display the API data directly via Views.

How can I create a Views handler for the REST API?

It is not easy way to show that data with views. You can show them to user without views and without  saving them but when you want use views you  must save them in database or create a custom module to do that. But my suggestion for you is to create a content type then save that data  in node. If you don't need to create a rule that delete them after a specified date, as example delete all data that  older that 3 days ago.


Coupon redemption form I just updated the Drupal Commerce installation to beta 7 which includes support for promotions and coupons. I just can't seem to get the coupon redemption form in the cart to test this functionality. I checked the cart view, there is a field 'Coupon' in the global footer, but that is just meant to show the already activated coupons I believe. At least it didn't do anything for me.

I tried to add 'Coupon' to my relationships in the view, but this broke down the website (incorrect query generated).

In the code I also noticed the CouponRedemption FormElement. I'm not sure how to add this to my cart (view), but that seems to be what I need.

I finally figured out the answer: the functionality has simply not been coded. Applying the patch from this issue: https://www.drupal.org/node/2792653 (patch #95 is the latest right now) will add a checkout pane for entering coupon codes. It is still not available on the cart page as you would expect in a webshop, but at least visitors can enter a coupon code.

You can place the checkout pane using Commerce->Configuration->Checkout flows->pick your flow by clicking 'edit'->Coupon redemption pane.


Installed base them NineSixty - where is it? I've installed the base theme NineSixty using the URL method without any errors.
When I then look for the files I can't find them anywhere.
I've looked in the themes directory as well as the sites/all/themes directories. In fact i've looked everywhere.

Where do the base theme's files end up?

If you have access to the database, check the "system" table of your drupal database and look for a record with the "name" ninesixty. That row will also tell you the path to the theme.

If you have phpmyadmin via cpanel or something similar you can just browse the system table.

Otherwise you could use this SQL (if your database is using a prefix it will be slightly different a the prefix will be appended to the table name "system"):

SELECT * FROM system WHERE name = 'ninesixty';

and that will give you all the info about your ninesixty theme.

Another way is to search your file system for the word ninesixty, which I imagine won't be anywhere except for the theme and maybe your base theme.


Question about users vs cck I need to add a field to represent a person's role on a board. I have a CCK for individuals that includes a field for their position.  I now need to make some changes so that I can keep track of the current position as well as other positions they may have had in the organization.

Originally, I did not set this up as a "User" entity but as a content type.  Now I"m wondering if this is the best way to structure my desired functionality?

Any Advice?

Do these people need to login to the website? Do they have to change those profile settings themselves? do you plan that those entities will interact on that page? If any of these is yes, than you probably want users.

In all other cases this is probably a no and you are good to go with content types/ custom entities.

for keeping a record of past positions, you might want to try out field collections, you could create a field collection with start, end, position for instance and allow n entries of it.


caching issue after updating records into database I've developed leave management in drupal 7 but facing an issue. When leave balance is updated due to calculations then it not shows right value from database due to drupal caching. Once I clean all caches then it shows right values. Is there any way to stop caching or update caching?

Please do some help.

Any well written module that has a cache, should prefix it with cache, meaning that the answer to your question is "Yes".

In the odd event that a module caches data somewhere else, you can check your modules for implementations of hook_flush_caches, and see what they remove.

Reference by Letharion


Is there a standard way to control which node or entity links appear in which view modes? My module adds a link to the node view, from within hook_node_view. Is there a "Drupal" way to let the site builder control which view modes should show that link?

Right now, I'm using a multiselect control on the module's admin settings page.

If you are adding fields in hook_node_view then the most polite thing you can do is add them to the 'manage display' tabs for that content type. Do this using hook_field_extra_fields(). This way people can: hide or show them per content type, per view mode and also position them amongst other fields, just like any field API field.

Here is a code example where I have added the print links to the node using hook_node_view().

/**
 * Implements hook_node_view().
 */
function zest_general_node_view($node, $view_mode, $langcode) {

    // Add print and email links as pseudo field.
    $node->content['print_links'] = array(
      '#markup'=> print_insert_link() . print_mail_insert_link(),
      '#view_mode' => $view_mode,
      '#prefix' => '
',
      '#suffix' => '
',
      '#weight' => 20,
    );

}

Then I add them as a 'pseudo field' using hook_field_extra_fields().

/**
 * Implements hook_field_extra_fields().
 *
 * Adds the print and email links as a pseudo field.
 */
function zest_general_field_extra_fields() {
  $extra = array();

  $extra['node']['product'] = array(
    'display' => array(
      'print_links' => array(
        'label' => t('Print Links'),
        'description' => t('Links provided by the print module.'),
        'weight' => 20,
      ),
    ),
  );

  return $extra;
}

hook_field_extra_fields()


How can a view in DrupalGap, which is used by a custom module, NOT be cached but instead be called each and every time? I am using a Local Task Menu as demonstrated in the docs to present one more tab named members next to View and Edit. This tab is showed only to group nodes and i have connected a custom view inside Drupal which fetches the members of this group. Works good. Fetches, displays and links the members in the appropriate page.
But the problem is that this view is called only the first time. In other words, if a user subscribes or unsubscribes from this group after the first call, then this change won't be updated and showed.
In Views Caching:None and Block caching:Do not cache but i think this is a matter of drupalgap menu cache.
Is there a way i can make this specific view not to be cached but instead be called every time the menu tab is clicked?

DrupalGap 7 is a multi-page application, which means as you navigate around, pages that you previously visited remain in the DOM. Then when you navigate back to that page, it is already in the DOM, so it isn't rebuilt.

All you need to do is add the reloadPage option to your link and that'll force the page to be reloaded upon navigation: http://docs.drupalgap.org/7/Pages/Reloading_Pages

/**
 * Implements hook_menu().
 */
function my_module_menu() {
  var items = {};
  items['foo'] = {
    title: 'Foo',
    path: 'foo-bar',
    options: {
      reloadPage: true
    }
  };
  return items;
}


How to add Modal in Bootstrap Sub Theme I am trying to make a sub theme based on Bootstrap 3 Drupal theme.

I want to add a modal markup in every page. I can see in the base Bootstrap theme template files, there is a file called modal.tpl.php with corresponding HTML markup but I do not know how to include it into my page. Anyone can help?

First refer to the bootstrap documentation on modals http://getbootstrap.com/javascript/ to construct a working modal with the content you want. Use bootply or whatever to get it working the way you want.

You then have two options that come to mind: You could just create a standard block using the Drupal UI, place the markup in the body of the block, and configure the block to "display on every page except" ... <front>. Then assign the block to a region.

Alternatively, you can override tpl files in your subtheme and place the modal markup in those. You do this by placing a copy of the Bootstrap theme's page.tpl.php in your subtheme. First create a copy of it called page--front.tpl.php then add your modal markup to page.tpl.php.


Multiple form submissions sorted by user Here's my case:

I have site with 5 forms. These can be filled in by user assigned with the a 'client' role. They can view and edit their own submissions and fill in forms multiple times, this works all as expected.

Now I'm looking for a way to display all submissions of all forms filtered by user. So when the site admin clicks on a client he can see a list with all submissions that this particular user has made.

I've been trying to tweak the default webform submissions view, create new views based on user, create a new view based on webform submissions with different relationships and contextual filters,.. unfortunately all without any luck.

I've been looking around but haven't found a good answer yet, I do apologize if I overlooked and this question has already been asked and properly answered.

Thanks a lot in advance.

It sounds like you are doing two different searches:

A. Get all webforms for which a user is the author

B. Get all users

Basically, Views has trouble with this kind of thing, because Views generally deals with one type of entity at a time, and users and webforms are different types of entities.

You can use Views Field View module to put one view inside the other.

Rough outline:

Create a view showing all the forms for a given user (filter for the user using a Contextual filter on the UID)
Create another view showing all users.  Use Views Field View to embed the view created in 1 and supply the UID as the argument.

This view will probably be very slow/performance intensive but since this is mainly for admin purposes hopefully that's ok.

See more details in this answer.


Using drupal to run a download website with about 10K files I want to run a website which has more than 10000 files available for download.Is sites/default/files a good place to store the files?
I see some websites store their files in someting like server1.example.com/file1.zip or drupal.org uses ftp for project files.

Which one should I use?

It depends on how do you want to manage/upload your files. You can put your files in sites/default/files but create a new vhost (with or without the same web server with your primary site) at files.example.com to give access to this folder. Also, it depends on whether you want access control to your files. If you don't want public access to those files, you should use the vhost, but use something like X-Sendfile header to reduce server load.


Adding  to options on node edit and node create screen I have an option field on my content types that allows you to select several items in a taxonomy vocabulary. The list has several child and parent items and it is really hard to read.

Is there a way I can add html around these checklist elements so that I can format them better with CSS?

I have attached a screenshot for more info.

There is the Taxonomy Term Reference Tree module that will format terms hierarchically.

  This module provides an expandable tree widget for the Taxonomy Term
  Reference field in Drupal 7. This widget is intended to serve as a
  replacement for Drupal's core Taxonomy Term Reference widget, which is
  a flat list of radio buttons or checkboxes and not necessarily fit for
  medium to large taxonomy trees.

This module produces nested ul lists, which seems optimal for styling hierarchies, if needed.


Inline Entity Form validation Created a content type and add taxonomy form in it using Inline entity Form module.

So, the rendered taxonomy add term looks like :

What I want to do is ADD CUSTOM VALIDATION to the "NAME" field.

I tried:

function hook_inline_entity_form_entity_form_alter(&$entity_form, &$form_state) {
  //kint($form_state->getStorage('inline_entity_form'));die;
  // $entity = $form_state->getFormObject()->getEntity();
  //   $nid = $entity->get('name')->getValue();
  $userInput = $form_state->getUserInput();
 // kint($form_state->getUserInput()['field_plan_features']['form']['inline_entity_form']['name']);die;
 // $form_state->setErrorByName('name', t('Term already exists in taxonomy blah'));
}

How it can be done.. please suggest some way.

I suggest you implement hook_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) function.

    function hook_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
      // Check if the $form_id is your node type add form.
             if ($form_id == 'article') {
                // Add a custom validation function. Example:
                $form['#validate'][] = 'custom_form_test';
              }
    }

Then you need to implement the custom function where you will put your logic.

function custom_form_test(&$form, FormStateInterface $form_state) {
  // Get value of the field which use the inline entity form display.
 $tags_value = $form_state->getValue('field_tags');

}

See the screenshot of the $form_state dump and also with the field_tags taxonomy term reference values:

So you can access all the values from the inline form display.
For example to access name value:

$name = $tags_value[0]['inline_entity_form']['name'][0]['value'];

Just looping into arrays. Once you get the value that you want you cand restrict finishing the submision of a node by write a message error. Example:

 $form_state->setErrorByName(
                'field_tags',
                'The name is WRONG!'
              );

Hope to help you!


User registration through service I have a local Drupal instance with services. I created an endpoint that has user resource included. I verified that all is well by logging in using the endpoint. I am now stuck at registering new users through the api. I tried the following:

URL: http://localhost/recipes/api/user/register

Method: POST

Content-Type: application/json

Body:
    {
   "name":"user34",
   "pass":"3323",
   "mail":"sample@example.com",
   "status":"1"
}

Result: 22:CSRF validation failed

I know that this error pops out when the token is not passed in the header of the request but how am I supposed to get the token if I am an anonymous user wanting to register?

Kindly mention the steps that I need to follow to have a user register through the REST api

Thanks :)

Anonymous (and authenticated) users can both get the token from the same place. Try following these steps:

Get the token with a GET to ?q=services/session/token
Attach the token to your POST header under the name X-CSRF-Token
Make the POST call to register the user


Form element's #required set to FALSE, but form submission still consider it as required I am trying to theme Contact form with template file, manipulating the contact form with form API, trying to hide the subject field and make it optional for submission.

$form['subject']['#required'] = FALSE;
hide($form['subject']);

I used dsm() to confirm that the #required is successfully set to FALSE.

However, when I submit the form, it still ask me to fill in Subject field. (The cache has been cleared.)

These are the steps that I have followed:

In the template.php file I added the following code

function mytheme_theme() {
  return array(
    'contact_site_form' => array(
      'render element' => 'form',
      'path' => drupal_get_path('theme', 'mytheme') . '/templates',
      'template' => 'contact-site-form',
    ),
 );

I created the contact-site-form.tpl.php file with the following code

$form['subject']['#required'] = FALSE;
hide($form['subject']);
print drupal_render_children($form);

I cleared the cache

Yes, theming the form only changes its markup. If you want to change the form you have to hook_form_alter.

I once wondered how to add required styles to elements that weren't actually required. Your question just gave me the answer.


How get path between two point on map? I want to use an API that gives me the path between two points. I know the value of latitude and longitude.

How do I get path, latitude and longitude of points of in between path?

I believe you can use the Google Maps Directions API, although I don't know any Drupal module that handles this API out of the box.


Different number of decimals for prices and totals I use Drupal Commerce and I have a problem with the number of decimals in prices. In Spain (and I suppose in other countries too), I could have prices of products with more than two decimals, but at the end, the totals are rounded to two decimals. With currency settings module I can set the number of decimals, but It is for all (prices and totals). Is there anyway I could have four decimals for prices and two for totals?
Thanks in advance.

If you can set the number of decimal places site wide... I would set it to most precision I am likely to need and shorten it through the theme/js in the places where I need it shorter.  It may not be as graceful as variable precision, but if no other answers come up, it will get the job done...


Display parent term based on child term in views I have a vocabulary with the following structure:

Vocabulary
Parent term 1
    Child term 1.1
        Child term 1.1.1
    Child term 1.2
        Child term 1.2.1
Parent term 2
    Child term 2.1
        Child term 2.1.1
    Child term 2.2
        Child term 2.2.1

Based on the above structure of taxonomy terms, I have a view of all the terms of last level like,

Child term 1.1.1
Child term 1.2.1
Child term 2.1.1
Child term 2.2.1

Now, i want to create the view, which list me 2nd level of taxonomy term by passing term id of the 3rd level.

  Example:- If i pass term id of Child term 2.2.1 in contextual filter, i should see the Child term 2.1 as a result of view.

You need to add Taxonomy term: Parent term in RELATIONSHIPS of the view.

Then in the field section select the Relationship

That's it. Whatever term you enter in the contextual filter it fetches the parent term of it.

Here is entire exported view (example).

$view = new view();
$view->name = 'tag_relation';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'taxonomy_term_data';
$view->human_name = 'Tag relation';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Tag relation';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Relationship: Taxonomy term: Parent term */
$handler->display->display_options['relationships']['parent']['id'] = 'parent';
$handler->display->display_options['relationships']['parent']['table'] = 'taxonomy_term_hierarchy';
$handler->display->display_options['relationships']['parent']['field'] = 'parent';
/* Field: Taxonomy term: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'taxonomy_term_data';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['relationship'] = 'parent';
$handler->display->display_options['fields']['name']['label'] = '';
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
$handler->display->display_options['fields']['name']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['name']['link_to_taxonomy'] = TRUE;
/* Contextual filter: Taxonomy term: Name */
$handler->display->display_options['arguments']['name']['id'] = 'name';
$handler->display->display_options['arguments']['name']['table'] = 'taxonomy_term_data';
$handler->display->display_options['arguments']['name']['field'] = 'name';
$handler->display->display_options['arguments']['name']['default_action'] = 'empty';
$handler->display->display_options['arguments']['name']['default_argument_type'] = 'fixed';
$handler->display->display_options['arguments']['name']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['name']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['name']['summary_options']['items_per_page'] = '25';
$handler->display->display_options['arguments']['name']['limit'] = '0';
/* Filter criterion: Taxonomy vocabulary: Machine name */
$handler->display->display_options['filters']['machine_name']['id'] = 'machine_name';
$handler->display->display_options['filters']['machine_name']['table'] = 'taxonomy_vocabulary';
$handler->display->display_options['filters']['machine_name']['field'] = 'machine_name';
$handler->display->display_options['filters']['machine_name']['value'] = array(
  'tags' => 'tags',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'tag-relation';


Best way to assign a user to a node I would like to associate users with a node (and make it possible for users to do this themselves) and have the result easily retrievable programmatically in a nice array( preferably with $node) and also have this in Views..

I found the following options so far

User Reference
Flag
Custom text field where I store userids as comma separated values
Entity Reference
Relation

Flag has the advantage of having actions that show on node view as well, which is quite convenient.

It depends on your requirements.

What would not recommend is something custom like comma separated values in a textfield. Because that's probably the only option where you don't have built-in views/rules/.. support.

Most of the listed solutions require edit access to the node. If you don't want that, you'd need to write custom code which allows users to add themself.

The user and entity reference modules store their information directly in the field information of the node, which might not scale well if you expect dozens or even hundreds of linked users on a single node (because the edit form will get bigger with each referenced user). The new relation project doesn't have this limiation, because every connection is a separate relation entity, which points to both the node and the user. A possible downside of that might be the additional overhead you have, compared to a simple user reference field.

Flag then is quite different to the others. Users can add themself to a node with it easily, but there is no UI provided to add other users or manage users which flagged a specific node (AFAIK), although you might be able to build something using Views, VBO and so on.


Why is the 'time ago' not displayed in my view? I'm not sure whether this is a bug or not, so I'm just going to ask this. I created a view (and block) with a 'Comment: Post date' field with 'Time ago (with "ago" appended)' as Date format. I didn't fill in a custom date format.

Everything is previewed perfectly, but when I go to my dashboard, I only see the "ago": the actual numbers (hours, minutes, seconds...) aren't displayed.

I cleared caches, but nothing happened. I'm still using the default Seven 7.23 administration theme for my dashboard and I didn't set a custom template file or anything else. I just created the view.

How can I solve this?

Edit: I exported my view, so you can read the code here.

I don't know what causes the problem, but I solved it temporally. I changed the Date format to 'Time ago' an added the 'ago' manually via the 'Rewrite results' function.


Is media-7.x-1.x vulnerable to SA-CONTRIB-2018-020 The Drupal Media module version 7.x-2.x contains a remote code execution vulnerability which was patched with:

https://cgit.drupalcode.org/media/commit/?id=1cd77ffa9c2cf96d80b76d47318179a8a82f0d46

1.x and 2.x seem to be very different beasts, I can't find any corresponding code to media_ajax_upload() in 1.x but I'm still rather unsure wether this version is vulnerable or not.

According to Joseph Olstad 1.x is not vulnerable to the problem found in the 2.x branch. Source:
https://www.drupal.org/project/media/issues/2966112#comment-12592407

There is a previously unreleased fix for another security issue though. This was integrated in version 1.7 of this module.


How to remove a menu path defined in hook_menu from naviagtion I've added two paths for use my my module (for OAuth authentication), but I don't want them to appear as links in menus. I tried defining their 'type' as MENU_CALLBACK but they still appear.

Is there a better way to define paths which aren't necessarily pages.

Don't add type to the array in hook_menu, it will not be displayed as a menu, but still will be accessible (by code)

$items['menu/%/link1'] = array(
   'title' => 'Link1',
// 'type' => MENU_LOCAL_TASK,
   'page callback' => 'link1()',
   'page arguments' => array(1),
   'access callback' => TRUE, //'has_access',
);


Unable to change backend language During install, it is possible to choose the language to be used on the admin screens. However, in this new Drupal 7.40 instance it was not chosen at install time. I need now to change the language from the default English (this is NOT a multilanguage issue).

Every tutorial I read tells me to click the "Add Language" button on Administration > Configuration > Regional and language > Languages. But there is no such button, there isn't even a "Languages" option under "Regional and language":

The option is displayed only after activating the "Locale" core module on the admin > modules page.


Inline entity form complex and cardinatlity I am adding an ief type field to my form with the following

    $form['inline_entity_form'] = [
        '#type' => 'inline_entity_form',
        '#op' => 'add',
        '#entity_type' => 'my_ent_type',
        '#bundle' => 'my_bundle',
    ];

I am sure this is something under my nose that i am missing but how do i force this to complex and set a cardinality for this instance?

Grateful for any pointers
Mathew

Try changing the type to inline_entity_form_complex so that you have the following;

$form['inline_entity_form'] = [
    '#type' => 'inline_entity_form_complex',
    '#op' => 'add',
    '#entity_type' => 'my_ent_type',
    '#bundle' => 'my_bundle',
];

Got the pointer from the following answer. https://drupal.stackexchange.com/a/207582/9906


Views slideshow - 3 items per slide - how to center them? I've been trawling the web on and off for months searching for an answer to the following:

I'm using Views Slideshow to show a series of logos in rotation. I have set there to be 3 items per slide in the slideshow settings. What I would like is for the three logos to be centred - i.e. an equal amount of space to either side of the logos. At the moment, they float left and I cannot for the life of me find the right CSS to do this, or where to add it.

I would really appreciate it if someone from the community could take a glance at the logo slideshow at the following url:

http://eunic-global.aptalops.com/

Please note that's it's the rotating logo carousel at the bottom of the page I'm having trouble with, not the slider under the main menu.

Best wishes,
A~

#views_slideshow_cycle_teaser_section_eunic_members-block {
margin: 0 auto;
}


Is there a list of ahah effects? I'm getting into the FAPI ahah property and I was wondering if there is a list of all the "standard" possible effects that would be available for use without adding any modules (i.e. additional libraries).

Thanks!
Stephanie

Accord with the Documentation you can use:

none (default)
fade
slide


What does General Cache Wipe mean The definition of CACHE_TEMPORARY used in cache_set reads as follows.

  CACHE_TEMPORARY: Indicates that the item should be removed at the next
  general cache wipe.

I am just curious as to what General Cache Wipe means and what constitutes to General Cache Wipe other than obvious cron.

Any action that makes a call to either cache_clear_all(NULL, $table); on all core cache tables or a call to cache_clear_all(); can be termed as General Cache Wipe

I could list down following based on a quick grep search for these functios.

Cron : Very obvious.
When a vote is submitted on a poll.
Any operation performed on admin/content page like

Node Multiple Delete. (Handled as a special case with confirmation form)
Any other operation like

When node access is rebuilt. (Like change of permissions)
When menu cache is cleared. (Node module clears all the caches [node_menu()])
Node Form Submission. [Creation or Updation]
Node Deletion
Comment Form Submission
Any operation performed on admin/content/comment page
Block administration. Any action performed on admin/structure/block
Create, Delete/Update any custom block.
Any forum form submit.
Any System Theme settings are changed.
When aggregator parses a feed.
Profile fields are edited/updated/deleted or their weights and categories are changed.
When a user account is cancelled.
When taxonomy term/vocabulary is added/deleted/updated.


Only front page works I am trying to set up a local server to try out drupal 8.1.3 and so far I was able to set up my profile and website but I cannot go to any pages other than the first page. (Welcome page, front page)

I have used the following link to install Drupal:

https://www.howtoforge.com/tutorial/how-to-install-drupal_8-with-apache-and-ssl-on-ubuntu-15-10/

Few things to note:

I'm not sure if I have CleanURL, tried to fix this issue but couldn't succeed I believe.
I have tried  multiple different approaches to fix issues like CleanURL, SSL connection, Apache2 (AllowOverride All) etc
I tried adding "?q=" and while this doesn't make the page crash, it just directs me back to the front page

Currently, I am playing around with four files to try to figure out my problem: ".htaccess", "apache2.conf", "drupal.conf" and "settings.php"

I want to be able to access the Drupal tools to modify the website and run it locally, I simply want to test Drupal, I wanted to share this because it may simplify the solution.

Some of the code that I have added while trying to fix my situation:

drupal.conf:

            <Directory "/var/www/drupal">
                    Options FollowSymLinks
                    AllowOverride All
                    Require all granted
            </Directory>

apache2.conf:

<Directory /var/www/>
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>

.htaccess:

RewriteBase /

# homepage redirect
RewriteRule ^$ /SUBDIRECTORY/index.php?q= [L]

# if directory or regular file...
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_URI} =/favicon.ico
# stop here
RewriteRule ^ - [L]

# if a regular file in SUBDIRECTORY directory
RewriteCond %{DOCUMENT_ROOT}/SUBDIRECTORY/%{REQUEST_URI} -f
RewriteRule .* SUBDIRECTORY/$0 [L]

# Redirect everything to /SUBDIRECTORY
RewriteRule .* /SUBDIRECTORY/index.php?q=$0 [QSA]

settings.php:

$settings['trusted_host_patterns'] = array(
  '^127.0.0.1$',
  '^localhost$',
  '^www.example.com$'
  );

PS. I have tried both localhost and an example website url like www.example.com but it didn't help.
PS2. I am only using Firefox currently but I don't think the problem is with the browser.

I hope I was able to follow the question guidelines, I am really trying my best to make it a question "suitable" to the website, I am sorry if I made a mistake.

Edit1: I have rewrite already enabled.

I believe the problem was due to the location of my .htaccess file. (The main problem was the Clean URLs.)

My original location was /var/www/drupal/sites/default/files; after, I moved it to
/var/www/drupal. The .htaccess file started to being read. Previously, it was not being read.

I hope this helps someone else! This also may not be the solution because I am having a different issue now.


Where can I find all form display options types for custom entity fields? I created a custom entity with drupal generate:entity:content.

I am adding fields in the baseFieldDefinitions method of the entity class.

Below is what drupal console generates by default for the name field.

Where I can find a list of all possible type values for ->setDisplayOptions('form'). For example, the field below uses string_textfield.

public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
    ...
    $fields['name'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Name'))
      ->setDescription(t('The name of the entity.'))
      ->setSettings([
        'max_length' => 50,
        'text_processing' => 0,
      ])
      ->setDefaultValue('')
      ->setDisplayOptions('view', [
        'label' => 'above',
        'type' => 'string',
        'weight' => -4,
      ])
      ->setDisplayOptions('form', [
        'type' => 'string_textfield',
        'weight' => -4,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

Those are field widget plugin IDs.

You can get all of those by querying the field widget plugin manager (service ID: plugin.manager.field.widget).

E.g. to get all the IDs in your entity class (once the service is injected):

$widget_types = $this->fieldWidgetPluginManager->getDefinitions();
$plugin_ids = array_keys($widget_types);

Same thing in procedural code in case someone wants it:

$widget_types = \Drupal::service('plugin.manager.field.widget')->getDefinitions();
$plugin_ids = array_keys($widget_types);

If your current context allows you to inject the widget plugin manager service rather than get it from \Drupal, all the better.


Complex condition drupal query I'm trying to add following mysql condition:

WHERE       DAYOFYEAR(curdate()) <= DAYOFYEAR(DATE_ADD(FROM_UNIXTIME(field_birthday_value, '%y-%m-%d'), INTERVAL (YEAR(NOW()) - YEAR(FROM_UNIXTIME(field_birthday_value, '%y-%m-%d'))) YEAR))
AND         DAYOFYEAR(curdate()) +7 >= DAYOFYEAR(DATE_ADD(FROM_UNIXTIME(field_birthday_value, '%y-%m-%d'), INTERVAL (YEAR(NOW()) - YEAR(FROM_UNIXTIME(field_birthday_value, '%y-%m-%d'))) YEAR))

To my db_select $query->condition:

//Build query
$query = db_select('users', 'u');
$query->leftJoin('field_data_field_birthday', 'fb', 'u.uid = fb.entity_id');
$query->condition('THE CONDITION MUST BE ADDED HERE');
$query->fields('u', array('uid', 'name'));
$query->fields('fb', array('field_birthday_value'));
$query->range(0,5);
$users = $query->execute();

But i can't figure out how. Simple conditions like =, <> are easy. But i got no clue how to add my more complex condition.

Thx

EDIT:
Should pay more attention to the documentation :). Ty!

//Build query
$query = db_select('users', 'u');
$query->leftJoin('field_data_field_birthday', 'fb', 'u.uid = fb.entity_id');
$query->where("DAYOFYEAR(curdate()) <= DAYOFYEAR(DATE_ADD(FROM_UNIXTIME(fb.field_birthday_value, '%y-%m-%d'), INTERVAL (YEAR(NOW()) - YEAR(FROM_UNIXTIME(fb.field_birthday_value, '%y-%m-%d'))) YEAR))");
$query->where("DAYOFYEAR(curdate()) +7 >= DAYOFYEAR(DATE_ADD(FROM_UNIXTIME(fb.field_birthday_value, '%y-%m-%d'), INTERVAL (YEAR(NOW()) - YEAR(FROM_UNIXTIME(fb.field_birthday_value, '%y-%m-%d'))) YEAR))");
$query->fields('u', array('uid', 'name'));
$query->fields('fb', array('field_birthday_value'));
$query->range(0,5);
$users = $query->execute();

As The Docs for condition says:

Parameters
$field: The name of the field to check. If you would like to add a more complex condition involving operators or functions, use where().

So let's see QueryConditionInterface::where:

Parameters
$snippet: A portion of a WHERE clause as a prepared statement. It must use named placeholders, not ? placeholders.
$args: An associative array of arguments.

Should do the trick for you.


Must implement interface > Drupal\Core\Entity\EntityTypeManagerInterface, none given in __construct() function I am trying to write a custom eventsubscriber for commerce 2.x for an event after a successful checkout. Everything works and now I want to create a __construct function to initialize an object, but then I get the following error:

  TypeError: Argument 1 passed to
  Drupal\custom_module\EventSubscriber\OrderCompleteEventSubscriber::__construct()
  must implement interface
  Drupal\Core\Entity\EntityTypeManagerInterface, none given, called in
  /home/user/websiteName/docroot/core/lib/Drupal/Component/DependencyInjection/Container.php
  on line 264 in Drupal\custom_module\EventSubscriber\OrderCompleteEventSubscriber->__construct()

I've tried explicitly defining the EntityTypeManagerInterface within the class, but everything is resulting in this error. Not finding anyone with any similar issues, and this particular block of code works for other people, just wondering what I am missing or If I am doing something incorrect. This code runs great if I don't construct an object with EntityTypeManagerInterfaceas the argument ... any ideas?

namespace Drupal\custom_module\EventSubscriber;

use Drupal\commerce_order\Entity\OrderInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\rng\RegistrantFactoryInterface;
use Drupal\state_machine\Event\WorkflowTransitionEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class OrderCompleteEventSubscriber implements EventSubscriberInterface {

  use StringTranslationTrait;

  /**
   * The registration entity storage.
   *
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected $registrationStorage;

  /**
   * The user entity storage.
   *
   * @var \Drupal\user\UserStorage
   */
  protected $userStorage;

  /**
   * The registration access handler.
   *
   * @var \Drupal\Core\Entity\EntityAccessControlHandlerInterface
   */
  protected $registrationAccessHandler;

  /**
   * The registrant factory.
   *
   * @var \Drupal\rng\RegistrantFactoryInterface
   */
  protected $registrantFactory;

  /**
   * Drupal\Core\Session\AccountProxyInterface definition.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;

  /**
   * Constructs a new OrderCompleteEventSubscriber object.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   * @param \Drupal\rng\RegistrantFactoryInterface $registrantFactory
   * @param \Drupal\Core\Session\AccountProxyInterface $current_user
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager, RegistrantFactoryInterface $registrantFactory, AccountProxyInterface $current_user) {
    $this->registrationStorage = $entity_type_manager->getStorage('registration');
    $this->registrationAccessHandler = $entity_type_manager->getAccessControlHandler('registration');
    $this->userStorage = $entity_type_manager->getStorage('user');
    $this->registrantFactory = $registrantFactory;
    $this->currentUser = $current_user;
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    return [
      'commerce_order.place.post_transition' => ['buildRegistration'],
    ];
  }

  /**
   *
   * @param \Drupal\state_machine\Event\WorkflowTransitionEvent $event
   */
  public function buildRegistration(WorkflowTransitionEvent $event) {
    $order = $event->getEntity();
    // do stuff
      }
    }
  }

}

Services.yml File

services:
   custom_module_event_subscriber:
      class: '\Drupal\custom_module\EventSubscriber\OrderCompleteEventSubscriber'
      tags:
        - { name: 'event_subscriber' }

A bit late but the code from EventSubscriber has three arguments so your services.yml file should read:

services:
  custom_module.order_complete:
    class: Drupal\custom_module\EventSubscriber\PurchaseBuildRegistration
    arguments: ['@entity_type.manager', '@rng.registrant.factory', '@current_user']
tags:
  - { name: event_subscriber }


How i change scripts in my custom theme in drupal 6 i write a custom theme for my site and i want to remove misc/tableheader.js script from site scripts and add my own tableheader.js instead.
is any way to i do it without changing original misc/tableheader.js file?

It's been a while but I think this is the way to do it in Drupal 6:

function MYTHEME_preprocess_page(&$vars) {
  // Add your JS
  drupal_add_js(drupal_get_path('theme', 'MYTHEME') . '/my-tableheader.js'));

  // Get the cached JS
  $js = drupal_add_js();

  // Remove the core tableheader file
  unset($js['module']['misc/tableheader.js']);

  // Change the scripts var to reflect the new array
  $vars['scripts'] = drupal_get_js('header', $js);
}


Drupal 6 node_load with conditions Here is the situation:

I have two content types. Content type a has a CCK reference field for content type b.

Now I am trying to load all the nodes from content type a that are referenced to content type b.

Here is the code that I have.

$nidcur =  $fields['nid']->content;

$node = node_load(array("field_micselect" => $nidcur));

dpm($node);

So I would like to load all the nodes that are related to the nid $nidcur.

This should work for you:

$referenced_nodes = db_query("SELECT `field_FIELD_NAME_nid` AS `nid` FROM {content_field_FIELD_NAME}");
while ($referenced_node = db_fetch_object($referenced_nodes)) {
  $node = node_load(array('nid' => $referenced_node->nid));
  // Do your stuff here
}


Calendar week views block dates Drupal 7.14 - Calendar Module 7.x-3.4

Does anyone have an idea how to display the dates alongside the week days on the week views block?

First you need to copy calendar-week-overlap.tpl.php from calendar/theme to your custom Drupal theme and add the following lines:

Add this code before html code - after line 30

$start_date = date_format($view->date_info->min_date, 'U');

After line 40 &nbsp;	 replace the following code

 <?php foreach ($day_names as $cell): ?>
    <th class="<?php print $cell['class']; ?>" id="<?php print $cell['header_id']; ?>">
      <?php print $cell['data']; ?>

  <?php endforeach; ?>

with this code

<?php $i = 0; foreach ($day_names as $cell): ?>
    <th class="<?php print $cell['class']; ?>" id="<?php print $cell['header_id']; ?>">
      <?php print $cell['data']; ?>, <?php print date('d/m/Y', strtotime("+$i day", $start_date)); $i++ ?>

  <?php endforeach; ?>


Change the front page value for logged in users On my site I have two front pages:

node/31, for anonymous users
calendar-node-field-journal-date/month, for logged in users

When a users clicks on the front page (which is rendered as $front_page in my page.tpl.php file), I want them to be taken to the appropriate front page.

However, if a logged in user goes to node/31 directly (e.g. by not clicking on the front page link) they should still be able to see the node (and not be re-directed).

After researching, I've found Rules is the best way to do this and there are instructions here.
However, this re-directs logged in users when they visit node/31. How can I get the Rule to only run when the user clicks on the $front_page link and not on the direct node/31 link?

I don't want to set it up via my theme, as I am sharing the theme on a multi-site. I also don't really want to install other modules, as I am already using Rules for other things.

I would recommend the Front Page module, not rules:

The Front Page module allows for customised home pages dependant on
role. The pages can be of the following types:
Alias (only 2.x branch) - Allows for another Drupal path to be shown
as the home page without redirecting the user.
Redirect - Allows you to redirect users to a local or remote URL.
Themed - Allows you to enter some static text that will be placed into the content area > of a standard Drupal page. Full - Allows for static content to be displayed
to the screen as is. This method does not pass through Drupal's
theming system.


Getting the media URL in a views field I'm using Drupal 8.5. I have a content type with the in-core media module. I'm making a view for content syndication, and I need one of the columns to be the FDQN URI to the media resource-- i.e, not the rendered entity itself (which comes through as an img tag), but https://example.com/sites/default/files/media_image.jpg.

I've added the media field to my view, but I didn't find any Formatter, View Mode, or Rewrite Pattern that gives me the absolute URL to the resource. I can get the path to the media (e.g. https://example.com/media/1899), the entity_id (e.g. 1899), but no path to the file.

How can I render the path to the media image in my view?

The media field is an entity reference type field.  You will need to add a relationship to the media entity.  This should add the URI field in media entity to the view selections.  You should then be able to select this (with the right reference relationship) and use the standard URL formatters.


Caching Panel page variants I don't believe I have never run into this before, but I have a Panels page with a few variants based on selection rules.  Is there a way that you can serve up cached results for the whole page (not just the individual panes) after the selection rules have run?  I am not seeing any options or other modules to get Page Manager to do this.

Did you try any off the following module

Panels Page Cache

  This plugin can cache panels based on the path/url (arg() structure).

  This is needed if a panel has content which is dynamically per page
  (eg ad-tags, content related items).

Panels Hash Cache

  This module provides a hash-based cache for Panels and other Chaos
  Tools powered displays.
  This support caching based on any combination of:

Contexts (node, term, user etc)
Arguments
Drupal Path (args) (same as the Panels Page Cache Module)
Full URL (including domain and query string)
Users
Roles


7 - FAPI: form_set_error messages on bottom of page or dialog box My ajax FAPI multi-step form is rather large, the error validation message are located by default at the top. But users can't see these messages as they are clicking submit on bottom of a large form (scroll down).

Editing the $messages in the template has no effect on de FAPI vailidation.

Is there a way to place it in a dialog box or at the bottom?

Perhaps the Inline Form Errors module is useful to you. It provides Inline Form Errors (as the name implies). More details from the module's project page:

IFE or Inline Form Errors allows you to place form submission error inline with the form elements. Three options are provided for setting your inline error behaviour. You can configure the default behaviour or override the behaviour on a per form basis. You can add as many forms as you like.
IFE provides three behaviours for the configured forms

Leave the messages in place, this option will copy the error messages and place them inline. The original error messages set by Drupal will remain in place.
Show an alternative message, this option will replace the original messages with a generic error message such as 'Please correct all errors.'. This message can be set in the IFE configuration page. The original error messages are placed inline with the form elements
Remove all messages, this option will remove all error messages and place them inline with the form element

In all cases only the messages related to the form will be touched. All other messages will remain in tact.


Imported views from other site that didn't have any Master display in the UI. How to remove Master display from Views UI? I wanted to reuse some View I built on older site which is using EVA module and contextual filters and so on. So I just re-imported it to my new site and now from nowhere there's that Master display showing up (while on older site its not shown) when editing view and the view cannot be saved because it gives me error:

'Display "Master" uses fields but there are none defined for it or all are excluded.'

The problem is that I don't need that master display at all. How is that it popped up from nowhere?

A view will always have a master display. You can set it to not display on the views settings page at 'admin/structure/views/settings'. To get rid of the error you are seeing, just a add field to the master display, or set the display to show content instead of fields.


Image style and loss of fidelity There is at least one other question dealing with this, but I found no satisfactory explanation, let alone a solution.

My site used to deliver 800x600 native images hosted externally that were scaled by the browser and CSS. To improve the Google Page Speed, my client asked me to ingest and serve the images on the Drupal site and to size them on the server.
So far, so good.

Now I am noticing a big degradation in quality - not good for a real estate site:

(this is slightly enlarged to better show the issue)

On the right is the old site with scaling/cropping done by Chrome from 800x600 down to 315x208, left is the new site with an image style using imagemagick set to 100% quality, doing the same size reduction and cropping. I tried the "resize" filter but that has the same issue and does not give me the desired results.

The images are not from a stale cache, the image field max size is 800x600, and the file on the server is unaltered and has the original size. It is definitely the image style filter that is causing this.

Previous recommendations were to increase the quality setting for the image toolkit (admin/config/media/image-toolkit), switch to imagemagick, and ensure that the max resolution of the image field does not cause scaling. I have done all that and don't see any improvement.

Any other suggestions?

I was wrong about not pulling from a stale cache. Credit goes to Jeff who does not want it:

Changing a filter does not mean the image toolkit renders the image again. This only happens once the /files/styles folder is cleared out. Once I did this, the quality improved and I don't see a difference between old and new anymore.


Creating a shortcut to a listing of a specific content type or a set of specific nodes I want to create a shortcut that acts similar as when you click the "Content" link. But I want to be able to display only a specific content-type or probably a specific set of nodes.

Is this possible weather by coding or through a module?

You can do it with the Views module and some additional extensions.

The easiest way to do it is to install the Administration Views module (and all of its dependencies). It provides administrative lists just like you get from Drupal core, except they're built using Views.

Once you have that installed, go to /admin/structure/views. Clone the "Administration: Nodes" view provided by Administration Views, change the node type filter to be fixed instead of exposed, change the system path setting (eg. /admin/content/my-node-type) and save it.

That should be all - let me know if I messed a step or if something is unclear.


How do I update the URL after changing the hosting of a website? Our website recently changed hosts. After updating the named servers the home page shows but all links in the page take you to 404 error.  The new host advises that the URL links need to be refreshed.

There are a couple of possibilities when this happens. The first is to make sure that you still have an .htaccess file, as moving between hosts sometimes doesn't include the hidden files.

If you do have it, depending on the server, the Symlinks may need to be changed. For instance my Ubuntu server needs the .htaccess file to be changed to this in order for it to work

#Options +FollowSymLinks // Commented out
Options +SymLinksIfOwnerMatch

The next possibility is that the DNS propagation hasn't finished yet. It can take up to 72 hours with some hosts before everything is fully refreshed and pointing the right location.


How do you modify modules/templates without waiting for the cache? I'm a beginner at both php and drupal, I know some PHP, at least enough to modify templates and add/remove content from modules, but what irks me is that I always have to wait around 60 seconds for the changes to be visible.

Now I've heard about using the Admin Menu to flush all caches, I've tried every single module that claims to flush the cache, but I still have to wait 60 seconds for the changes to appear

I've also tried disabling the cache by modifying settings.php, to no avail.

As I've said, I'm a beginner at both php and drupal, is this a browser-side cache? or am I missing something?

This most likely is a server-side-cache related issue. I have also experienced this with my hosting. Try contacting your hosting provider about this issue or try to find a setting to turn off the server cache in your hosting's admin panel.


problem in admin_path module with my custom content type paths I have created a content type "Test".

The content which I created of type "Test" have the paths like this "test/content1, test/content2 etc. means test/*".

So I entered the path "test/*" in the administrative pages.

But when I try to open any content of type "Test", First the url becomes like this "#overlay=test/content1" and then it redirects to "test/content1" and does not appear in overlay.

I tried some other paths of the contents of some other types and they are working fine in overlay.

So what is the problem with my custom content type? Any one who have some idea about t his?

Check out overlay_paths module. Should solve your problem. Sounds like admin_paths() isn't accepting up your url aliases. http://drupal.org/project/issues/overlay_paths.


Uninstall or delete modules when upgrading 6 to 7? Sorry to ask such a basic question, but I can't find an answer (and I'm an amateur).

I have a website that was written for me in Drupal 6. I want to upgrade it to Drupal 7.

There are quite a few contributed modules, and I realise I need to disable these before upgrading the core. Can I then simply delete the unused modules via FTP, or do I have to use uninstall within Drupal?

Updated after re-reading your question. :)

The process for completely removing a module is generally:

Backup your site.  The Backup and Migrate module is great
here too.
Disable the module. Admin -> Modules -> Uncheck module ->
save.
Uninstall the module - Goto yoursite.tld/admin/modules/uninstall ->
Check Modules to uninstall -> Click Uninstall
Delete the module - Delete module directory.

Additionally you can find details regarding upgrading from previous versions of Drupal at drupal.org.

Another useful module is the Upgrade Status module.  Listed only for reference.


what is the difference between a load callback and list callback in the i18n hook_i18n_object_info() function? I am learning how to use the i18n module to translate a module. In hook_i18n_object_info() implementations, I have noticed other modules using list callback or load callback.

What is the difference?

A list callback is a callback that returns all the objects of a specific type; for example, for content types, the list callback is node_type_get_types().
A load callback is a callback that loads a single object of that specific type; for content types, the load callback is node_type_get_type().

Reference

hook_i18n_object_info()
i18n_node_i18n_object_info()


Module version format I would like to know what is the correct version format for custom modules in Drupal 7.
I see some contributed modules come with 7.x-1.2-rc1. I don't know what is rc1.
When I name my custom module with version 7.x, my module didn't work in module installation and it wasn't enabled. When I name the version 7.x-1.2, it works fine.

Is there any documentation for Drupal module version format?

Release naming conventions reports exactly the format used for the release names, and how they are formatted.

In short, the format is [Drupal version].x-[major version]-[minor version]-[flags].

Drupal version is the Drupal version with which the module is compatible
flags are extra identifiers that starts with one of the following string:

unstable
alpha
beta
rc [a.k.a. release candidate]

For a development snapshot, the format is [Drupal version].x-[major version]-x-dev.

"Major version" and "minor version" refer to the module version, where "minor version" is a progressive number.

As for the module not working if the release number doesn't follow the schema, I think the problem is another one; as far as I know, Drupal doesn't check the format, and the release name is only used from the update manager, when it is looking for the module updates, and the module is hosted on Drupal.org.

You should not be worried about the format used for the release version identifier, if not when you are developing a module that is host on Drupal.org. If you are developing a custom module that is not hosted there, you don't need to report the module version. In fact, in my test site I have a test module that doesn't report its version, and Drupal is still able to use it; the only difference is when another custom module depends from that, and it is reporting with which version of the first module is compatible. Then, Drupal will not show the module version in the module page, if the .info file doesn't report that.


How to get uri from Url object in twig? I want to inject Font Awesome icons to user menu based on the route/link of each item.

But it looks like there is no way to get the path grom the url object. I tried everything I could think of but nothing worked. It's like the url object won't give any data in Twig.

This is what I am trying to do in menu template for user acocunt:

                    {% set uri = path(item.url.routeName) %}

{{ dump(item) }}

{{ dump(uri) }}

                    {% if uri == 'user' %}

                    {% elseif uri == 'user/logout' %}

                    {% elseif uri == 'user/register' %}

                    {% elseif uri == 'user/login' %}

                    {% endif %}
                    {{ link(item.title, item.url) }}
                    {% if item.below %}
                        {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
                    {% endif %}

{% set uri = item.url.toString %} will also work.


Cache front page for logged in users I'm having a performance crisis with my front page.  I have the standard drupal cache enabled which works great for anonymous users, but my front page is practically unusable for logged in users.

The front page doesn't contain any user-specific information, so it would be great if the front page was always cached version for all users.

Actually, there is a user account link in the header which is user-specific, but I'd be willing to forgo that (display as anonymous) for the quick, all-encompassing solution.  I'm working on a real caching solution for logged in users, but I'd like a quick fix like this.

AFAIK there is no easy way of getting a cached page as though the user was anonymous.

The easiest solution is probably to cache the elements of the front page, but that's hard to say without knowing how it's built and what's elements it consist of.


is there a place in the .info file to set a url to check for updates? I created a custom theme to serve as the base for all my company's future drupal projects, that includes all of our base requirements. The sites will live on different servers, and each site will have it's own subtheme.

Drupal themes compare versions w/ the drupal projects server to check for updates.

I do not want to submit my company's theme to the drupal.org, as it has company specific features.

The goal is to be be able to update the theme in a "local" central repository, and have the various drupal sites check for version updates.

is there a place in the .info file to set a url to check for updates?

The version number is pretty easy to set.

Yes, you can use project status url:

  Allows module maintainers to define a URL to check for updates to their module using the Update status module. No module released on drupal.org should define this parameter. URL should point to an XML feed that accepts requests in the form of http://my.domain.com/projects/{project}/{core}. In that example, project status url should be set to http://my.domain.com/projects.

See Writing module .info files (Drupal 7.x) for full details.


Extend Drupal 6 "form_token" & "form_build_id" I'm posting in my website by using command line.

Below codes works just fine for me

curl -b cookies.txt -d title="$(my-own-sed-command)" -d taxonomy%5Btags%5D%5B1%5D="$(my-own-sed-command)" -d teaser_include=1 -d body="$(my-own-sed-command)" -d field_source%5B0%5D%5Burl%5D="$(my-own-sed-command)" -d changed= -d form_build_id=form-2bef00e4e4c6c53c1cedfc61e857186b -d form_token=883b4e7f69cdd1bf3311854732eff3f7 -d form_id=post_node_form -d op=Save http://www.mywebsite.com/node/add/post

Usually I will post several times a day using above command. But the problem is; sometime I will take a rest for 2 or 3 days. After 2 or 3 days, the "form_token" & "form_build_id" has expired.

In order to prevent expiration, how to extend the "form_token" and "form_build_id" to become 7 days?

Any ways are welcome; hacking the core, disable token for this node type submission, etc.

TL;DR: Those values will not expire if

you use the same user to log in to the site
the PHP session is not expired
Drupal finds in its cache the form array associated with "form_build_id."

The token used for "form_token" is the one created using with the following function call: drupal_get_token($form['#token']); the only value that changes in that function call, for the same form, is session_id() which is invoked from drupal_get_token().

function drupal_get_token($value = '') {
  $private_key = drupal_get_private_key();
  return md5(session_id() . $value . $private_key);
}

The value returned from drupal_get_private_key() is unique for each Drupal site; the only way to make it change is to delete the Drupal variable "drupal_private_key" that is never deleted (if there isn't a third-party module that delete it), but it is initialized when Drupal is installed. The value returned by session_id() is the same each time drupal_get_token() is called, if the logged in user is the same, and the PHP session has not yet expired.

As for the value of "form_build_id," its value is totally random, initialized from drupal_prepare_form() using the following code:

  if (isset($form['#build_id'])) {
    $form['form_build_id'] = array(
      '#type' => 'hidden',
      '#value' => $form['#build_id'],
      '#id' => $form['#build_id'],
      '#name' => 'form_build_id',
    );
  }

$form['#build_id'] is initialized from the following code in drupal_get_form():

  $form_build_id = 'form-' . md5(uniqid(mt_rand(), TRUE));
  $form['#build_id'] = $form_build_id;

As you are passing the value of "form_build_id," and "form_id" in the POST data, then the following code is executed (see drupal_get_form()):

if (isset($_POST['form_id']) && $_POST['form_id'] == $form_id && !empty($_POST['form_build_id'])) {
  $form = form_get_cache($_POST['form_build_id'], $form_state);
}

If the cache contains the form, then "form_build_id" is not generated again.


How can I change the file private URL So I've uploaded a private file. It can be accessed like following:

http://drupal8.dev/system/files/2016-12/README.txt

How can I change how that file is accessed?

http://drupal8.dev/files/README.txt, etc.

Assuming I understand the question: To the best of my knowledge, you cannot. For a file in the private file system, the file URL must be rendered on a page in order to be accessed. Redirects and rewrites won't work.


How to create a page with all the nodes of a specific user? My users' profile pages contain a View with their 4 latest nodes. I would now like to add a "more" link underneath that View that redirects visitors to a page with all the nodes of that user.

I can easily create a View with all nodes of a specific user, but I don't know how to generalize this and create a page for every user. Am I making things too complicated? Maybe this is a triviality, but I can't find a solution on the internet...

Nope, that's totally fine. What you are looking for is the power of Views' built-in contextual filters. With that you can pass arguments from an URL to a view.

  The classic example of how contextual filter values are provided to
  views is by the view path. If a view has the path example.com/my-view,
  the URL example.com/my-view/story/22 will call the view along with two
  values for contextual filters (in this case story and 22). But there
  are more ways of providing contextual filter values.

Just a rough outline so you can get the idea:

Build a Views page with a path that contains a wildcard. Let's say it's usersnodes/%
Build the "more" link on the user's profile page then to dynamically hold the user's uid. So that would be usersnodes/123 for example.
In the view you created in step one now set the contextual filter (I think it's on the very right in the UI). There you have to possibility to grab an argument (or two, or three ...) from the URL and pass it as a contextual filter to the view to only get the nodes of the user whose uid was in the URL.


How NOT to cache a hook_menu callback I wrote a callback in my hook_menu() implementation, wich won't work the way it is intended to because of caching. The callback just returns some text depending on a cookie. Something like that:

function _show_logoutpage(){
    if($_COOKIE['foo'] == true) {
        return 'foo';
    }
    else {
        return  'bar';
    }
}

The code is called after the user is logged out so I would say the user is anonymous. Problem is the the output is cached (since the last menu cache clear) so the logic won't work.
Any idea how to fix this in a simple way?

$GLOBALS['conf']['cache'] = FALSE;

See also module CacheExclude, here are some more details about it:

  This module provides a simple way to exclude certain pages from being cached. Sometimes you want all pages to be cached for anonymous users except for one or two pages that have dynamic or random or rotating content. If those pages are cached, the dynamic parts cease to be dynamic. This module allows an administrator to selectively exclude certain paths from being cached so that dynamic content is actually dynamic.


how to insert a search form in custom content I'm trying to insert a search form in the middle of some custom HTML on a Panel Page.  There's already the Search Block on the page somewhere else.  The Search Widget is available, but it gets inserted after the custom HTML, which is not what I want.  I thought I could do something like
http://api.drupal.org/api/drupal/modules!search!search-block-form.tpl.php/7

<?php if (empty($variables['form']['#block']->subject)): ?>

<?php print t('Search form'); ?>

<?php endif; ?>
<?php print $search_form; ?>

or

<?php
drupal_get_form('search_form');
?>

but the PHP doesn't seem to execute (naturally, I have PHP selected as the input.).

Edit:
This produced a search form in the correct place, but the CSS conflicts with the existing Search Block.

<?php print render(drupal_get_form('search_block_form')); ?>

I was close but needed to declare the variable.  I still don't really understand what's happening here, but it works.

<?php global $search_form; print render(drupal_get_form('search_form')); ?>


How to get the distinct number of the nodes? In my task I need to get the distinct number of the nodes of some content type. How can I do it?

$query = $this->connection->select('node', 'node')->condition('node.type', $type);
$query->addExpression('COUNT(*)');
$query->innerJoin('taxonomy_index', $id,  "$id.nid = node.nid  AND $id.status = 1");
$count = intval($query->execute()->fetchField());

As the node may have multiple values for the field, in the end it counts all nodes and produces the wrong output. Therefore I need to get distinct number of nodes.

Just adding $query->distinct(); doesn't bring anything. Could you please help me how can I solve the issue?

If you want to retrieve distinct number of the nodes of content type $type.
Try this.

use Drupal\Core\Database\Database;

//- Retrieves a \Drupal\Core\Database\Connection which is a PDO instance
  $connection = Database::getConnection();
    $query = $connection->select('node', 'node')
        ->fields('node', array('nid'))
        ->condition('node.type', $type, '=')
        //- Force filtering of duplicate records in the result set.
         ->distinct()
        ->countQuery()
        ->execute();

    $count = $query->fetch(\PDO::FETCH_NUM);

Ps: you still have to add Your desired innerJoin to the query take a look to Select::innerJoin .


When exiting views modal I am returned json When I am in views UI and I edit an option a modal box appears. I edit some seetings then press save and am displayed with something like:

  [{"command":"settings","settings":{"basePath":"/","pathPrefix":"","ajaxPageState":{"theme":"bartik","theme_token":"SUIsCUisas2D3yeSiBkGNwaXtTMtlVVXouHWgoffCYA"}},"merge":true},{"command":"viewsDismissForm"},{"command":"viewsShowButtons"},{"command":"viewsTriggerPreview"},{"command":"insert","method":"html","selector":"#views-tab-block","data":"\u003Cdiv
  id=\u0022edit-display-settings-details\u0022\u003E\u003Cdiv
  id=\u0022edit-display-settings-top\u0022
  class=\u0022views-ui-display-tab-actions views-ui-display-tab-bucket
  clearfix\u0022\u003E\u003Cdiv class=\u0022ctools-no-js ctools-button
  ctools-dropbutton\u0022\u003E\u003Cdiv
  class=\u0022ctools-link\u0022\u003E\u003Ca href=\u0022#\u0022
  class=\u0022ctools-twisty
  ctools-text\u0022\u003Eopen\u003C/a\u003E\u003C/div\u003E\u003Cdiv
  class=\u0022ctools-content\u0022\u003E\u003Cul class=\u0022horizontal
  right actions\u0022\u003E\u003Cli class=\u0022duplicate ...

What could be going wrong?

Make sure you use the default jQuery version (1.5) when using The Views UI module.


Newbie question : where to put "advanced" page content? It's been almost 3 years that I'm a web developer and I just started with Drupal 8. I have to say that's I'm feeling really confused by all the things in the Drupal worlds that you have to understand in order to create a website.

Here is the thing, I'm supposed to create a little website (3 pages for now) with a 100% custom appearance. I started by creating a new Drupal 8 theme with its libraries and dependencies and started coding the website's layout in twig. I added a few blocks in the theme's configuration (and in the twig) like a header block, two highlights blocks, a main content block and so on.

I'm at the point where I finished the layout and I'm supposed to add content of the 3 pages :

A main page containing text, images, a thumbnail of the last posted photos album, and an overview of the two last posted articles.
A form who's supposed to store the data somewhere (in the database I guess).
A second form who's supposed to do quite the same.

My questions are :

Since I have a very specific content for my three pages with HTML/CSS and Javascript, where am I supposed to put it ? Simply in 3 separated "Basic page" in the "Content" section of Drupal ? It seems way too simple. The "Basic page" content isn't supposed to be only text/images ?
I'm using a "naked" Drupal. In order to create the forms and other special stuffs, I'm supposed to use modules, right ? Are there any that are mandatory ?

Thank you all in advance, and please excuse my English, it isn't my mother tongue.

IMHO it's easier to start with content, and add the design once the content structure is ready. Drupal tries to separate content and design as much as possible, so you can always change one and keep the other.

There are no mandatory modules, especially with Drupal 8 you can get very far without any additional modules.

Drupal stores the content of a page as "nodes". Nodes have a type, like "article" or "product". You can use the default node types that you get out-of-the-box, or define your own. Each node type has a number of fields, like a text fields, image fields, date fields, etc. You can enhance node types by adding additional fields. Drupal will take care of rendering those fields on a form, storing the content in the database, and displaying the content on the page. There is a lot more I could say about this, but I recommend that you read the documentation, especially the part about content structure.


Migrating XML data with many-to-one relationships I'm using Drupal 8's migrate system to import data from an XML source which has this simple layout:

<books>
    <book>
        <isbn>...</isbn>
        <title>...</title>
        <author>...</author>
    </book>
</books>

My code creates 'book' and 'author' entities on the Drupal side, with each 'book' referencing its corresponding 'author'. The problem is that different books can have the same author. This ends up creating a separate 'author' entity for every occurrence of the same author in the XML file.

I've looked at the $row variable in PrepareRow to see if there are ways of manipulating the ID map table to avoid the duplicates but haven't had any luck. So I'd appreciate any suggestions or ideas!

By the way, my code has two source plugins - one for 'author' (which runs first) and another for 'book'. I'm using the 'plugin: migration' in my YAML file to make the book entity pickup the author entity's ID. It all works except that author gets duplicated.

I ended up not using the "plugin:migration" option because apparently it assumes one-to-one relationships. So instead, I added code to the 'author' plugin's prepareRow to rejected incoming duplicate authors. Then I added code to my 'book' plugin's prepareRow to retrieve the author entity ids from the database and add it to the book entity. I was hoping for a built-in solution in the migrate system but this will do.


Why is my library not attached when programmatically rendering a block? I have this block:

public function build() {
  $build = [
    '#attached' => [
      'library' => [
        'mymodule/mylibrary',
      ],
    ],
    '#markup' => '<!-- see template -->',
  ];

  return $build;
}

Somewhere I am rendering this block via custom text filter:

{{ '[embed:block:mymodulemyblock]' | text_format }}

This is my text filter that replaces the "token" with the rendered block:

public function process($text, $langcode) {
  if (preg_match_all('/\[embed:.+\]/isU', $text, $matchCodes)) {
    foreach ($matchCodes[0] as $index => $token) {
      $parts = explode(':', $cleaned);
      array_splice($parts, 0, 1);

      $entityType = trim($parts[0]);
      $entityId = trim($parts[1]);
      $viewMode = isset($parts[2]) ? trim($parts[2]) : 'full';

      if ('block' == $entityType) {
        $rendered = '';

        if ($block = entity_load('block', $entityId)) {
          $replacement = entity_view($block, 'block');
          $rendered = drupal_render($replacement);
        }
      }
      $text = str_replace($token, $rendered, $text);

    }
  }
  return new FilterProcessResult($text);
}

It works fine, except the block's library isnt attached. Not even when I add this inside the block template:

{{ attach_library('mymodule/mylibrary') }}

When I place the block in the block layout it works fine.

Why isnt the library attached?

Edit

This is how I register the template for the block itself:

function mmodule_theme($existing, $type, $theme, $path) {
  return array(
    'block__mymodulemyblock' => array(
      'render element' => 'elements',
      'template' => 'block--foobar',
      'base hook' => 'block',
    ),
  );
}

I think it's because attached needs to be a separate element than your markup.

This is one render element for markup, with the attached attached to it:

$build = [
    '#attached' => [
      'library' => [
        'mymodule/mylibrary',
      ],
    ],
    '#markup' => '<!-- see template -->',
  ];

The correct way to set up a build array is with the markup being a separate element:

$build = [];

$build['#markup'] = ['#markup' => '<h1>testing 123</h1'];

$build['#attached']['library'] = ['mymodule/mylibrary'];

return $build;