Is it necessary to clear site caches after putting site into maintenance mode? I enabled maintenance mode on a Drupal 7 site; however, when I checked the homepage as an anonymous user, I noticed that the original homepage was still being displayed rather than the maintenance page. It was only after clearing the site's caches that the maintenance page was displayed. Anonymous page caching is enabled on the site.

I am wondering if it is necessary to clear the site cache's for maintenance mode be be effective or is it sufficient to just enable maintenance mode in the admin UI? My main objective to be able to safely run database updates, which should be run whilst the site is in maintenance mode. The actual display of the maintenance page is not really important.

As you stated that 'The actual display of the maintenance page is not really important' hence it is not necessary to clear the site caches in this case.

But it is best practice to do so, because if any user interactions like forms are there, user will be getting error messages!!


Empty title on one View based on Taxonomy Terms I'm struggling with a couple of pages that won't propagate a page title.  Because the view is based on Taxonomy Terms I want it to change the page title to the taxonomy term it's using. I've spent hours going through different drupal blogs etc to try and trouble shoot the problem but nothing's working.  The site is www.skyviewelectronics.com and the problem pages are all the pages that use the collection Taxonomy Terms:
/collection/cables-and-connectors
/collection/cell-phone-signal-boosters
/collection/clearance
/collection/computer-software
/collection/computers
/collection/data-storage-and-backup-drives
/collection/hd-tv-antenna-accessories
/collection/hd-tv-antennas
/collection/high-speed-internet
/collection/networking
/collection/notebook-bags
/collection/protection-and-cleaning
/collection/security

I've turned off the Metatag View module since some people report that is a problem.
Here is the options for my view:

Here is the options I have for the contextual Filter under content: has taxonomy term ID (with depth)  - I've also tried without depth, and many many many other combos...

Can anyone help??

Ok I found the answer (might not be the right answer but it's working).  I changed the "title" section in the View to %1 %2 and it started pulling from the metatag title section in each taxonomy term.


Can someone help me with contextual filters in profile2 I would like to single out a second profile with a views page using basic taxonomy reference or user information. Can you help me get my contextual filter to work with either user id, profile id, or taxonomy reference. I have my view to show users of a particular roll type. All users of this type will have a unique taxonomy reference ( or tag). When I choose fields for this tag in contextual filters and test it using the tag I don't get any results.

I was able to (finally) populate something on the user id. I guess it's the best way because I am going to be using rules to handle the information after the profile is created. Unfortunately, for some reason when I create a new user sometimes one of my profile id's is set to '0' shrugs which throws off the population of the field (check this especially if you use profile2_regpath).

How I was able to do it was to like this

I referenced the profile based on user id... then I drew three relationships on the profile, the profile type, and the user id.  I finally chose fields that substantiate the information I needed the user to see (in this case they are just testing it out). Please let me know if there is another way. I'm assuming there has to be something else out there or something I am missing. It populates one user at a time based on the profile owner's user id.


Is there a module equivalent for Suggest a Friend for Drupal 7? I am creating a social networking site for which I need the Suggest a Friend module, but it is not available for Drupal 7. Is there a similar module for Drupal 7?

Very powerful social networking module for creating inner social network for Drupal 7 is User Relationships.

It is well supported so i guess you can accomplish what you need.


Get the language from route Is there a way to get the language from a routeMatch in Drupal 8?

E.g. if I do:

$route_match = \Drupal::routeMatch();

Currently I can't find any language information in the returned object.  It looks like as if all language information has been stripped out, and the route object know's nothing about the language it is in.

I've looked into using the language manager, but can't find a way to combine this with the routeMatch class.

Scenario:
I'm writing my own AccessInterface class, and want to hide entities from certain languages.  I need the information of the language for the route (and not the site's current language).

I actually had the same problem with a Drupal 8 site.

I know this is unlikely to sound like a problem, but I can think of at least one situation (the situation I am in!) where it is.

We have the CMS setup so that the admin interface is in the users preferred langauge (a request by the client) so they can copy-paste translated content in whilst keeping the admin interface in a language they can understand.

However this creates confusion, as \Drupal::languageManager()->getCurrentLanguage() returns the langauge the admin system is using, not the lanuage the content is in.

The easiest way I found around this was to do the following:

$node = \Drupal::routeMatch()->getParameter('node');
$currentLanguage = $node->langcode->value;

(if anyone is curious as to why $node->langcode->value works, this question has some good answers: How to get the property of a content object in Drupal 8)

This literally gets the current node you've viewing, and then the language the node is displaying in.


Displaying articles created by user in profile page using views I want to display the articles created by user in user profile page. It should also display to anonymous user also.

For example : twitter.com/google displays all tweets by google.

Like that I want to display xyz.com/john. I want to display all articles created by john in user profile page.

I also want to know how to add that view to profile page.

Create a view for content of type all
Inside the view display node title and all other fields as per your requirement.
Add a contextual filter content : author uid
While adding that you will have a option for provide a default value
select that option and inside that use filter by 'currently logged in user'.
Save it by this you will be able to see all the nodes of current logged in user.
Inside the path you can enter just any path like '/my-nodes'. and you are done.
If you want you can avoid providing default value and switch to manual input
by placing the path as '/my-nodes/%' and then just add contextual filter as 'content : author:uid' without default value(depends as per the requirement).

For user name you can add a relationship content author:uid then
 in the contextual filter use User name with relationship author:uid


invoking a block and attaching it to a specific html element I have been having this problem for quite some time now and I don't know how to proceed.

I am trying to get a block by invoking it, the simple way:

 $block2 = module_invoke("module", "block_view", "nameofblock");
  print $block2["content"];

and insert it after a specific div with a unique id.

I tried using JavaScript and jquery:

(function($,Drupal,window,document,undefined){$(document).ready(function(){
$('#page-title,page').append('#invokedblockid');
 });})(jQuery,Drupal,this,this.document);

//and

document.getElementById("page").appendChild(document.getElementById("invokedblockid"));

//and all these

(function($) {

$(window).ready(function() {
$("page-footer-wide").detach().append("page-title");
$("#faresisgod").insertBefore("#page");
$("#faresisgod").appendTo("#page");
});})(jQuery)

but still the block is rendered where i originally added it, and if i put php inside of javascript, the new block will return a  and close my script prematurely...

so is there a way to show this block in the specific div id by using javascript/jquery or is there a way to use php aray to check for the required id then invoking the block.

this is giving me a headache for quite sometime and i am out of options.

thanks in advance

You can achieve this by creating a custom module which prints block content as shown below:

<?php
function mymodule_menu(){
    $items = array();

    $items['ajax/replace/block'] = array(
        'title' => t('Ajax Block'),
        'page callback' => 'ajax_callback',
        'access callback' => true,
        'type' => MENU_NORMAL_ITEM
    );

    return $items;
}

function ajax_callback(){
    $block2 = module_invoke("block", "block_view", 1);
    print $block2["content"];
}

Then add following jQuery line in your page to replace the target element with block content:

jQuery("#target-selector").load("/ajax/replace/block");


Create a custom form from Custom Content Type & Save it I've created a custom content-type using GUI interface.

I need to customize the form which takes input while creating a content of the content-type. I can do this by hook_theme implementation but I'm trying to create a brand new form, and save the content's fields in database, so that it appears as a full-functional content of my content-type.

How do I create a form (I know how to create forms in my custom module) that contains the fields (all, or selectively some) of my custom content-type?
Most Importantly, when the form is submitted, how do I save the fields so that it appears as a brand new content-type?

I think I've made it clear, please answer, or ask me to clarify the question more if necessary...

node_form will give you a form for your content-type, just pass a node.object having your content-type ($node->type) and maybe something more .., plus the content-type needs to be registred already i guess

saving is handled automagically ...


How to union two views and pass on arguments I want to union two views and pass on arguments from the first to the second view. Below is what I have so far. Not sure, if this is working. At least the bit to pass on arguments is still missing. Any ideas what I should put in the code?
use Drupal\views\Views;
use Drupal\views\ViewExecutable;

/**
 * Implements hook_views_pre_execute().
 */
function mymodule_views_pre_execute(ViewExecutable $view) {
  if ($view->id() == 'music_by_year' && $view->current_display = 'block_2') {

    $view_by_author = Views::getView('music_by_author');
    $view_by_author->setDisplay('block_1');
    $view_by_author->build();

    $query_by_author = $view_by_author->build_info['query'];

    $query_by_year = &$view->build_info['query'];
    $query_by_year->union($query_by_author);
  }
}

What you can do is to load and execute the $view_by_author view as you are doing but passing the by_year  arguments/contextual as this:
$arguments = [$view_by_year->build_info['parameter_you_need']];

$view_by_author = Views::getView('music_by_author');
$view_by_author->setArguments($arguments);
$view_by_author->setDisplay('block_1');
$view_by_author->preExecute();
$view_by_author->execute(); // or build, etc

I believe something like this would work for you.
Also, there is a module called Views Field View that might do what you are trying to do.


image_style_url doesn't create images I am using image_style_url to get a thumbnail of a picture I added through the administrator interface.

// $foo->field_picture['und'][0]['uri'] has value public://foo.jpg
image_style_url('foo-thumb', $foo->field_picture['und'][0]['uri']);

The API states that the image will be created when the URL is requested. However, when visiting the page the image isn't displayed (404). The URL returned from the function seems to be well formed, but the file hasen't been created.

The 'foo-thumb' folder is in the public data folder and the file permissions should be OK. I tried flushing the image cache (drupal image-flush foo-thumb) but still no results.

Any ideas?

From: https://drupal.org/drupal-7.20-release-notes

In addition, any code which programmatically generates a link to an
image derivative without using the standard image_style_url() API
function will no longer work correctly if the image does not already
exist in the file system, since the necessary token will not be
present in the URL.

Instead you can do something like this;
$image_uri      = $node->field_image[LANGUAGE_NONE][0]['uri']; // or any public://my_image
$style          = 'my_style';
$derivative_uri = image_style_url($style, $image_uri);
$success        = file_exists($derivative_uri) || image_style_create_derivative(image_style_load($style), $image_uri, $derivative_uri);

$new_image_url  = file_create_url($derivative_uri);


Not able to add new CCK field to custom content type Today all of a sudden I found out that I can no longer add custom CCK fields to any of my custom content types. The right most drop down box to select the field type is now disabled!!

When I try to add to the field anyway, I get an error:
Add new field: you need to select a widget. But I just can't select the widget type. The combobox is disabled.

Any ideas on why is this happening? We are running Drupal 6.22

Thanks!

Most likely either JavaSript or AJAX failure is giving you problems. Check your browser Javascript error messages with a tool like Firebug, and check your server log.

Alternatively you can disable the javascipt enabled interface entirely.


Commerce Kickstart demo: How do I change the region for the blocks Main Menu and Secondary Menu? In the Commerce Kickstart demo the blocks Main Menu and Secondary Menu are assigned to the Menu region. You can see in the image:

But I go to /admin/structure/block these blocks are Disabled. I mean they are not assigne to the menu region

Is this done programmatically? I need to move the blocks to other region. How can I do it?

Menus are printed in the region--menu.tpl.php @ profiles/commerce_kickstart/themes/commerce_kickstart_theme/templates .

You can see the settings for the same in the link admin/appearance/settings/commerce_kickstart_theme

If you would like to change the positions of menus, then disable the Main Menu & Secondary menu in above link settings as shown in screenshot and enable the blocks using Blocks page.


How to get the selected value of a dropdown inside panel? I have an exposed filter inside the panel.

I want to filter the taxonomy term. For that I add "Content: Has taxonomy term (exposed)" field.

I need to get the selected value in js.

Drupal.behaviors.mymodule = {
  attach: function (context, settings) {
    var tid = $('#edit-tid').val();
    alert(tid);

  }
};

In alert I am getting "All" rather than the selected tid, as shown in this image:

Apply little trick and my issue solved. Used default taxonomy search and hide it.

(function($) {

Drupal.behaviors.tushar_1 = {
  attach: function (context, settings) {
    $('#edit-shs-term-node-tid-depth').change(function(){
      var eid = $('#edit-shs-term-node-tid-depth').val();
      $('#edit-tid ').val(eid);
    });
  }
};

})(jQuery);

Solved my issue.


What is the right way to use a different base theme for some pages when applying custom theme? I know that custom theme usually inherited from the "stable" theme, and the default backend theme is "seven. I like the UI of "/user/login","/user/register" and "/forum" pages. If I use a custom theme inherited from "stable", how can I make the UI apperance of these special pages stay in "seven" theme? I tried to set the "base theme" to "classy" or "false", but the theme suggestions still choose the "stable" as a default.

How can I make the UI appearance of these special pages stay in
  "seven" theme?

Seven is the default theme for admin paths in Drupal. To mark special pages like the user login as admin path use the module Admin Login Path.

You can add your own paths in a custom route subscriber like the one from the module:

<?php

namespace Drupal\admin_login_path\Routing;

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

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

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    // Define the routes we want to use the admin theme.
    $login_routes = ['user.login', 'user.register', 'user.pass'];
    foreach ($collection->all() as $name => $route) {
      if (in_array($name, $login_routes)) {
        $route->setOption('_admin_route', TRUE);
      }
    }
  }

}


Global 'Last updated' timestamp Is there a way to create and display a global 'Last updated' timestamp that would be displayed on every page? 'Last updated' would include adding and changing any piece of content on the website. I know how to display a similar timestamp for each node but I'd like to be able to display just one per page. Maybe looping through all created nodes and finding the latest date? How would I achieve that? Or is there a better solution - looping through all nodes might be memory-intensive, right?

Thanks

If by "Last Updated" you are only talking about nodes, then yes, you can.

Create a new view for content (using views module), add a block display, do not filter by any content type, but I think that you can keep the "Published" status. Sort by updated time, descendant, set the pager to show only 1 node. And set the display to only show the updated time. That's all.


Add class to sub-taxonomy terms Is it possible to add a class to my subterms in a taxonomy vocabulary? So I can style theme and indent them. This is my taxonomy vocabulary:

And in my front-end it looks like this:

I'd like to remove the "-" and give them a padding-left. But how can I do this?

I'm showing this as a term reference in my registration form shown as checkboxes.

If you're using them in a form you could use this module to have much more control of your checkboxes tree and you will have different classes for parents and children:

https://www.drupal.org/project/term_reference_tree

Enable the Term Reference Tree module.
Go to the Manage Fields tab of any fieldable entity (such as a content type, taxonomy term, or user.
Add a new field with a type of Term Reference.
In the widget select box, select Term reference tree.


How to hook to content profile edit form validation I try the following code, but it doesn't seem to work.

function mymod_profile_node_form_validate($node,&$form) {
  firep($form, 'form');
}

Could anybody help?

It will not work as it is not a hook.

Try hook_form_alter() to edit form so that $form['#validate'] can be defined.

$form['#validate'] = !empty($form['#validate']) ? $form['#validate'] + array('mycustom_validate_handler') : array('mycustom_validate_handler');

Then define your function

function mycustom_validate_handler($form, $form_state){
     // Do your validation.
}


EntityQuery for taxonomy term of specific bundle I would like to build a query for all taxonomy terms of a specific bundle.

$terms = \Drupal::entityQuery('taxonomy_term')
  ->condition('type','mail_template')
  ->execute();

This returns an error 'type' not found.

How do I query taxonomy terms of a specific bundle (specific vocabulary)?

This works :

$terms = \Drupal::entityQuery('taxonomy_term')
  ->condition('vid','mail_template')
  ->execute();


Set value to Field collection item link field I have a Field Collection item which consist of a drop down, a text box and a link field. After the user submits a form I create a node were this field collection item is included. Before I save it, I populate some fields.

I managed to set the 'Url' in the link field(part of field collection item) by using:

$field_collection_item2->field_url->setValue($base_url . '/form/email-project-completion-survey');

Which works fine. Now I'm trying to set the 'Link text' but I can't make it work.

Any idea?

Thank you in advance

I managed to solve it by using an array in setValue.

$field_collection_item2->field_url->setValue(array('uri'=>$base_url . '/form/email-project-completion-survey', 'title' => 'Survey'));


How do I display some no results text in a view if the views results are aggregated? I have created a view block that displays the number of users a separate user has flagged. I did this by using the "Use aggregation" option in the advanced drop down. I have a UID field that I have grouped by count, and in the no results configuration I have written "0". For some reason when I go and print out my view, if there are no results, it won't display anything and I am wondering why.

I figured it out. Instead of configuring the no results display on the UID field, I had to configure it in the no results display of the view itself.


Countdown timer field with a scheduler module i am using https://drupal.org/project/field_countdown and https://drupal.org/project/scheduler modules.

I have added field_countdown field to my content type 'items'.
I have enabled scheduler for my content type 'items'.

When i am creating a node, i have to choose a date for field_countdown (it shows jQuery timer countdown until set date), also i have to set Scheduler date after that. So you have to set 2 dates instead of one, because these modules are not working together.

So i want to fill only 1 field instead of 2 of them, in my case its a field_countdown and copy its options to a scheduler input.

I've tried jquery without success:

(function($) {
    // jquery timer
    Drupal.behaviors.MyTimer = {
        attach: function (context, settings) {
            // This code will run, on load, even in overlay!!!!!!
            var timerDate = $('#input-id').val();
            alert(timerDate);
        }
    };
})(jQuery);

But js console says that timerDate is undefined. I am using overlay and bartik theme for administration pages.

Here is a good place to start:

http://code.zeurois.com/jquery-countdown/configurator/new/-/tpl/t105-900


Error when deleting some node After pressing the delete button the following message appeared:

  The website encountered an unexpected error. Please try again later.

How can I solve this problem?

when deleting field The system log says:

  PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table '[name].field_deleted_data_5' doesn't exist: SELECT field_deleted_data_50.entity_type AS entity_type, field_deleted_data_50.entity_id AS entity_id, field_deleted_data_50.revision_id AS revision_id, field_deleted_data_50.bundle AS bundle FROM {field_deleted_data_5} field_deleted_data_50 WHERE (field_deleted_data_50.deleted = :db_condition_placeholder_0) AND (field_deleted_data_50.bundle = :db_condition_placeholder_1) LIMIT 10 OFFSET 0; Array ( [:db_condition_placeholder_0] => 1 [:db_condition_placeholder_1] => patient_info ) in field_sql_storage_field_storage_query() (line 577 of C:\xampp\htdocs[name]\modules\field\modules\field_sql_storage\field_sql_storage.module

It sounds like your problem is that you have delete a field on your node, which makes Drupal rename the table storing the field data to field_deleted_data_ID. The error you are getting is that one of such tables is missing, and the delete fails since the query to delete the data creates a SQL error.

I know of two ways to solve this.

Recreate the table deleted.
Delete the field info from field_config and possibly field_config_instance.


Inline Javascript throws an error on drupal_add_js() within an AJAX callback I am trying to get JavaScript to measure a text field and auto submit at a character limit for an Ajax callback to be validated against a Luhn Algorithm and errors out on failure to validate.
I found this code in Firing ajax_callback on textfield after a minimum number of character.
// Trigger ajax event on myitem only after 5th character typed.
$('.myitem-class').on('keyup', function() {
  if ($(this).val().length == 5) {
    $(this).trigger('change');
  }
});

The JavaScript can allegedly be put inline in a wrapper like this to be used in an Ajax callback in a form. See drupal_add_js within AJAX callback.
function my_module_form($form, &$form_state) {
  drupal_add_js('Drupal.ajax.prototype.commands.myFunction = function(ajax, response, status) {
    // …
    }',
    'inline'
  );

  return $form;
}

I got to run replacing function(ajax, response, status) with function($, Drupal).
When I put in the code, it throws a PHP error at ).on(. I wasn't able to get the inline wrapper recommended in Converting 6.x modules to 7.x / JavaScript should be compatible with libraries other than jQuery to work because it fails seeing the $ as a variable.
(function ($) {
  // […]
}(jQuery));

Right now, I am stopped by syntax errors.
Does anyone know how to get this JavaScript code work?

Quick written code:
      <?php

      /**
        * Form.
        */
      function sample_luhn_form($form, &$form_state) {
        // I don't recommend inline js, prefer usual module js file, attach via $form['#attached'] or in module info file
        // Also I am use jQuery instead of $, but your shown (function ($) { }jQuery)); is preferred, I don't know why it's show errors, try inspect on dev.tools
        drupal_add_js('jQuery(document).ready(function () { jQuery(".luhn-nums").keydown(function() { if (jQuery(this).val().length >= 5) { jQuery(".luhn-check").mousedown(); } }); });', 'inline');

        // text field that should be checked for Luhn
        $form['luhn_nums'] = array(
          '#type' => 'textfield',
          '#title' => t('Luhn numbers'),
          '#prefix' => '
',
          '#suffix' => '
',
          '#attributes' => array(
            'class' => array('luhn-nums'),
          ),
        );
        // hidden ajax button
        $form['luhn_check'] = array(
          '#type' => 'submit',
          '#ajax' => array(
            'callback' => 'sample_luhn_form_ajax_submit',
            'wrapper' => 'luhn-nums-wrapper',
          ),
          '#attributes' => array(
            'class' => array('luhn-check', 'element-invisible', 'hidden'), // set class, that hide this ajax submit button or hide via CSS styles
          ),
        );

        // here goes another form elements
        // ...
        $form['submit'] = array(
          '#type' => 'submit',
          '#value' => t('Submit'),
        );
      }

      /**
       * Ajax callback function.
       */
      function sample_luhn_form_ajax_submit($form, &$form_state) {
        if (_sample_luhn_check($form_state['values']['luhn_nums'])) {
          // If luhn not passed
          form_set_message('luhn_nums', t('Luhn error, please fix numbers'));
        }
        // here you can alter luhn_nums textfield value
        return $form['luhn_nums'];
      }

      /**
       * Validate form.
       */
      function sample_luhn_form_validate($form, &$form_state) {
        // Don't allow pass to submit untill luhn will passed
        if (_sample_luhn_check($form_state['values']['luhn_nums'])) {
          // If luhn not passed
          form_set_message('luhn_nums', t('Luhn error, please fix numbers'));
        }
      }

      /**
       * Form submit.
       */
      function sample_luhn_form_submit($form, &$form_state) {
        // save data
      }

      /**
       * Private function that check luhn algorithms.
       */
      function _sample_luhn_check($nums) {
        $result = FALSE;

        // check numns by luhn algorithms
        // lot of code that alter $result

        return $result;
      }


D7 jquery dropdown menu categorized/ordered by content type and taxonomy In D7 I want to create a jquery dropdown menu categorized/ordered by content type (first level) and (if content type has taxnonomy tags) taxonomy via views.

What is the best approach? thnx!

I now use custom menu items and the modules 'Taxonomy Menu' together with 'Nice Menu' and some custom jquery javascript.


How do I use add the image field Product entity in to my view? I'm using Drupal 7.28, Views 7.x-3.8 and Commerce 7.x-1.9.

I've created lots of products in the Products section and I've also created some product displays. For example, I have created a round oak table, square oak table and a rectangle oak table. I have then created a product display called Old Oak Table and I've referenced the three oak tables.

Now I need to create a view that lists all tables. My view needs to show one image from each product display.

I was unable to add the image field to my view - so I added a Product reference and I'm now able to add the Image field which is on the Product entity not the content type.

Now that I've added the image field, my view shows every product image so for example the round table, the square table and the rectangle table - I just need it to show one image from each product display, so for example just one image from the Old Oak Table product display.

Thank you very much for reading.

To show just a single image, you can add a filter to the view to restrict the product reference field to delta 0.


Add an image to a views title (Taxonomy Term View) I have a view listing nodes of my taxonomy terms. All well and good and my view shows nodes of every taxonomy term with the taxonomy term name as the view title.

My taxonomy terms though have an image assigned to them. So is there any hook or any other way to show the taxonomy term title next to its corresponding image? Something like this?

Example image:

And here is a screenshot of the view. Notice the path that is taking the term id as a parameter to display nodes of a specific term.

EDIT: I am using the default Taxonomy Term View

Views UI

I would use Panels for that. You may combine any elements from Drupal on the same page (node fields, views, terms, blocks, etc.) with Panels.

With this module you can edit the taxonomy term page as you wish (Structure > Pages > Taxonomy view > Active then edit).

In the Content section, after setting path, context and layout, you add your taxonomy term custom image field, followed by your taxonomy term name (with a little CSS float, you will have your image on the left).

Finally, you add your View below (do not forget to activate the Chaos tools sub-module "Views content panes") and you're done.

Panels needs a little practice but it is a powerful tool to work on page templates.


Completing the checkout process event isn't firing I have a Drupal Commerce 7 installation which isn't firing the Completing the checkout process event.

Steps I've tried:

I've rebuilt Rule's cache
I've rechecked the integrity of the rules
I've set "Log debug information to the system log" (Log all warnings and errors)
I've disabled all of the rules bound to the event "Completing the checkout process"
I've created a new rule, which will only send an email.

However, the e-mail is never sent and I don't see the rule being written on the log.

I've tried to submit correctly the order in the storefront (with a "normal" user and with an Admin user).

I've tried to use different types of payment.

I've tried to change the order status to "Checkout complete" in the Backoffice.

What else I'm missing? What's making this event not firing?

Based on others posts, I've checked the rules for other events and realized there's a rule "Commerce order message: changing status", for the event "After updating an existing commerce order". It has the following actions:
Creates new entity Message Type Commerce Order: state change of the order
Set a data value message:message-commerce-order = commerce-order
Set a data value message:arguments:order-status = [commerce-order:status-title]
Set a data value message:arguments:order-status-previous = [commerce-order-unchanged:status-title]

However, this doesn't seem to be responsible for the event never firing, or is it?

Can anybody help me and shed some light on this?

This is the Rules debug information I get, after changing the Order status to Complete, directly on the Backoffice:

Rules debug information:
" Reacting on event After updating an existing commerce order.

0 ms Reacting on event After updating an existing commerce order.
11.574 ms Evaluating conditions of rule Delete shipping line items on shopping cart updates. [edit]
13.432 ms The condition data_is evaluated to FALSE [edit]
13.442 ms AND evaluated to FALSE.
13.546 ms Evaluating conditions of rule Commerce order message: changing status. [edit]
14.047 ms The condition data_is evaluated to FALSE [edit]
14.057 ms AND evaluated to TRUE.
" Rule Commerce order message: changing status fires. [edit]
    0 ms Rule Commerce order message: changing status fires.
    6.493 ms Evaluating the action entity_create. [edit]
    7.441 ms Added the provided variable message of type message [edit]
    9.105 ms Evaluating the action data_set. [edit]
    24.349 ms Evaluating the action data_set. [edit]
    26.206 ms Evaluating the action data_set. [edit]
    26.454 ms Rule Commerce order message: changing status has fired.
40.578 ms Saved message of type message.
46.594 ms Finished reacting on event After updating an existing commerce order.

Still no information regarding the firing of "Completing the checkout process" event...

Debugging is the art of eliminating possible causes for an issue. In this case, your issue could be because ... your rule is disabled.

As per the 'I've disabled all of the rules bound to the event "Completing the checkout process" ...', double check that the rule you want to fire is (still) enabled. If it isn't, then make sure to enable it (again).

Also, your question states "the e-Mail is never send": it could well be because something (different from your rule not firing) is wrong. So therefor, add an extra Rules Action to the rule you're struggling with, as the very first Rules Action, and which is only to "show a message on the site"", and with a message like "Bingo" (or whatever). Then rerun your testcase, and verify if you do get such "Bingo":

If you do, your rule has fired ... and your real issue is related to sending the eMail.
If you don't, (temporary) remove ALL Rules Conditions in your rule and retry. If in that case you do get a "Bingo", then your issue is related to one or more of your Rules Conditions (though the rule did fire).

The above is how I typically do most of my Rules debugging, in cases where some rule seems to not fire (stupid, but pretty effective).

If none of the above debugging tips helps ... then edit your question and include an export of the rule you are debugging (in that case I might further improve my anwer).


Removing the Text Format selection Every textarea gives you an option to use either Filtered, Full, or Plain Text. Is there a way to remove or hide it so the layout becomes more streamlined? I'm using CKEditor if it means anything.

You can change who has permission to use which input format under Settings (Site Configuration) -> Input formats for Drupal 6 or Configuration -> Text formats for Drupal 7.

If you uncheck all the other options (I'm assuming the one with the editor is set as default) then the option won't appear for those users who only have the default checked.

That's at least one way.


Commerce Rule For Sales Tax On Shipping To One State We want to only apply sales tax on orders shipped to a particular State. I tried to cobble together the following rule from the included 'Price Component' and it seems to apply tax on shipping for -all- orders, regardless of the address component.

Can someone look at this and tell me what I'm doing wrong?

{ "rules_apply_taxes_to_shipping" : {
    "LABEL" : "Apply Taxes to Shipping",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "commerce_order", "commerce_tax", "commerce_shipping" ],
    "ON" : { "commerce_shipping_calculate_rate" : [] },
    "IF" : [
      { "commerce_order_compare_address" : {
          "commerce_order" : [ "commerce-line-item:order" ],
          "address_field" : "commerce_customer_shipping|commerce_customer_address",
          "address_component" : "administrative_area",
          "value" : "WA"
        }
      }
    ],
    "DO" : [
      { "commerce_tax_calculate_by_type" : {
          "commerce_line_item" : [ "commerce_line_item" ],
          "tax_type_name" : "sales_tax"
        }
      }
    ]
  }
}

Here is the Rules Evaluation Log. Apparently the rule isn't even firing. How do I figure -that- out?

    0 ms Reacting on event Calculating the sell price of a product.
    3.479 ms Evaluating conditions of rule Calculate taxes: VAT. [edit]
    3.489 ms AND evaluated to TRUE.
        0 ms Rule Calculate taxes: VAT fires.
        0.138 ms Evaluating the action commerce_tax_calculate_by_type. [edit]
        4.267 ms Rule Calculate taxes: VAT has fired.
    7.837 ms Evaluating conditions of rule Calculate Bundle Product Price. [edit]
    7.845 ms AND evaluated to TRUE.
        0 ms Rule Calculate Bundle Product Price fires.
        0.093 ms Evaluating the action commerce_product_bundle_calculate_price. [edit]
        4.688 ms Rule Calculate Bundle Product Price has fired.
    12.594 ms Evaluating conditions of rule Quote Required. [edit]
    12.609 ms AND evaluated to TRUE.
        0 ms Rule Quote Required fires.
        0.012 ms Rule Quote Required has fired.
    12.692 ms Evaluating conditions of rule Calculate taxes: Sales tax. [edit]
    12.699 ms AND evaluated to TRUE.
        0 ms Rule Calculate taxes: Sales tax fires.
        0.111 ms Evaluating the action commerce_tax_calculate_by_type. [edit]
            0 ms Executing rule Calculate Sample Michigan Sales Tax 6%.
            0.169 ms Evaluating conditions of rule Calculate Sample Michigan Sales Tax 6%. [edit]
            2.254 ms The condition commerce_order_compare_address evaluated to TRUE [edit]
            2.263 ms AND evaluated to TRUE.
                0 ms Rule Calculate Sample Michigan Sales Tax 6% fires.
                0.089 ms Evaluating the action commerce_tax_rate_apply. [edit]
                0.571 ms Added the provided variable applied_tax of type commerce_price [edit]
                0.6 ms Rule Calculate Sample Michigan Sales Tax 6% has fired.
            2.905 ms Finished executing of rule Calculate Sample Michigan Sales Tax 6%.
        5.114 ms Rule Calculate taxes: Sales tax has fired.
    17.894 ms Evaluating conditions of rule Unset the price of disabled products in the cart. [edit]
    18.145 ms The condition data_is_empty evaluated to FALSE [edit]
    18.334 ms The condition entity_has_field evaluated to TRUE [edit]
    19.067 ms The condition data_is evaluated to FALSE [edit]
    19.076 ms AND evaluated to FALSE.
    19.102 ms Evaluating conditions of rule Quote Required. [edit]
    19.195 ms The condition data_is_empty evaluated to FALSE [edit]
    19.296 ms The condition entity_has_field evaluated to TRUE [edit]
    19.708 ms The condition data_is evaluated to FALSE [edit]
    19.716 ms AND evaluated to FALSE.
    19.737 ms Finished reacting on event Calculating the sell price of a product.

No idea why your rule isn't triggering based on the state. From the label, it looks like you're trying to apply taxes to the order total including shipping. So you need two things here you need to configure a state specific tax rule and then you need a shipping rule, and a second shipping rate calculation which applies your tax to your shipping rate. Hope that helps.


How to restrict access to /user page? I did my my own login form with custom functionality that is on /login url. Now I would like to restrict acces to default /user url in order to prevent logging in the old way.

I have a lot of different functionality in this form, so I though it is better to built it all from scratch instead of altering something. And I don't like the word in the /user, since in our language it sounds similar to some word that is not appropriate here.

I've tried to add /user item to hook_menu and define the same callback as /login item has.

I was hoping it could redirect users to new login form, but it had no effect.

What is the right way of doing this?

Since user is already defined as menu item from a module, you cannot use hook_menu() to alter it, but you need to use hook_menu_alter(). Since user is used for the currently logged-in user, it probably a bad idea to redirect them to login.

As said from Mołot in his comment, the correct way of altering the login process is altering the login form, and add new validation handlers. This is similarly to what the OpenID module in Drupal core does.

function openid_form_user_login_alter(&$form, &$form_state) {
  _openid_user_login_form_alter($form, $form_state);
}

function openid_form_user_login_block_alter(&$form, &$form_state) {
  _openid_user_login_form_alter($form, $form_state);
}

function _openid_user_login_form_alter(&$form, &$form_state) {
  $form ['#attached']['css'][] = drupal_get_path('module', 'openid') . '/openid.css';
  $form ['#attached']['js'][] = drupal_get_path('module', 'openid') . '/openid.js';
  $form ['#attached']['library'][] = array('system', 'jquery.cookie');
  if (!empty($form_state ['input']['openid_identifier'])) {
    $form ['name']['#required'] = FALSE;
    $form ['pass']['#required'] = FALSE;
    unset($form ['#submit']);
    $form ['#validate'] = array('openid_login_validate');
  }

  $items = array();
  $items [] = array(
    'data' => l(t('Log in using OpenID'), '#openid-login', array('external' => TRUE)),
    'class' => array('openid-link'),
  );
  $items [] = array(
    'data' => l(t('Cancel OpenID login'), '#', array('external' => TRUE)),
    'class' => array('user-link'),
  );

  $form ['openid_links'] = array(
    '#theme' => 'item_list',
    '#items' => $items,
    '#attributes' => array('class' => array('openid-links')),
    '#weight' => 1,
  );

  $form ['links']['#weight'] = 2;

  $form ['openid_identifier'] = array(
    '#type' => 'textfield',
    '#title' => t('Log in using OpenID'),
    '#size' => $form ['name']['#size'],
    '#maxlength' => 255,
    '#weight' => -1,
    '#description' => l(t('What is OpenID?'), 'http://openid.net/', array('external' => TRUE)),
  );
  $form ['openid.return_to'] = array('#type' => 'hidden', '#value' => url('openid/authenticate', array('absolute' => TRUE, 'query' => user_login_destination())));
}


Custom form block not working In my custom module I have created custom for like below:
Path: custom_module/src/Form/UserType/UserType.php

<?php
/**
 * @file
 * Contains \Drupal\resume\Form\UserType.
 */
namespace Drupal\custom_module\Form\UserType;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class userType extends FormBase {
  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'user_type_form';
  }
  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $user_types = \Drupal::entityManager()->getStorage('taxonomy_term')->loadTree('user_type');
    $user_type_options = array();
    foreach ($user_types as $user_type) {
        $user_type_options[$user_type->tid] = $user_type->name;
    }

    $form['user_type'] = array(
      '#type' => 'select',
      '#options' => $user_type_options,
    );
    return $form;
  }
  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

  }
}

Then I created a block in following path:
custom_module/src/Plugin/Block/UserTypeBlock.php

<?php
/**
 * @file
 * Contains \Drupal\custom_module\Plugin\Block\UserTypeBlock.
 */
namespace Drupal\custom_module\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormInterface;
/**
 * Provides a 'user_type' block.
 *
 * @Block(
 *   id = "user_type_block",
 *   admin_label = @Translation("User Type block"),
 *   category = @Translation("Custom")
 * )
 */
class UserTypeBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */
  public function build() {
    $form = \Drupal::formBuilder()->getForm('Drupal\custom_module\Form\UserType');
    return $form;
   }
}

But after assign the block in to a region I'm getting following error:

  InvalidArgumentException: The form argument
  Drupal\custom_module\Form\UserType is not a valid form. in
  Drupal\Core\Form\FormBuilder->getFormId() (line 190 of
  C:\wamp\www\www_mysite_com\core\lib\Drupal\Core\Form\FormBuilder.php).

The php file of the form is in a subfolder, but the class name in getForm() does not reflect this.

Change the location of the php file from

custom_module/src/Form/UserType/UserType.php

to

custom_module/src/Form/UserType.php

and

namespace Drupal\custom_module\Form\UserType;

to

namespace Drupal\custom_module\Form;


Place a link at top AND bottom of each node I made some code to put a button/link at the bottom of a node. But it would be nice to place this link also at the top of the node. Would this be possible?

This is the code that places a button at the bottom of each node:

function hook_node_view($node, $view_mode, $langcode) {
    $node->content['links']['job'] = array(
        '#links' => array(
            array(
                'title' => t('Apply'),
                'href' => 'jobs/apply',
            ),
        ),
    );
}

You are placing your link in the links object of the $content array which will generally, unless a template file overrides it, render all it's content in one place.

If the one link you have added visually covers your needs, the other one should be placed within the $content array, with a 'light' #weight property (0 for instance) along with the rest of the array's items (body, fields, etc).

the code could look something like this:

$node->content['top_link'] = array(
  '#markup' => ''.t('Apply').'',
  '#weight' => 0,
   );


Location Contextual Filter: Distance/Proximity works for all nodes but one Drupal 7 site with Location and Location CCK modules.

Client has custom content type with Location field provided by Location CCK module.

Each Location node has a Views block display of Nearby Locations with sort criteria “Location: Distance / Proximity (asc)” and this works for all nodes except a new one recently created.

In Views UI, if I preview with contextual filters, I see the closest four locations sorted by proximity.

But viewing the actual node, I see four other locations that are quite some distance farther away.

What could be causing this, and how should I troubleshoot it? (I have cleared the cache!)

I did not figure out why this is happening, but I was able to enter the latitude and longitude manually. This solves the problem for the short term, since the client does not add Location nodes often. I'm leaving the question open in case anyone has a clue!


How to show only content created by the user in the find content (administrative) page I've got some users who are allowed to create content. In the administrative interface, they actually see a list of all contents in the site but edit/delete only the content created by them. Is it possible to show in this page only the content they created and do not show content created by other users?

I've found that it's better to leave the admin areas to the admin user alone, and to build custom Views for "manager/editor" users.  This gives you more control over the presentation and lets you easily add in additional information and links that aren't normally available in the admin screens.  Not only that, you get easy access control to the listings.

If you really must do it the way you're talking about, there's an article on the drupal.org site discussing the theme hook for that screen, which I believe you could override and then filter based on ownership of the nodes in the node listing:

http://drupal.org/node/108986


How can I link a group of galleries through a single image using Views? I found a great article titled "How to Create an Image Gallery in Drupal" and at the end the author was sketching the posibility of its intregration with Views.My intention is to display a grid View of single images that represents the full contents (the galleries) that I created thanks to that article,and when you click on each one they take you to its respective group of images.

You can just do the following on the View:

Add your custom "path" field and set it to be hidden (Exclude from Display).
Add The image field. Under "Rewrite results" set it to "Output this field as a link" and use the token for the previously hidden field.

This will allow you to define what will each image do when clicked.


Is there any way to export data to CSV file and then import updated data? I have a website I started to build couple years ago. But the website itself grew up to something bigger, with more fields and details - and old data are missing these. E.g., recently added Long./Lat. fields but old content doesn’t have them. So I wonder if it’s possible (and what module) to export all data into csv file, update it (I think it's much easier than open one by one node) and than import the updated data? Or something like that.

Thanks for any help.

If you want to do it that way, use Views data export. Here is an excerpt about it from the module's project page:

... designed to provide a way to export large amounts of data from views. It provides a display plugin that can rendered progressively in a batch. Style plugins are included that support exporting in the following types:

CSV.
Microsoft XLS.
Microsoft DOC.
Basic TXT.
XML.

Then, re-import using the Feeds module. Here is an excerpt about it from the module's project page:

Import or aggregate data as nodes, users, taxonomy terms or simple database records.

One-off imports and periodic aggregation of content
Import or aggregate RSS/Atom feeds
Import or aggregate CSV files
Import or aggregate OPML files
PubSubHubbub support
Create nodes, users, taxonomy terms or simple database records from import
Extensible to import any other kind of content
Granular mapping of input elements to Drupal content elements
Exportable configurations
Batched import for large files


Update a content type field via db not working D8 I have a content type field with machine name field_p_frontip and for that i have a table node__field_p_frontip and in that there is field value like field_p_frontip_value . Eventhough i manually inserted a value in to that field its not taking effect in the front end . I updated the value in the node_revision__field_p_frontip table too and cleared the cache .Why its not working ,any idea ?

I done this because i done via hook_form_alter and its not taking effect .

node__field_p_frontip table structre :

+-----------------------+------------------+------+-----+---------+-------+
| Field                 | Type             | Null | Key | Default | Extra |
+-----------------------+------------------+------+-----+---------+-------+
| bundle                | varchar(128)     | NO   | MUL |         |       |
| deleted               | tinyint(4)       | NO   | PRI | 0       |       |
| entity_id             | int(10) unsigned | NO   | PRI | NULL    |       |
| revision_id           | int(10) unsigned | NO   | MUL | NULL    |       |
| langcode              | varchar(32)      | NO   | PRI |         |       |
| delta                 | int(10) unsigned | NO   | PRI | NULL    |       |
| field_p_frontip_value | longtext         | NO   |     | NULL    |       |
+-----------------------+------------------+------+-----+---------+-------+

and node_revision__field_p_frontip table structure :

+-----------------------+------------------+------+-----+---------+-------+
| Field                 | Type             | Null | Key | Default | Extra |
+-----------------------+------------------+------+-----+---------+-------+
| bundle                | varchar(128)     | NO   | MUL |         |       |
| deleted               | tinyint(4)       | NO   | PRI | 0       |       |
| entity_id             | int(10) unsigned | NO   | PRI | NULL    |       |
| revision_id           | int(10) unsigned | NO   | PRI | NULL    |       |
| langcode              | varchar(32)      | NO   | PRI |         |       |
| delta                 | int(10) unsigned | NO   | PRI | NULL    |       |
| field_p_frontip_value | longtext         | NO   |     | NULL    |       |
+-----------------------+------------------+------+-----+---------+-------+

From Berdir's comment

I was trying to set the value of the field 'field_p_frontip' in form_alter as follows , but both didnt worked .

$form['field_p_frontip']["en"][0]['#default_value']['value'] ='192.168.1.100'; $form['field_p_frontip']['#default_value'] = '192.168.1.100';

To update the value of a field for a node, you need to.

Load it
Modify it
Save it

In code it looks like this:

$node = \Drupal\node\Entity\Node::load($nid);
if ($node) {
  $node->field_p_frontip = '192.168.1.100';
  $node->save();
}

How you set the value of the field, depends on the field itself. Most fields are simple, and can be set with a scalar value. If field has multiple values or stores more complex data (like the address field), you need to account for this complexity. Usually this is done with arrays.


Displaying content type as a field in a page I am stuck with this architectural design for a client of mine. I am trying to create a testimonial block in 3 different pages, that client can pick any testimonial and I will create simple bootstrap carousel system for that.

So I created a custom content type name testimonial which has 3 fields, body, client name, and client title. This is the point I get stuck, I have no clue what would be the next? I tried to create that block via views slideshow but then client won't be to pick testimonials that they want, it will display all the testimonials.

I wonder if there is a way that I can add this content type as a field at that page? Or am I going to create a custom page(as a module) and create a custom field for this testimonial content type? If I have to do so, is there anyone who encountered this and completed something like this, can direct me to a sample of this?

Create a custom block type "Testimonial slideshow" or so (Accessible through local tasks on the block overview page), add a reference field and allow nodes of your given type. Set the cardinality to exactly 3.

Then you can create a block of that type and select 3 testimonials (with select or autocomplete, depending on what you configure on manage display).

That's it, now you just have to implement the necessary templates to show it as a slideshow.


Remove Caption and next/previous arrows from Colorbox for Node To display Node in Modal, I am using colorbox node module

I changed the settings in Colorbox module to not display any information like Current, Next, Previous, etc. like:

however I can still see that small arrow and node count as shown in the picture below:

How do I remove these small arrows and count overall and only have that Cross(X) to close the Modal.

Edit: I cleared the cache and this 4 of 41 is gone... but those arrows are still there.

The only way I found to do this was to change my theme css file (I use an Omega >theme so used global.css) and add:

  #cboxPrevious, #cboxNext {
        width:0;
     }

  I initially tried display:none but something is overriding it.

display:none works if you use !important


How do I mock the "file_system" service? How do I mock the file_system service in PHPUnit?

The issue is being reproduced when \Drupal::service('file_system') is executing in the test suite environment.  If \Drupal::service('file_system') is removed the class loads the assertions in the test class run perfectly. My belief is that this service needs to be mocked. (This could be completely false. I am really unsure).

The terminal error displayed when running the test is the following.

  Drupal\Core\DependencyInjection\ContainerNotInitializedException: \Drupal::$container is not initialized yet. \Drupal::setContainer()

This is the class method that executes the Drupal 8 service.

 /**
   * @inheritdoc
   */
  public function setBasePath($path = Null) {

    if ($path !== Null) {
      $this->directories['base'] = $path;
    } else{
     $this->directories['base'] = \Drupal::service('file_system')->realpath(file_default_scheme() . "://");
    }
  }

This is the test class that is going to test the above class in the future. Right now it compares a string only.

/**
 *
 * @group react_forms
 */
class DirectoryStructureTest extends \Drupal\Tests\UnitTestCase {

  /**
   * @var object
   */
  private $objToTest;

  /**
   *
   */
  public function setUp() {
    $this->objToTest = new DirectoryStructure();
  }

  public function testGetDirectories() {

    $this->assertEquals('this', 'this');
  }

  /**
   * Once test method has finished running, whether it succeeded or failed,
   * tearDown() will be invoked. Unset the unit created object.
   */
  public function tearDown() {
    unset($this->objToTest);
  }
}

You shouldn't call file_system with \Drupal::service('file_system') use dependency injection instead:

So try something like the following in your service:

Add arguments to your *.services.yml file.

services:
  yourModule.yourService:
    class: Drupal\yourModule\yourServiceClass
    arguments: ['@file_system']

Inject the file_system service in your Class:

  use Drupal\Core\File\FileSystemInterface;

  /**
   * The file system service.
   * @var \Drupal\Core\File\FileSystemInterface
   */
  protected $fileSystem;
  /**
  * Class constructor.
  * @param \Drupal\Core\File\FileSystemInterface $file_system
  */
  public function __construct(FileSystemInterface $file_system) {;
    $this->fileSystem = $file_system;
  }

Change setBasePath method to be like.

  /**
   * @inheritdoc
   */
  public function setBasePath($path = Null) {

    if ($path !== Null) {
      $this->directories['base'] = $path;
    } else{
     $this->directories['base'] = $this->fileSystem->realpath(file_default_scheme() . "://");
    }
  }


qTips do not appear on content type create form I have installed qTip (Stylish jQuery Tooltips) module v7.x-2.0-rc3, but I cant get it to work on a content type create form.

The steps I've followed are the following:

Install and enable qTip module along with Fields sub-module.
Create a new qTip instance with the default and simplest options.
Go to my content type and manage a Long text field with a text-area widget.
Enable the qTip Settings for it. Set it to Custom Text and fill in a sample text. Select my previously created qTip instance.
Press Save and clear all caches.

However when I go to the form (Content -> Add Content -> My_content_type) the qTips are nowhere to be seen. I've tried to hover over the label and the text editor. Nothing shows up.

On the other hand when I preview my instance the qTip appears normally:

Am I missing something here?

I found no solution why this was happening, so I had to switch to Form Tips which worked flawlessly along with some custom CSS theming.


How do I get block content to show? I have a custom module that I created. In it, I've implemented the hook_block_view:

function event_details_block_view($delta = '') {
$block = array();

switch($delta) {
    case 'event_details':
    $block['content'] = array(
    '#theme' => 'event_block_details',
    );
    break;
}

return $block;
}

I then have a file named event-block-details.tpl.php in my module folder. Right now, this is just some basic HTML to test whether or not the block is accepting the theme. When I go to my site however, I am able to see the block in the blocks tab and I can add it to a page, but none of the content displays.

Are there any suggestions as to what could be wrong? This is the first module I've written so I'm unsure where the errors can lie. I use Drupal 7.

I think you should check this link for solving your problem : how-to-theme-a-custom-block-in-drupal-7. Actually you can search for that type of question around here.


Custom placeholder markup when leveraging #lazy_builder in elements Using bigpipe.

To avoid blocking page loads for long-lasting API calls, etc, I implement:

$element = [
  '#lazy_builder' => ['service.admin:method', []],
  '#create_placeholder' => TRUE,
];

and it works great! The page loads, and once the service returns the render array, it gets popped into the placeholder.

However, the placeholder span is empty and does not provide the user with any useful status. My goal is to have the empty placeholder replaced with a message (i.e. 'Loading data..'). This is proving more difficult than I assumed - I feel like I must be missing something.

My first crack was manually defining the placeholder:

$element = [
  '#markup' => 'Loading data..',
  '#attached' => [
    'placeholders' => [
      'Loading data..' => [
        '#lazy_builder' => ['service.admin:method', []],
      ],
    ],
  ],
];

This generates the desired content, but blocks any elements further down of it from loading until the method returns - pausing with half the page rendered. I assume it pushes the lazy_builder into the render process where it isn't as useful for this purpose.

I skimmed through core and couldn't glean any examples of this.

Is there an easy way to add text to the placeholder? This cannot be a novel need.

Warm Regards.

I know this is an old question, but for anyone who stumbles upon it via a search engine (like I did), then the answer is that as of right now, you can't provide custom placeholder markup, but there is a Drupal.org issue with patches that adds this functionality, so it's possible that the feature will eventually be available in the Big Pipe module without a patch.


Limit the number of levels (depth) of a taxonomy vocabulary I would like to limit the depth of a taxonomy vocabulary to a maximum number parent/child nestings. I would like my users to not be able to add at most 4 levels deep of taxonomy terms per tree. Is there a module for this or what code is needed to enforce this depth on the tree?

After a lot of Googling and trial and error I came up with the following means of limiting a vocab's depth. You can make it as specific as you like:

Limit the depth of Parents on the term edit page:

function MY_MODULE_form_taxonomy_form_term_alter(&$form, &$form_state) {
  if ($form['#bundle'] == 'MY_VOCAB') {
    // Limit parents to none or only top level items
    foreach ($form['relations']['parent']['#options'] as $tid => $option) {
      if (substr($option, 0, 1) == '-') {
        unset($form['relations']['parent']['#options'][ $tid ]);
      }
    }
  }
}

Limit the depth of Tabledrag on the taxonomy terms listing page:

I could not re-implement theme_taxonomy_overview_terms() as another module had already done this and it made no sense to do that.

function MY_MODULE_preprocess_page(&$variables) {
  if (current_path() == 'admin/structure/taxonomy/MY_VOCAB') {
    // Prevent tabledrag from allowing more than two levels in this hierarchy
    $settings['tableDrag']['taxonomy']['term-depth'][0] = array(
      'target' => 'term-depth',
      'source' => 'term-depth',
      'relationship' => 'group',
      'action' => 'depth',
      'hidden' => false,
      'limit' => 1,
    );
    drupal_add_js($settings, 'setting');
  }
}


Didn't we used to be able to type "entity:node/####" in a typeahead field? When using any Drupal 8 link field to dynamically link to a node, I start typing the title and the typeahead function starts providing options to chose from. These are Drupal field types such as Link or Entity Reference.

For various reasons, sometimes the correct title doesn't appear and I can't choose it using what's in the typeahead choices. In those cases, I always just used:

entity:node/[node_id_number]

I'm trying to do that now, and Drupal isn't recognizing it as a valid entity. I keep getting the error message:

There are no entities matching "entity:node/6491".

I've tried typing it every which way I could think of, figuring I just forgot the correct syntax. I tried:

/entity:/node/6491
/entity:node/6491
entity:/node/6491
/entity: node/6491

and more.

Can anyone tell me what I'm doing wrong? Or was it all just a fever dream and I was never able to fill in a typeahead link field using 'entity'?

Ooooooooookay.

The entity:node/[node_id_number] only works in a Drupal link field. It does NOT work in a Drupal entity reference field.

Although both of those fields feature the typeahead function and link to other nodes, you cannot use  entity:node/[node_id_number] to fill in an entity reference typeahead field.

Thanks @Clive for making me clarify my field types and start down the path to seeing my wrong assumption.


How to apply css to the maintenance page? I need to work on some serious update to my D7 website. So I put my site in maintenance mode. I'm able to personalize the maintenance page by creating maintenance-page.tpl.php in my theme's template directory and it works like charm, no issues. The problem is, none of my theme css files are loaded when I'm opening the site in maintenance mode.

I'd really like to prettify the maintenance page for any visitors who visits the site in the mean time (while I'm updating). How do I do that? BTW, I'm using omega theme stable release.

Override the maintainence stylesheet in the theme layers .info file...

  stylesheets[all][] = system.maintenance.css

To be honest if none of your theme stylesheets are loading then not sure it will work but ideally it should.

Heres some more info on theming the maintence page...

http://drupal.org/node/195435

UPDATE

Alternatively, try the following in your theme...

/**
 * Implements hook_preprocess_maintenance_page().
 */
function YOURTHEME_preprocess_maintenance_page(&$variables) {
  drupal_add_css(drupal_get_path('theme', 'YOUR_THEME') . '/css/maintenance-page.css');
}


View sorting programmatically I have a view with grouping (by one field) and sorting by nodequeue weight.
I want to sort the groups as well so I've used hook_views_pre_render and sorted the results array programmatically, but as far as I can see the results aren't rendered as the results array on $view->result order.

What am I missing? Workaround will also be great!
Thanks!

The problem was hook_views_pre_render, for some reason the markup is already render at this stage (weird..),  when I used the same code in hook_views_post_execute it worked perfectly.


Popup slide of galleries I need to create a slide in popup where the user can list the galleries.

In short, the left and right arrows is navigation for previous and next gallery (as well as numbers for navigation), each gallery has a number of images that can be changed by clicking on the thumbnail image.

My idea is to create a content type for the gallery, and then using Views Slideshow to list only body of that content type. Is such a thing possible? Could there be another way in which this can be done?

Any suggestion is welcome...

This is step by step solution that I use to get this done:

Create new content type with image field
Install Field Slideshow and View Slideshow modules
Create new View of type Slideshow
Add image field from created content type in View, than set 'Slideshow' for 'Formatter' of that field and choose settings that you want for slideshow
That's it, you have slideshow of images inside slidedeshow...


Exposing a form to anonymous users I'd like to provide a form where anyone can submit a new job opening.  The goal is to allow anyone to submit a subset of fields for a jobs content type.  Once submitted, the site admin would come in and fill in the rest and publish the new node.  I've played with allowing anonymous access to create new nodes of the content type, but I just don't like the way the form looks and I don't want the user to see all the fields.  Is there a way to hide some fields and set the published marker to unpublished for anonymous users and protect the form with a captcha or is creating a custom form the way to go?

I guess the Field Permission module is what you need. It allows you to set finegrained permissions to fields. Once installed you can set the permissions to edit, view etc to the field on the manage fields tab of your content type...


Get a notification if a new version (tag) is created Before there was a RSS fead that got update if a new release of drush is available, see question:
Getting an email notification when a new Drush version is available.

But after drush is moved to github it seems that the RSS feed does not get updated anymore.

Is there a possibility to get an email notification if a new release tag is created on the github site?

Not directly through Github, but check https://sibbell.com

It's notifies you of new Github releases.


How to publish and unpublish content depending on the type of user? I have a site with content for two different user types: primary and secondary. I want to publish and unpublish some content depending on whether the current user is anonymous user, user primary or secondary user.

If the current user is an anonymous user:

to publish primaria/docentes
to publish secundaria/docentes
to unpublish primaria/docentes/kit
to unpublish secundaria/docentes/kit

If the current user is a primary user:

to unpublish primaria/docentes
to publish primaria/docentes/kit

If the current user is a secondary user:

to unpublish secundaria/docentes
to publish secundaria/docentes/kit

I try to do this with the the Rules module. The result of my configuration is this:
 - In the computer 1, I login as a primary user. Everything works fine.
 - In the computer 2, I login as a secondary user. Everything works fine.
 - If I return to the computer 1, the things are not good. I see that everything works as if logged in as a secondary user.

My settings do not respect the rules for the user already logged on. Every time someone logs on to any part of the world, that user settings apply to all other users in the world.

Please help me. I attached screenshots of my settings. :(

All my rules:

Log in as an anonymous user.

When primary user logs.

When primary user logs off.

Publishing and unpublishing is not the way to go.

Step 1)

Install the Node Access module and give access to each node or content type accordingly, this way people can't share direct links with other users that have a different role.

Step 2)

What you need is to create 3 different view blocks

One for anonymous which lists primaria/docentes & secundaria/docentes nodes.

One for primary which lists all the primaria/docentes nodes

One for secondary which lists all the secundaria/docentes/kit nodes.

  Hopefully node access module lets you filter your view by node access.
  Otherwise, you'll need to make the "kit", "primaria" and "secundaria"
  be a different content types so then you can filter by content type in
  your view.

Use view's access to role and select the role you want to be able to see the view. (see picture below)

Then you place all 3 view blocks wherever you need them (home page perhaps?) and since you have the view access by role, they will only see 1 view (the one they have access to).


Dynamic select forms I have created a custom form in Drupal 8 where I want to select a vehicle make, populate the models under the vehicle make and avail the list for selection in another field. I am stuck at the Ajax callback I have googled but haven't found a solution. I need guidance on how to use Ajax to get the desired results. My code is the following.

$query = \Drupal::database()->select('vehicle_make', 'veh');
$query->fields('veh', ['make_id','make_name']);
$results = $query->execute();
$options_makes = array();

foreach ($results as $result) {
$options_makes[$result->make_id] = $result->make_name;
}

$form['vehicle_make'] = array(
  '#type' => 'select',
  '#title' => $this->t('Vehicle Make'),
  '#options' => $options_makes,
  '#default' => '--Select Make --',
  '#ajax' => array(
    'callback' => 'ajaxfunction',
    'wrapper' => 'vehicle-model',
    'effect' => 'slide',
    ),
);

$form['vehicle_model_container'] = array(
  '#type' => 'container',
  '#prefix' => '
',
  '#suffix' => '
',
);

if ($form_state->hasValue('vehicle_make')) {
  $vehicle_make = $form_state->getValue('vehicle_make');
  $subquery = \Drupal::database()->select('vehicle_model', 'md');
  $subquery->join('vehicle_make', 'mak', 'md.make_id = mak.make_id');
  $subquery->fields('md', ['model_id','model_name']);
  $subquery->condition('md.make_id', $vehicle_make);
  $results = $subquery->execute();
  $model_options = array();

  foreach ($results as $result) {
    $model_options[$result->model_id] = $result->model_name;
  }

  $form['vehicle_model_container']['model'] = array(
    '#type' => 'select',
    '#title' => t('Vehicle Model'),
    '#options' => $model_options,
  );

  function ajaxfunction(array $form, FormStateInterface $form_state) {
    return $form['vehicle_model_container'];
  }

You shouldn't return fetched array as result, in Drupal ajax the return value from the ajax function actually overwrites the wrapper, so you've got to set $form['vehicle_model']['#options'] with fetched value and the return this piece of form ($form['vehicle_model']) as function return value. so the code will be something like this :

function _ajaxfunction(array $form, FormStateInterface $form_state) {
  $vehicle_make = $form_state->getValue('vehicle_make');
  $subquery = \Drupal::database()->select('vehicle_model', 'md');
  $subquery->join('vehicle_make', 'mak', 'md.make_id = mak.make_id');
  $subquery->fields('md', ['model_id','model_name']);
  $subquery->condition('md.make_id', $vehicle_make);
  $results = $subquery->execute(); $options_models = array();
  foreach ($results as $result) {
    $options_models[$result->model_id] = $result->model_name;
  }
  $form['vehicle_model']['#options'] = $options_models;
  return $form['vehicle_model'];
}


Pre-populate a field based on another node's field value I have several different fields attached to my user (user type) which are used to temporarily save settings for that user (most are node references, set by rules/flags/buttons)  Is there a way to auto populate a new node's fields based on tokens or rules so that every time a user starts to create a node, some of the fields are pre-populated based on the vales stored in the user's user fields?  Note: I would like to expose these values to the user during the node creation process.

You should check out hook_form_alter. It would let you preload form values but still keep them editable.

Something like this would work to load something from the user's profile fields into the node form for new nodes.

<?php
  function custom_module_form_alter(&$form, $form_state, $form_id) {
    switch($form_id) {
      case 'NODETYPE_node_form':
        global $user;
        $current_user = user_load($user->uid);
        // Set only on nodes that haven't already been saved
        if (!isset($form['#node']->nid)) {
          $form['field_YOUR_FIELD_NAME'][LANGUAGE_NONE][0]['value']['#default_value'] =
            $current_user->field_YOUR_USER_FIELD[LANGUAGE_NONE][0]['safe_value'];
        }
      break;
    }
  }
?>


Menu block module overrides I'm really confused with how to theme menus in Drupal 7 and I've found the Menu block module which is supposed to makes things simpler. Turns out it's not that simple for me.

I've created a Menu block called "myfooter" and thanks to the Menu block documentation page I was able to determine that the mytheme_menu_link__menu_block__myfooter() function seems to be acting on the menu. Huzzah.

But I don't know how to use it at all. It's not as if there was a $variables inside and I could var_dump the var to try and understand what's in it.

Currently, I'm only doing the following to check that it's actually replacing my menu items by a simple print statement:

function mytheme_menu_link__menu_block__myfooter() {
  print 'test string';
}

Basically, my problem is that Drupal outputs the menu with an unordered list structure that I don't need.

Item1

Item2

How can I wipe it to simply print my items one after another, with a pipe sign or dash or whatever separator I wish? Is mytheme_menu_link__menu_block__myfooter() even sensible to achieve that?

I've found a bunch of Drupal menu functions in the API but they are all so confusing I feel like I should stick to what Menu block offers.

Documentation for theme_menu_link():

function theme_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

The generated html needs to be returned as a return value.

The $variables argument has all the data.

Instead of var_dump(), you should install devel and do a dpm($variables). You might have to refresh the page twice to see the result.


Whats the difference between a 'page', a 'panel', and a 'handler'? I am porting a site over and looking through the code, and in a module there are folders for pages, handlers, and plugins/layouts (containing panels layouts) . The pages and handler folders contain .inc files. They are exports of pages and panels etc. However, what is the definitive difference between a handler, panel, and page?
Thanks

If you navigate to admin/structure/panels. It gives a short description.

Panel page

Panel pages can be used as landing pages. They have a URL path, accept arguments and can have menu entries.

Custom content
Custom content panes are basic HTML you enter that can be reused in all of your panels.


How can I set a default value for date field using hook_form_alter I am new to Drupal. I need to set a default value to a date field. Please anyone help me on this. Thanks.

Please see below code to set a default value for date field using hook_form_alter

$form["your_date_field"]["und"][0]['#default_value']['value'] = '2016-11-16 00:00:00';


How to make a multi field reference multiple content types? I'm trying to implement a Project Member relationship but I don't know how to do that. I have as a content types: Project, Member and Position as the attached UML diagram shows. My doubts are about the team field in Project.

I need to relate team members with a certain positon (which can be different from default position) to the Project. One way would be to create another content type called ProjectMember, but I'm trying to avoid that.

What would be the fastest vs the most elegant way to implement that?

Is Field Collection module a suitable way to go?

This is one way:

Project (Content Type)
Member (Content Type)
Position (Taxonomy - Because maybe you want to classify)

In Member you will have a field that is a Term Reference to Position.

In Project you will have a Field Collection named Project Position, which will have an Entity Reference to Member and a field that is a Term Reference to Position.


Change the path used by a route dynamically Taxonomy terms have a canonical path of /taxonomy/term/{taxonomy_term} by default, which displays a View with content tagged with that term.
For certain taxonomies I would like to use a different view, dependent on the taxonomy bundle, so I can't just override the path entirely.
For example, "article" tags should link to /articles/{taxonomy_term}, "product" tags to /products/{taxonomy_term}.
My idea is to override the entity.taxonomy_term.canonical route adding some kind of callback that generates the path dynamically based on the taxonomy_term. Is this possible?

I don't believe that there is any need for custom route manipulation in your case, and besides, while I am not entirely sure, I don't think that something like what you describe, would actually work, since then you might have issues with the view's contextual filtering.
I believe the TVI Module is the answer to your problem. It can be used to specify the view/views that will be used in the vocabularies of your choice.


Get this jQuery Youtube Playlist working? Drupal 7.  I'm trying to get this to work - seems simple enough.  I added the .js file through my theme's .info file, and it's picking that up.  I selected "Full HTML" as the format for my block, and pasted the code in (both the js and the ul).  Just doesn't work.

http://www.geckonewmedia.com/blog/2009/8/14/jquery-youtube-playlist-plugin---youtubeplaylist

Any ideas?  I suspect the js needs to be loaded somewhere else, that maybe it's being stripped out from the block code?

Per SoftArtisans (thanks) this is now what I have in the Body of my custom block (set to full HTML):

Video 1

Video 2

Video 3

It's still not working.  I verified the other .js file is being picked up in the source.

In Drupal, you can't just call jQuery quite like that. The reason is mostly because there my be other JavaScript libraries in use so jQuery is not aliased as $() in Drupal. For more details on that you can view the Drupal Docs about JavaScript compatibility, or the specific issue in the queue.

The solution is to wrap your jQuery code as described in the Drupal docs page linked to above. In your case it would look something like this...

(function ($) {
  $("ul.demo1").ytplaylist();
})(jQuery);


Voting API + Fivestar Voting - Restricting votes to user and not to IP I want Fivestar rating to be restricted to the logged in user and NOT to the IP they are using.

I want two (or more) logged in users using the same IP being able to have their own votings. At the moment it is possible to influence each other votings.

Am I missing something?

This is the default behavior.

Votingapi will limit to IP address when a user is anonymous. If the user is logged in the voting will be restricted by the User ID not ip address.

What version of votingapi are you using? If you're having a problem where this isn't the behavior a bug report might be more helpful.


Replacement module for Image FUpload Last week the Image FUpload module got the "no longer supported" status because "its dependencies swfupload are not maintained and not safe anymore".

Are there any Drupal 6 modules that can replace the Image FUpload module, allowing uploading multiple files/images at once? An HTML5 solution would be great. Thanks!

ImageField module is the perfect solution for your requirement. It is dependent on CCK and FileField modules. Some of the additional benefits provided by ImageField are it works fine with AJAX upload and removal, HTML5 and you can also restrict its behavior.


Pass the value in a field into a colorbox popup Is it possible to dynamically change a link on a colorbox popup a specific field value?

I have a view displaying a list of external links that have been added using a custom content type. And what I would like to do is be able to have a colorbox popup when you click on one of those links that explains that you are about to go to an external site.

I have the colorbox popup working with a button to go to that link, but I need the link of the colorbox button to change depending on which node they click on in the view.

My field is "field_conf_presentation_link"

Can I pass that value in anyway to the link that the popup would have?

Here is my view displaying the link they would click on:

Here is the code I have on my page template file that creates the content for the popup:

  <?php print '
' . t('You are now being redirected to view this live session.') . '
'; ?>
  <?php print l('Watch Now ›', '**LINK HERE**', array('attributes' => array('class' => array('btn-small')) ) ); ?>

I've been looking around and see that there is a module called Colorbox Node that might be able to give me what I want, but I am hoping I can get around that for something like this.

Using the Drupal Colorbox module you should be able to accomplish this.

You just need to add the class colorbox-load to your link and then to modify the colorbox settings per link append something like ?width=500&height=500 to the end of the path.

Colorbox Documentation

  Check the "Enable Colorbox load" option in Colorbox settings.

  This enables custom links that can open content in a Colorbox. Add the
  class "colorbox-load" to the link and build the url like this
  "[path]?width=500&height=500&iframe=true" or
  "[path]?width=500&height=500" if you don't want an iframe.

  If you want to pass the width and height of the Colorbox as a
  percentage (useful for responsive designs), you can format the link
  like this "[path]?width=90%25&height=90%25&iframe=true" or
  "[path]?width=90%25&height=90%25", where the "%25" is the HTML entity
  for "%".

  Other modules may activate this for easy Colorbox integration.

  Load inline content in a Colorbox

  Check the "Enable Colorbox inline" option in Colorbox settings.

  This enables custom links that can open inline content in a Colorbox.
  Inline in this context means some part/tag of the current page, e.g. a
  div. Replace "id-of-content" with the id of the tag you want to open.

  Add the class "colorbox-inline" to the link and build the url like
  this "?width=500&height=500&inline=true#id-of-content".

  It could e.g. look like this.

  Link to
  click  What
  ever content you want to display in a Colorbox.
  Alternatively instead of style="display: none;" you could use
  class="element-hidden".

  Other modules may activate this for easy Colorbox integration.


display only selected terms in custom node template How can I change the below code to display only the selected terms in the node. right now all terms which are defined in the vocabulary is displayed

<?php
$items = taxonomy_vocabulary_machine_name_load('test_categories');
$taxonomy = taxonomy_get_tree($items->vid);
foreach($taxonomy as $key => $items):
  print $items->name;
endforeach;
?>

For specific node you need to use $info = node_load($nid) where you find your field value using $info->field_name. Using that field you can use foreach something like foreach($info->field_name as as $key => $items).


How to validate input data that are previously saved? I am creating a module that can store user input in db and populate in a listing page with validation. I am collecting all values before submit i.e. any change in any field I store the form state in database, next I need to validate it on a listing page which will validate those input and give the error.

I have tried node_validate_form & drupal_validate_form but it's not working.

I think drupal_validate_form will do what I want but it omit default field validation like required validation or email validation are not validating properly and also in listing page it only validate the 1st one after that it is not checking any validation.

$header = array(
    array('data' => t('Field')),
    array('data' => t('Error')),
  );
  $rows = array();
  $owner = '';
  $result = db_select('MY_MODULE', 'lt')
    ->fields('lt', array('owner', 'form_state', 'form_state_input'))
    ->condition('lid', $lid)
    ->range(0,1)
    ->execute();

  if (!$result) {
    $rows[] = array(array('data' => t('No Result found.'), 'colspan' => 10));
  }
  else {
    $old_msg = drupal_get_messages();
    $_SESSION['messages'] = array();
    $node_form = (object) array(
      'type' => 'MY_CONTENT_TYPE',
      'language' => LANGUAGE_NONE,
    );
    $form = drupal_get_form('MY_CONTENT_TYPE_node_form',$node_form);
    $form['#submit'] = array('#type' => 'submit', '#value' => t('Next'));
    foreach($result as $r){
        $owner = l(t(user_load($r->owner)->name), 'user/'.$r->owner);
        $old_fs = @unserialize($r->form_state);
        $form_state_input = @unserialize($r->form_state_input);
        $old_fs['values']['uid'] = $user->uid;
        $form_state = array();
        $form_state['values'] = array_merge($old_fs['values'],$form_state_input);
        $form_state['values']['op'] = t('Save');
        $form_state['submitted'] = 1;
        $form_state['complete form'] = array();
        $form_state['rebuild'] = TRUE;
        $form_state['triggering_element'] = array('#parents'=>array('next'),'#button_type'=>'submit');
        unset($form['#token']);
        drupal_validate_form('MY_CONTENT_TYPE_node_form', $form, $form_state);
        $errors = form_get_errors();
        $noOfError = 'empty';
        if (!empty($errors)) {
          $noOfError = count($errors);
          foreach($errors as $field => $error){
            $field_name = explode(']',$field,2);
            $info = field_info_instance('node',$field_name[0],'MY_CONTENT_TYPE');
            $rows[] = array(
                    array('data' => $info['label']),
                    array('data' => $error),
                  );
          }
        }
        else{
          $rows[] = array(array('data' => t('No Error found.'), 'colspan' => 10));
        }
        form_clear_error();
    }
    $_SESSION['messages'] = $old_msg;
  }
  $build = array(
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => $rows,
    '#attributes' => array('id' => 'MY_MODULE'),
  );

Thank You In Advance....:)

oh..

drupal submit  form hook does the magic


Composer update still shows an older version of a module Updating dependencies according to these instructions offers an older version of the module. Composer.json file has the package required as "drupal/h5p": "^1.0@RC", and it used to update just fine. It seems to be stuck with version rc14 and unable to recognise any changes. It seems like a problem with packages.drupal.org being unable to update the package info.

The instructions on creating an issue about it here seem to be outdated as that is for a Drupal version 7 project.

Any ideas how could that be resolved? A newer version has been released in the meantime and the package manager is still showing the rc14 one.

The h5p module has 2 dependencies and must therefore be updated like this:

composer update drupal/h5p --with-dependencies


Site wont let me into administator areas Whenever I want to go to an admin only area (e.g. Modules), I get this error:

Fatal error: require_once(): Failed opening required
'/Applications/XAMPP/xamppfiles/htdocs/Ecommerce_website/sites/all/modules/openatrium-7.x-2.33/modules/system/system.admin.inc'
(include_path='.:/Applications/XAMPP/xamppfiles/lib/php') in
/Applications/XAMPP/xamppfiles/htdocs/Ecommerce_website/includes/menu.inc
on line 517

Any ideas?
(Tip: I have also tried putting openatrium back into the folder and it still gave me an error)

Why has it happened?

OpenAtrium is not a module, is an installation profile

You are mistaken an installation profile with a module. An installation profile contains the whole drupal core plus some extra modules and themes.

It means, you cannot put it in the modules directory of another Drupal installation. If you want to use an installation profile you do not need to use Drupal core.

How to fix it?

A: Re-install Drupal using OpenAtrium

If you want all the features in Open Atrium and you do not care about your current website, you'd better delete the whole thing and re-install Drupal using OpenAtrium.

Extract the content of OpenAtrium package to your document root (which is /Applications/XAMPP/xamppfiles/htdocs/ in your case). Then install it again.

B: Remove OpenAtrium and keep the current installation

If you already have a working Drupal installation and want to keep it, first you will need to remove OpenAtrium package out of it. There is no way you could use an installation profile along side a current installation.

First remove all the OpenAtrium files.

Then clear all caches. You can go to database and clear the content of all tables starting with cache_.

To access database you can use phpMyAdmin in browser (learn how) or an app like SequelPRO.

If the problem persists, you will need to rebuild the menu.


Why is url() outputting two '//'s? $form_state['redirect'] = url('node/add/media/' . $form_state['nid']);

When I get redirected it ends up at "http://mysite.net//node/add/media/772"

Any ideas?

I might be talking out my you know what, but just try:

$form_state['redirect'] = 'node/add/media/' . $form_state['nid'];


How can I hide nodes from view, but open access to JSON:API at the same time? I would like to use Drupal as a decoupled system, sourcing its content by using Gatsby.
Having set it all up, I would like my Drupal nodes not to be accessed by random unauthenticated users so I removed the permission from 'View Content'.

Having done that now I can't access the content by my Front end service which uses JSON API (unauthenticated of course).

What's the method to remove the node pages from the site and leave only the admin backend, while allowing to access the content using JSON API ?

If you're working with unauthenticated consumers, the Rabbit Hole module has the means to disable node/* routes without using the user role/permission system.

The Rabbit Hole module has a sub-module Rabbit Hole nodes that, when enabled, will let you disable node/* routes. This should leave open your jsonapi/* endpoints to anonymous consumers.


Undefined Index when adding a new field to any Content Type or Taxonomy Every time I add a new field to a taxonomy or any Content type, I get this error message on the edit screen.

Notice: Undefined index: default_image in image_field_update_field() (line 439 of /var/www/html/modules/image/image.module).

I'm stuck on where to debug next. Drupal logs show this message? Other image related modules include BackgroundField. Has anyone come across this?

Sounds like an issue with your current Drupal version

  A patch to fix this has been committed to 7.x and will be available in
  7.15. In the meantime, visiting the image field settings form and clicking Save will resolve the issue

More info: http://drupal.org/node/1558548
Patch here: http://drupal.org/files/drupal-1558548-3.patch


How to add classes to menu items in navigation twig template I'd like to add classes to <a>-tags for menu items that have a submenu.

Currently this is my code, I can only add classes to <li> elements:

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

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

There are two ways to add attributes to the <a> tag of a link, in the options of the url object or in #attributes of a link render element.

As I don't know how you can achieve the first in twig and to avoid an extra preprocess hook to do this in php, here is how you can replace the link function with a link render element in twig:

{% for item in items %}
  <li{{ item.attributes }}>

    {% set link = {
      '#type':       'link',
      '#url':        item.url,
      '#title':      item.title,
      '#attributes': { class: ['link-class1', 'link-class2'] },
    } %}

    {{ link }}

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

  </li>
{% endfor %}

Edit:

I just found out, that in contrast to the php function l() the twig function link() does provide a 3rd parameter to add attributes, so this is a much easier solution:

{% for item in items %}
  <li{{ item.attributes }}>

    {{ link(item.title, item.url, { class: ['link-class1', 'link-class2'] }) }}

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

  </li>
{% endfor %}


hook_form_alter won't save options cck field from custom form I have created content type named "site_profile", and form named "add_website_form".
The content type includes cck fields and one of the fields is "field_operators" which is select box field.
I have hooked options of the field to display variable that contains array of specific users with some mechanism.
The hook_form_alter is:

function lcm_form_site_profile_node_form_alter(&$form, &$form_state, $form_id) {
    $relevant_users = lcm_get_relevant_users();
    $form['field_operators']['und']['#options'] = $relevant_users;
}

Now I am trying to get functionality that stores data into the node through node_save() function from the "add_website_form" (costume form).

the code that supposed to insert the data is:

function lcm_add_website_form_submit($form, &$form_state){
    $website_name = $form_state['values']['website_name'];
    $url = $form_state['values']['url'];
    $operators_for_site = $form_state['values']['operators_for_site'];
    lcm_add_website_form_insert_to_db($website_name, $url, $operators_for_site);
}
function lcm_add_website_form_insert_to_db($website_name, $url, $operators_for_site){
    // Create a node object, and add node properties.
    $new_website = new stdClass();

    $new_website->type = 'site_profile';
    $new_website->title = $website_name;
    $new_website->uid = $GLOBALS['user']->uid;
    $new_website->field_url['und'][0]['value'] = $url;
    $new_website->field_operators['und']['value'] = $operators_for_site;
    $new_website->created = strtotime("now");
    $new_website->changed = strtotime("now");
    $new_website->status = 1;
    $new_website->comment = 0;
    $new_website->promote = 0;
    $new_website->moderate = 0;
    $new_website->sticky = 0;
    $new_website->language = 'und';

    node_object_prepare($new_website);
    // Save the node.
    node_save($new_website);
}

the problem is that the data that supposed to save on field_operators doesn't save...
Any ideas?

Ok, new answer, replace:

$new_website->field_operators['und']['value'] = $operators_for_site;

with this

$new_website->field_operators['und'][0]['value'] = $operators_for_site;


Placeholders must have a trailing [] if they are to be expanded with an array of values In Drupal 8 I am trying to insert some data in my custom table. While executing query I am getting error:

  InvalidArgumentException: Placeholders must have a trailing [] if they are to be expanded with an array of values. in Drupal\Core\Database\Connection->expandArguments()

Please find my code below:

$qt = new \stdClass();
$qt->name = 'test name';
$qt->machine_name = 'test machine name';
$qt->settings = array('setting1'=>value1, 'setting2'=>value2);

$query = \Drupal::database()->insert('my_custom_table');
$query->fields([
  'machine_name',
  'name',
  'settings',
]);
$query->values([
  $ob->machine_name,
  $ob->name,
  $ob->settings,
]);
$query->execute();

If I am giving values like below it is working. Please help me whats wrong with above code.

$query->values([
  'test',
  'ttt',
  'dfs',
]);
$query->execute();

That issue got resolved. It was regarding passing array in to the db. Added serialise function resloved the issue.

$query->values([
$ob->machine_name,
$ob->name,
serialize($ob->settings),
]);
$query->execute();