Sort a Table View by Fivestar Rating Fields I'm currently using Fivestar-7.x-2.0-alpha2 and Views-7.x-3.7. And running Drupal 7.

I am trying to create a table view that displays the information from fields on a certain node type. In this case, the "Program" node and all of the rating fields (fivestar fields) and two text fields (Discipline and University). You can see what I have currently here.

The problem I am having is I can't seem to get the table to sort properly. I have cleared out the Sort Criteria so there isn't any sorting being applied other than from the table settings (I think?). I went into the table settings for the view and checked off sortable for all of the fields. However, when I try to sort them they either don't change at all (the fivestar and computed fields) or they sort improperly (the University field).

I'm at somewhat of a loss. I've done hours of Googling but I can't seem to come up with any sort of solution. If anyone could offer some advice I would be most appreciative.

I should also note that the "Overall" field is a computed field that averages all of the fivestar fields.

This is incredibly late, but I just found the answer to the Fivestar rating issue:

You need to add "Content: Vote results" as a View relationship, then sort by "Vote results: Value".

Sorting by "Rating: Average Rating" seems to do nothing, as the queried fields seem to be undefined. This method, however, will work.


Using forms and templates and _submit callback I'm trying to wrap my head around the process of creating a form and handling the submitted data using x_submit().

I start by having a form callback:

function world_form(&$form_state) {

  // if ($form_state['post']) { drupal_set_message("Solved!"); }

  $forms['fieldset_options'] =
    array('#type' => 'fieldset',
          '#title' => t('Options'),
          '#collapsible' => FALSE,
          '#collapsed' => FALSE);

  $forms['fieldset_options']['tags'] =
    array('#type' => 'item', '#title' => 'Simple stuff');

  $forms['fieldset_options']['checkbox1'] =
    array('#type' => 'checkbox', '#title' => t('Solve world problems'));

  $forms['fieldset_options']['submit'] =
    array('#type' => 'button', '#button_type' => 'submit', '#value' => 'Go!');

  // $forms['submit'] = array('#type' => 'submit', '#value' => 'Go!');

  return $forms;
}

So I specify a theme callback, which takes me to a file world.tpl.php in which I do:

print drupal_get_form('world_form');

which invokes my form callback. So far so good. Now the problem I have is that I want to handle when this form is submitted (more specifically, I want the value of the checkbox when it is checked). I read a lot of documentation and most mention the world_form_submit function. So I create one like this:

function world_form_submit($form, &$form_state) {
  drupal_set_message("Posted!");
}

But after I've done that the function isn't called. However if I instead use the line which is commented out in my form function and comment out the '#type' => 'button' field it DOES get called and I can now access the checkbox state, however the problem I have now is that the form is not updated with the state of the checkbox (I.e. if I check the box and submit I get to the same page but the box is no longer checked).

So my questions are:

Why isn't the _submit callback called when I use a "regular" submit button? Do I have to use the $forms['submit'] way?
If I do get the _submit callback called, can I still update my form to reflect what it was before I submitted, and
How can I get the checkbox state in my world.tpl.php file? Say I want to print something if it is checked.

Thank you for your time.

Many questions here:

Your form function function should return the form array and doesn't need an argument unless you need it for something specific.
You should at least have an element of type 'submit' (not button) in your form.
Chances are good your submit function will get called if you implement it this way.
If the form fails validation, FAPI will restore it to the values submitted, keeping what was typed by the user.
You shoudn't try to embed business logic in your template, but rather in your module and/or a preprocess function.


Is there any other way to store values in DB other than 'system_settings_form'? On change(using AJAX) of Job title the text area will show and admin will enter text in admin form. By using system_settings_form I am storing values in DB using Variables.

PROBLEM:

I have more than 20 values in the dropdown.
For this I need to store the textarea values in a variable.
This leads to huge values stored in variable table.

Is there any other way rather than using this, or is this the best way of using?

I am just checking all the possibilities.

Any Ideas will be much appreciated, Thanks.

You can store your data wherever you like, in whatever format you like, and you can manage it in any way that php allows; Drupal doesn't have an opinion on the matter.

If you're asking whether Drupal has another variable API you can use for this slightly different requirement, then no it doesn't.

So to answer your question directly

  Is there any other way to store values in DB other than 'system_settings_form'

Yes, just use the database API in whatever way you think is appropriate for the data you're storing/retrieving. Various modules provide data layers, e.g. ctools has a data API as Jimmy mentioned in the comments. There's also the core entity API, but that's going to be overkill for your needs.

All that said, you might want to actually profile your code to see if 20 values serialised into a single row is going to cause you any real problems. Yours and MySQL's definition of "huge" might be quite different.


Posting drupal content to tumblr I am trying to post article content type to my tumblr account (want to post all articles created by different user roles) . I have tried tumblr_connect but its not working i have also installed tumblr api module and registered a application and added the keys.

But i am stuck there i dont how to configure to post only the article content type and link it to my tumblr blog.

You will have to do this in code. Use hook_node_insert() in a custom module and filter by content type. You can then invoke the tumblr API and send the node data across. See tumblr.lib.php for API usage.


Field Label for Content Type I need to find where the field label for a content type is stored within the database. I tried the field_config_instance, it's not there.

Yes it is, you just need to look a bit harder ;)

Have a look at the serialised array in the data column of that table. You'll find the label for the field listed in there.

If you want to extract this in code the best way is to use the field API functions, it saves you having to mess about with the serialised array directly:

$entity_type = 'node';
$field_name = 'body';
$bundle = 'article';

$info = field_info_instance($entity_type, $field_name, $bundle);
$label = $info['label'];


How to track down possible module conflict? I am trying to get the SMTP Authentication Support module working on my development site. Whenever I try to send a test message, I get the error "SMTP -> ERROR: Failed to connect to server: Permission denied (13)." Our SMTP server is configured to accept relay from any client on our internal network, which is where my server lives. When I look at the logs, I see two errors - one of type "mail" and one of type "smtp".  Each say about the same thing.  This leads me to believe that the SMTP module is conflicting with something, but no other modules are currently installed.  I have tried/removed other versions of the SMTP module and the PHPMailer module.  I can't find a "mail" module in the Core section, so I don't think that's it.

When I install the module on my local machine, in a clean Drupal instance, with all the same configuration settings, the test message flies right through.  So, I'm guessing that maybe one of the other modules left some cruft behind in the database somewhere, and this may be causing a conflict with the SMTP module.  However, I don't know how to hunt down and eradicate the problem.

Any ideas?

After much beating my head against the wall, I found a solution:

https://drupal.org/node/1593684

Turns out, it was SELinux snuffing out the SMTP attempt before it could even reach the server!  Doh!


How to render a field collection? How can I properly render a field collection ? Is there any specific function for that ? I tried field_view_field but it does not output children fields.

My field collection is attached to a line item entity, and I want to display it in a Commerce checkout pane review.

function mymodule_pane_review($form, $form_state, $checkout_pane, $order) {
  //loading line item
  $line_item = commerce_line_item_load($order->commerce_line_items['und'][0]['line_item_id']);
  //loading field_collection from its id
  $paxsup = entity_load('field_collection_item', array($line_item->field_paxsup['und'][0]['value']));

  return drupal_render(field_attach_view('field_collection_item',$paxsup, 'full'));
}

but get an error EntityMalformedException: Missing bundle property on entity of type field_collection_item

EDIT : I got a step forward, with the use either of

$paxsups = entity_load('field_collection_item', array($line_item->field_paxsup['und'][0]['value']));
$paxsup = end($paxsups);
//or shortcut, as per Marcvangend
$paxsup = field_collection_field_get_entity($line_item->field_paxsup['und'][0]);

dsm($paxsup) now returns

So I can output a child field with

$view = field_view_field('field_collection_item', $paxsup, 'field_paxsup_civilite', $display);
return drupal_render($view);

EDIT 2: I ended chaining #markup

$display = array('label' => 'hidden');
$cv = field_view_field('field_collection_item', $paxsup, 'field_paxsup_civilite', $display);
$nom = field_view_field('field_collection_item', $paxsup, 'field_paxsup_nom', $display);
$prenom = field_view_field('field_collection_item', $paxsup, 'field_paxsup_prenom', $display);
$date = field_view_field('field_collection_item', $paxsup, 'field_paxsup_datenaiss', $display);
$view .= $cv[0]['#markup'] .' '. $nom[0]['#markup'] .' '. $prenom[0]['#markup'] .t(', né(e) le '). $date[0]['#markup'] ;

But I'm not happy with this "old style" solution, would have preferred to find a more elegant and Drupal way to output that field collection

You may want to have a look how the field_collection module itself renders field collections in the field_collection_field_formatter_view function. I think it's important to note that is uses field_collection_field_get_entity() to load a field collection.

Looking at the code (not tested) I think you can do something like this:

if ($field_collection = field_collection_field_get_entity($line_item->field_paxsup['und'][0])) {
  return $field_collection->view('full');
}


How to speed up Batch API Operations? I've run into this both with 3rd party contrib modules as well as some of my own operations. I'm curious at the various ways to speed up my/contrib batch operations?

Assume they work with nodes (import/update etc) and we're dealing with parsing lists of nodes in the 10,000+ range (although I've had to deal with 15 million rows.. which yes - I'm just screwed on..)

Is it quicker to attach to drupals cron.php job and run "headless"? Using Drush? or is this simply a question of how efficient and quick parsing I can develop my code and there are no outside influences or batch specific optimization tips ...

Currently I've run into operations that (using some rough calculation) could take 24+ hours...

Thanks!

This doesn't work for contrib code, but if it's your code and you know it well, I recommend writing a drush command to do the work.  Within drush, limit drupal_bootstrap() to the appropriate bootstrap level.  I can't recall the actual numbers, but a very large percentage of time for every drupal request is spent in bootstrap, and you can save a lot of time there.

Furthermore, check out the guts of the Migrate module.  I don't know how it does it's mojo (never taken the time to grok it), but it can blaze through huge batches of nodes very quickly.


Detect when user accesses the site I would like to perform an actoin if the user's last access time was last month.

Would this be through hook_user(), when $op is equal to "after_update"?

I assume the last access variable would be updated, and I could check.

Drupal saves the timestamp of a user's last access, but by the time your can react to a user visiting the site, that value has already been overwritten with the current timestamp (that happens in sess_write()). I don't have a cut-and-paste solution for you, but there are some ideas how to store the previous timestamp for later use in this forum topic.


Allowing Automatic Logins from a Range of IP Addresses I'd like to implement the following functionality in my site:

Give an entire organization access to our Drupal 7 site from a specific range of IP addresses.

The way it would hopefully work is this: users in the organization, from any of the computers in their organization (in the ip range) would be able to go to our site and be automatically logged in.

Other users with individual accounts in our system should not be restricted from logging into our site.

Anyone know how to accomplish this?

IP Login

This module allows users to login automatically via their IP (v4)
address ranges or wildcards instead of having to enter a username and
password - plus many other features.


How can you force a stylesheet reload in Drupal7? This is about that old trick of tacking a fake query argument onto the URL of a stylesheet (e.g., <link rel="stylesheet" type="text/css" href="http://www.example.com/site.css?v=123">) so that, when you change the stylesheet, it'll be reloaded by the users' browsers, since it looks like a URL that's not in the browser's cache.

So, the question: How can you do this in D7 where the stylesheets are specified in the .info files?  I tried adding a query arg onto the entry in my site's info file -- stylesheets[all][] = site.css?v=123 but without any luck (the page rendering got very unhappy).  Any ideas?

You can do this with drush

$ drush help cache-clear
Clear a specific cache, or all drupal caches.

Arguments:
 type                                      The particular cache to clear. Omit
                                           this argument to choose from
                                           available caches.

Aliases: cc

So you can do

drush cc css-js

and this will rescan the cached CSS and JS files, nuke them if they are stale, and generate a new key that gets appended to CSS and JS URLs.


Offers with reservations My client wants a site where registered users can create paid offers of rooms to rent and other users can book those rooms. Users who created offers should be able to see those  reservations.

I think that registered users could create offers as nodes with payment options using the Pay-per-node module. I don't know how to create the booking feature. I tried to use a few modules, but none was proper for my goal.

There are some useful options, Please note that both Drupal Commerce and Ubercart have Marketplace modules which you could use in combination to achieve your desired functionalities:

A. Rooms helps with booking and room management, More info also available here

  Drupal Rooms is a booking and room management solution for hotels,
  vacation rentals and B&Bs.

  It allows an accommodation owner to:

Create rooms and assign availability (or on hold states) via a
calendar.
Manage pricing for rooms using calendars that allow to set pricing for entire seasons or just change it for specific dates.
Define optional add-ons for rooms. Charge either per-night or per-person. Handle children discounts. Create bookings and keep customer records.
Make rooms available for booking with a availability
search functionality and/or calendar - handling both immediate bookings and bookings following owner confirmation.
Search by Room Type.
Full integration with Commerce to manage payments, a range of different payment gateways, and a host of other e-commerce features.
Accept full or partial payments (deposits) using Commerce features.

B. Hotel Booking System For Ubercart

  The uc_hotel module is a hotel booking system for Drupal and Ubercart.

  It does not manage individual rooms, but rather lets you create room
  types, and set how many of each type are available for specific dates
  on the calendar. Each room type can be assigned a different rate, or
  be based off a single master rate and have a modifier applied to
  adjust that rate by a certain amount.

  You can vary the rate based on the number of adult and child
  occupants.

  The module also features an add-ons and upgrades sub module that
  allows you to bundle other date-based upgrades with the booking such
  as tennis lessons or spa treatments.

C. Open Hotel

  Open Hotel is a Drupal 7 Distribution that helps you create a full
  featured Hotel site with online booking and online availability.

Features

Online Availability
Online Booking
Multilingual
Photo Galleries
Responsive Design
Google Analytics E-Commerce Integrated
Free and Open-Source
Easy to integrate with any payments processor.
Search Engines Optimized


User Login Block does nothing The core user login block does not appear to work.

I have it placed in the Header region (Omega theme if that helps), with the following overrides:

function mytheme_theme(&$existing, $type, $theme, $path) {
   $hooks['user_login_block'] = array(
     'template' => 'templates/user-login-block',
     'render element' => 'form',
   );
   return $hooks;
 }

This lets me use my own tpl file for the login block.

function mytheme_preprocess_user_login_block(&$vars) {
  $vars['name'] = render($vars['form']['name']);
  $vars['pass'] = render($vars['form']['pass']);
  $vars['submit'] = render($vars['form']['actions']['submit']);
  $vars['rendered'] = drupal_render_children($vars['form']);
}

This lets me pass new variables..

Then in the tpl file:

    <?php print $name; ?>
    <?php print $pass; ?>
    <?php print $submit; ?>

    Create an Account | Forgot Password

Except when I login, the page refreshes, and nothing happens. User is not logged in, no error. When I use correct or incorrect credentials, nothing happens.

I used this same approach on a Drupal 6 site and it worked fine. Where am I going wrong?

I disabled Login Destination and Login Toboggan while debugging, no change.

You should print hidden elements:

    <?php print $name; ?>
    <?php print $pass; ?>
    <?php print $submit; ?>
    <?php print $rendered; // HERE HIDDEN ELEMENTS ?>

    Create an Account | Forgot Password


How to get the JSON/array value property name for a field instance? Given a Drupal\Core\Field\BaseFieldDefinition  how do you get whether the value is stored by target_id, or value or uri or color or ....

it seems getMainPropertyName() is what i'm looking, for but it returns null for the majority of fields. in my case it's only returning target_id or value for for created, status, and entity_id.

I just tested using a variety of field types, and it seems to work OK for me. Here's the code I used for testing:

$node = \Drupal\node\Entity\Node::load($nid);

print $node->get('field_test')->getFieldDefinition()->getFieldStorageDefinition()->getMainPropertyName();
print $node->get('field_test_image')->getFieldDefinition()->getFieldStorageDefinition()->getMainPropertyName();
print $node->get('field_test_link')->getFieldDefinition()->getFieldStorageDefinition()->getMainPropertyName();
print $node->get('field_test_email')->getFieldDefinition()->getFieldStorageDefinition()->getMainPropertyName();

This returns value, target_id, uri and value as one would have expected. What kind of fields are giving you trouble? How do you get you BaseFieldDefinition class? What kind of entity are they connected to?

I notice that the Views way of getting the property name is also pretty pragmatic:

// EntityField.php line 1111
if ($main_property_name = $field_item->mainPropertyName()) {
  $values[] = $field_item->{$main_property_name};
}
else {
  $values[] = $field_item->value;
}

Clearly it's not completely unexpected to have this method return null.


Image style effect for removing empty space around image There can be a lot of situations when e. g. set of logos in png format are not cropped regularly and some images can have different white spaces around the actual logo in the image.

Is there any module that adds an image style effect capable of cropping white space (transparent or white) around image?

I don't think you can with a module. The only solution is use Photoshop or else.
ImageCache Actions is the best module for custom style image, but I don't believe is going to...


comments module with infinite scroll I've added a comment field to my content type. Now I'd like to add infinite scroll to the comments messages, so it shows by default some number of comments and when I click on the load more button, it shows more.

The problem is that the list of comments is coming from the comment module, not a view, so I can't add infinite scroll plugin to the pager. If I create a custom view that shows the comments, it gets complicated because some comments have nested comments and so on. Is there any solution?

One option is to create a "views block" that shows comments, set it to use views infinite scroll, then add it to the bottom of the page (and disable the page from showing comments the normal way).


Drupal 7 - Suppress output of nodes on Taxonomy Pages Is there a way to suppress the output of nodes on taxonomy pages, without having to install a module (i.e. just in template.php)?

Nodes tagged with a taxonomy term appear on the "Taxonomy Index page" (e.g. yoursite.com/taxonomy/term/[id]).

New in Drupal 7, Taxonomy Index pages can have fields attached to them. However, if you try to over ride the taxonomy page with a View (for example, to control how the nodes are displayed), the fields on the Taxonomy Index pages will not appear.

I have therefore placed my Taxonomy View as block on the Taxonomy Index page. That way, I can control how the nodes appear and still have the Taxonomy Index page fields.

Because of this, the taxonomy page is still outputting its nodes. I can hide them by setting the teaser of the nodes to hidden, but it still loads up the nodes (and therefore any CSS/Jquery attached to nodes even though the nodes aren't being displayed). How can I suppress the nodes from appearing, ideally from inside of template.php?

Solution from http://www.wardontheweb.com/remove-node-lists-from-taxonomy-pages-in-drupal-7/ works for me well:

function THEMENAME_preprocess_page(&$vars){
   if (arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))){
     unset($vars['page']['content']['system_main']['nodes']);
     unset($vars['page']['content']['system_main']['pager']);
     unset($vars['page']['content']['system_main']['no_content']);
   }
}

Note: you should reset your site's cache.


add fields directly to node table? Is it a good idea to add field directly to the node table via db_add_field and schema_alter? e.g. i want to add just number of views field to it. I know the recommended approach is field api but find it kind of overkill to create a new table just for a simple field like that. Let me know your views on that approach.. has anyone done it in a project?

Perhaps this is not drupal standard, sometimes is needed to do things like that.

I prefer to create my own entities that to modify the node entity. This way if you use entity api as base this is integrated with views out of the box. Another approach to that not require coding is ECK module, you can define properties to the entity and this will be added on the same entity table as and extra column.


Commerce Node Checkout free option skip cart/checkout/payment I am working on a free/paid listing site. I setup Commerce Node Checkout with Node Checkout Expire and have a free version(14 days) and a paid "featured" option (30 days). The paid option should go to cart->checkout->payment while the free option should act and behave as if Drupal Commerce wasn't installed.

I was looking around rules but I can't seem to find the proper events/conditions/actions to basically treat free listings as regular drupal nodes. I don't really want to track orders for free listings, but I also don't want to mess Drupal Commerce's reporting up either.

Can rules do this? And if so, what would be the proper events/conditions/actions to bypass Commerce all together and just publish the node if "free listing" is selected under listing options for Node Checkout.

Thanks

You can write a custom module that implements hook_node_submit() and that sets

$form_state['values']['commerce_node_checkout_skip'] = True;

if the free version is selected.


How do you programmatically get the shipping information from a placed order? So far I have a working piece of code that sends me an email ($to variable) when a new order has been placed on my drupal 8 commerce.
This is not the email the person that places the order gets.

As part of the body of the email, i was able to find and use variables like a custom attribute, sku, quantity, product name etc...

I realize that in the orderCompleteHandler(), i might have to change what i send as a parameter, instead of $items having to possibly send $order.

But where can i find/how can i get the shipping information, like shipping address, shipping date and the user's that placed the order name : I would like to add them to the email i send.

More importantly is also: how do i find all this info and others by myself? i tried to kint($order) and it either freezes or runs out of memory. I tried dpm($order) and i get 10K lines of info but nothing that is obvious.
I tried to look in those 10k lines for some unique data that i knew was part of the shipping info but it wont show up, most likely because that value will be the return value of a get function.

Basically, how should i look and where should i look if i want various information from the order placed variable aka $order?

Any help in debugging and pointing me in the right direction would be appreciated.

public function orderCompleteHandler(WorkflowTransitionEvent $event) {

        // @var \Drupal\commerce_order\Entity\OrderInterface $order
        $order = $event->getEntity();
        $items = $order->getItems();

        $mail_manager = \Drupal::service('plugin.manager.mail');
        $to = 'myEmail@gmail.com';
        $langcode = \Drupal::currentUser()->getPreferredLangcode();
        $type = 'order_placed';

        $mail_manager->mail('my_custom_order', $type, $to, $langcode, $items, NULL, TRUE);

    }

/**
 * Implements hook_mail()
 * Prepares emails sent by the MailHandler service.
 * Emails are sent within the OrderComplete Event Subscriber.
 */
function my_custom_order_mail($key, &$message, $params) {
    switch($key) {
        case 'order_placed':
            $options = array(
                'langcode' => $message['langcode'],
            );
            // Creating an html formatted email.
            $message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed; delsp=yes';
            $message['from'] = 'staff@myCompany';
            $message['subject'] = t('Order @order_number confirmed', array('@order_number' => $params[0]->getOrderId()), $options);

            $entire_email_display = '';
            foreach ($params as $product) {
                // Get the Custom Location.
                $productLocation = $product->getPurchasedEntity()->getAttributeValueIds()['attribute_custom_location'];
                $order_item['sku'] = $product->getPurchasedEntity()->getSku();
                $order_item['quantity'] = (int)$product->getQuantity();
                $order_item['product_name'] = $product->getPurchasedEntity()->getTitle();

                // HERE I BUILT an entire email body and stored in the $entire_email_display.
            }

            $message['body'][] = $entire_email_display;
    }
}

You can have the shipping information with :

$shippement = $order->shipments->first()->entity;
$shipping_profile = $shippement->shipping_profile->first()->entity;


Field Collection with Date for Calendar View I'm working on the content design for a new site, but I'm having a major hangup with some of the connections between the data types, especially when it comes to Dates and Calendars.  Here's the rundown:

Films share a many to many relationship with Programs.
Programs can have one or many Screenings.
Screenings each have one Date and Venue.

I've successfully accomplished this using Node Reference and Field Collection.  There is a node reference between Films and Programs.  Programs contains a field collection called Screenings.  The field collection Screenings contains the fields Date and Venue.

The functionality I love from this setup is that each Date and Venue pair is grouped, and I can just click the Add button to generate another pair within that Program.  This satisfies the one or many requirement for Screenings.

Unfortunately, when I start to build this all into a Calendar view (Date module, Calendar module), it breaks terribly.  Depending on how I set things, I end up with SQL errors or index errors within Drupal.  None of it works.  Reading through issue posts, I've gathered that this is probably some sort of complexity added by Field Collection which is not handled in Calendar.

Short of getting Field Collection to play nice with Date and Calendar, can anyone suggest another method for implementing this?  My next thought would be to move Screenings off into its own node and create another node reference between that and Programs.  However, that would mean I lose the clean and simple Add button to generate a new Screening within a program.

Perhaps a custom add/edit form is all I really need.  Unfortunately, that road seems rather perilous for me without some clear guidance.

I couldn't get Calendar to play nice with Field Collections.  It seems like I needed to somehow provide for the custom calendar row plugin or calendar items within the field collection view (it's too complicated).

Ultimately, I went with the FullCalendar module, which is built on the FullCalendar jQuery plugin.

It's very clean, simple to setup, and it plays very nicely with everything I'm throwing at it.  If Calendar and Field Collections make any further progress with their development, I might revisit them, but for now this fits the bill.


Date time formats: October not correctly written in German I created a time format in Drupal administration (admin/config/regional/date-time) with the following settings in EN/ DE:

DE: d. F Y -> 05. October 2016
EN: dS F Y -> 05th October 2016

The problem is that "October" is written in German like "Oktober" ("k" instead of "c"). The strange thing is that the translation works fine with every other month ("May" for example becomes "Mai" in German) but just the October is written wrong. This appears to be an issue no matter where the date field is rendered, in views or node detail page.

Additionally this seems to be an issue with the PHP date format as it the same problem when using date('d. F Y', $timestamp). Can anyone give me a hint how to solve this issue?

The name of the month can be change via interface translation - see comment of Drupaler


very bad thing of output the vocabulary in drupal 7 I created four  vocabularies for the "article" content type.
I want to output the vocabulary which belongs to the node; when I used print render($conetent['field_vocab']), it output the vocabulary, but the HTML structure is too bad; more useless <div> and classes make me crazy. In order to remove them, I output it like this:

$content['body']['#object']->field_vocab['zh-hans'][0]['taxonomy_term']->name;

It's too long, and it makes me crazy too. If the vocabularies contain more than one taxonomy term, it only prints one.

Is there a better way to output the  vocabulary?

What you are looking for is what is called field formatters. It is essentially theme function for themes, and can be used to render the same field in ['form'] ways. You can create a custom field formatter where you render the output of the field how you want.

To read more about fields and formatters see: http://drupal.org/node/707832
Or you can checkout this step by step guide on how to create a field formatter.

Another option would be to simply overwrite the theme function (That can be done with any theme function) used for the default field formatter, which would then effect all of the fields across your site.


How to build multivalue form elements using Form API With the 'field collections' module at the form level, you can create a fieldset (or 'field group') that will accept multiple sets of values.

Is there a way to do this with the Form API directly (or with the help 'field collections' or 'field group' module) programmatically.  I can make the form fieldset easy enough, but I'm not sure how to set multiple values for this set.  In fact, I'm not really sure how you define multiple values for any field with the Form API.

UPDATE: Just to be clear I want to create the form, not the entity itself (at least not yet).  I want to use the Form API to accomplish this to make my own $form – just the form.

Suppose 'field_page_collection1' is the field collection for the 'page' content type having two text fields 'field_page_collection1_text1', 'field_page_collection1_text2'.

To attach or create field-collection item for node having node id 1.

<?php
$node = node_load(1);
$field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_page_collection1')); // Create new field collection item.
$field_collection_item->setHostEntity('node', $node); // Attach it to the node.
$field_collection_item->field_page_collection1_text1[LANGUAGE_NONE][0]['value'] = 'some value for text field 1'; // Fill value for field_page_collection1_text1.
$field_collection_item->field_page_collection1_text2[LANGUAGE_NONE][0]['value'] = 'some value for text field 2'; // Fill value for field_page_collection1_text2.
$field_collection_item->save(); // Save field-collection item.
?>


Where are the pages for the Statistics module shown? I've installed the Statistics module (version 7.18) in my Commerce Kickstart 2 store, but I can't find it anywhere in menu.

What should I do to access this module?

After enabling the statistics module, be sure to configure the module (admin/config/system/statistics).

The documentation for the statistics module indicates that:

  To enable collection of statistics, the Enable access log checkbox on
  the Statistics settings page must be checked. This access log is used
  to store data about every page accessed, such as the remote host's IP
  address, where they came from (referrer), what node they've viewed,
  and their user name. Enabling the log adds one database call per page
  displayed by Drupal.

  The Discard access logs older than setting on the settings page
  specifies the length of time entries are kept in the log before they
  are deleted. This setting requires a correctly configured cron
  maintenance task to run.

  Enable Count content views to turn on and off the node-counting
  functionality of this module. If it is turned on, an extra database
  query is added for each node displayed, which increments a counter.

After configuration, data will begin to be collected for the four reports that statistics provides:

Recent hits (admin/reports/hits)
Top Pages (admin/reports/pages)
Top Visitors (admin/reports/visitors)
Top Referrers (admin/reports/referrers)

NOTE: This applies to all Drupal 7 installations.  Statistics is a core module and is not specific to Commerce Kickstart 2.


D7 - Commerce Stock - Track products in different unit (e.g. grams?) I'm using Commerce Stock to track the amount of product stock we're currently carrying. That said, Commerce Stock only seems to let me track product in increments of 1? Is it possible for me to change the unit stock is tracked in? For example, grams? E.g. If my user purchases 10 grams, it should subtract 10 from the total 100 grams in stock.

One way of achieving this is to let Commerce Stock behave in its usual way, but to override the output on user interface, which should be pretty easy using the right hook. In other words, the custom code could just multiple stock quantity by 10 and, for example, instead of 1 output 10. So total 10 items would become 100 instead, if one item purchased then it would subtract just 1 on backend to output the remaining 9, but your function would just output 90 instead.


How can I export node data the same way you do webform data? We had previously used webform to collect data and our "power users" got used to being able to export the submissions to Excel easily. For various reasons, we've switched from webform to a custom content type. Is there a module out there (or maybe a module isn't even necessary) that would let these users (who do NOT have access to the admin functions of the site) to do the same kind of exporting of nodes?

Use the Views data export module.

This module is 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 (or really simple HTML understood by Excel)
Microsoft DOC
Basic TXT
XML


Setting up drupal's js and css on CDN I've got my drupal site set up so that all newly uploaded files are automatically stored on my CDN (Rackspace Cloud Files).

The only thing I need moved over is drupal's core css and js (along with the css and js for all of the installed modules).

I've been reading over the CDN module and the FileConveyor daemon, but it seems like a lot of overkill. I don't need a daemon that watches for new files and transports them over to CloudFiles. I really just need a one-time deal.

Is there an easier way?

My "easier way" was simply to copy all of the core css and js as well as the all of the modules css and js up into my CloudFiles container and then configure the CDN module to automatically rewrite the URLs of any .css or .js file.


Does Page Manager redirect work on alias paths? I am attempting to do a simple custom  page redirect using page manager following the example from NodeOne.se videos on Page Manager. While the video works, my attempt does not and I can't see the difference other that the alias path I use.

The  URL I want to intercept is specs/%spec so I have created a custom page with that URL. I have configured the page with one argument to interpret %spec as a taxonomy term ID.

Next I created a variant set to perform an HTML redirect (301) to the URL materials/%spec:name/facts (This URL will call a view). There are no selection rules so all content will pass. Thee are no contexts or relationships since the argument for the term name is already visible in the summary of contexts present.

My expectation is that a URL such as Example.com/specs/term1 should redirect the website display to the contents called by the view page /materials/%/facts using with term1 applied as a contextual filter giving me a URL of example.com/materials/term1/facts.  Since the URL is passing the context to the view,  I should not need to pass arguments through page manager/panels UI.

My result is when I enter the specs/term1 URL, the taxonomy page for that term is shown and the URL is not changed.

The only thing I can guess is that this does not work on aliases. Any ideas on why this fails anyone?

Yes panels will read the path alias. I have discovered two related reasons why this problem might be occurring.

Many of my taxonomy terms are two words long. Panels does not have a provision (views does) to convert the spaces to dashes.  The panel redirection variant is not reacting to the URL because it is looking for an argument that does not have dashes generated by %spec:name.
I tried the same redirect using the panel provided by the system /taxonomy/term/%term and it succeeded in placing the redirect path in the URL, although the redirect did not work.  This is because the term name had two words and was inserted with a space in it.

There are several LEARNING Points for me in this answer:

First, I discovered that the actual Drupal path to nodes and terms are fully interchangeable.  I thought that if a URL was using an alias, I was restricted to working with the alias format. The ability of panels to intercept the Drupal name pattern taxonomy/term/%term out of the alias drove home to me the fact that Drupal sees them as exactly the same.

Second, When this problem arose, I thought too big, too fast.  I suspected a bug in the module or a major misunderstanding of how the selections in the form connect to each other to generate the action of the panel variant.  I have had similar problems using views, which also very a complex module.  The problem turned out to be a minor, easily overlooked error.


Adding a field to users from a module.install file Is it possible to add a custom field to users from a module.install file, as it would be done from admin/config/people/accounts/fields?

It is possible, in the same way forum_enable() adds a new field to the "forum" content type; the only difference is that "entity_type" and "bundle" are both set to "user."

// Create the 'taxonomy_forums' field if it doesn't already exist.
if (!field_info_field('taxonomy_forums')) {
  $field = array(
    'field_name' => 'taxonomy_forums',
    'type' => 'taxonomy_term_reference',
    'settings' => array(
      'allowed_values' => array(
        array(
          'vocabulary' => $vocabulary->machine_name,
          'parent' => 0,
        ),
      ),
    ),
  );
  field_create_field($field);
}

// …

// Create the instance on the bundle.
$instance = array(
  'field_name' => 'taxonomy_forums',
  'entity_type' => 'node',
  'label' => $vocabulary->name,
  'bundle' => 'forum',
  'required' => TRUE,
  'widget' => array(
    'type' => 'options_select',
  ),
  'display' => array(
    'default' => array(
      'type' => 'taxonomy_term_reference_link',
      'weight' => 10,
    ),
    'teaser' => array(
      'type' => 'taxonomy_term_reference_link',
      'weight' => 10,
    ),
  ),
);
field_create_instance($instance);

You can implement a similar code in the hook_enable() implementation of your module, or in the hook_install() implementation; in the first case, you should check if the field doesn't already exists, or field_create_instance() raises an exception.

To verify the field doesn't already exist, you can use code similar to the following one, where $instance is the same array as used in the previous code:

$prior_instance = field_read_instance($instance['entity_type'], $instance['field_name'], $instance['bundle']);
if (empty($prior_instance)) {
  field_create_instance($instance);
}


Display Profile2 fields in another view How can I display Profile2 fields in a view that has a content type as filter?

Later edit(example):

I have a view which displays a content-type X. I have a profile Y with different fields. I would like to be able to add fields from profile Y to the view which already has fields from content-type X.

First you need to add User relationship, “Content: Author” for example.
After that you will be able to add new relationship “User: Profile” on base of User relationship.

Now you can add fields from user and user profile. You must not forget that SQL query becomes heavier with each new relationship.


drupal_render in hook_form_alter prevents javascript from being included in the header I'm calling drupal_render to render a textarea element in another element's #prefix field in hook_form_customtype_node_form_alter().  When I load the form, most of the script tags in the header do not get printed.  If I comment out the line with drupal_render they print out and the accordions and sliders load on the page.

Why would calling drupal_render prevent some of the javascript files from being included in the page header?

UPDATE

Here's my code:

$deltas = preg_grep('/^[0-9]*$/',     array_keys($form['field_recommendation_reference'][LANGUAGE_NONE]));
foreach ($deltas as $delta) {
  if ($form['field_recommendation_reference'][LANGUAGE_NONE][$delta]['field_key']['#default_value']['finding_wrapper'] == $wrapper_field_name) {
    $wrapper = $form[$wrapper_field_name];
    $wrapper['#printed'] = FALSE;
    $wrapper['#value'] = 'test';
    //$form[$field]['#suffix'] = drupal_render($wrapper);
    dpm(drupal_render($wrapper));
  }
}

When I output the element with dpm, the form loads all of the javascript.  Also, when I include the markup without using drupal_render, the page loads correctly.

If I included the rendered markup manually the form doesn't load all of the javascript.  Could it be a conflict with id's being used already?  I have the same element stored in the $form array but with #printed set to TRUE.

Found the Issue

if I set #autocomplete_path = '', the form element's markup does not disrupt the rest of the page.  Is it possible to get autocomplete to work with drupal render?  I saw some comments related to this on the drupal_render api documentation

Setting the #id to $wrapper['#id'] = drupal_html_id('edit-' . str_replace('_', '-', $wrapper_field_name));  resolved the issue.  theme_textarea was unable to get a value for $element['#id'].

edit

I still had trouble getting the #ajax elements to be processed even after adding a call to ajax_pre_render_element.

I restructured my alter hook so that it prints the textarea inside the form element that I'm trying to append to. that way it prints both fields one after the other.  This way, I'm not touching drupal_render and everything works.


I'm on drush version 6 & can't do a drush status on my drupal8 site, whats the story? drush status says I'm on drush version 6  How can I get drush to work with Drupal8 ?  Do I have to grab a later version of drush directly from github?  Any directions for this?  Thanks.

This is the error message I'm getting when trying to run drush against my drupal8 install:

Drush 6.0 does not support Drupal . See http://drupal.org/project/drush for more     [error]
information.

This is a known bug in Drush 6.0.0 that was caused when Drupal 8 changed the way that the Drupal VERSION constant was defined.  This has been fixed in the master branch on GitHub; currently, the only way to use Drush with Drupal 8 is to clone the master branch directly.  There should be a 6.1.0 release out shortly to address this.

For more information, see:

https://github.com/drush-ops/drush/issues/63

UPDATE:  I mis-spoke above.  Drush 6.x supported Drupal 8 until the recent release of Drush 6.0.0.  Now, only the master branch (Drush 7) supports Drupal 8. So, there is no way to get Drush 6 to work with Drupal 8; you must use the master branch.  When 6.1.0 comes out, Drush will correctly tell you that Drush 6.1.0 does not support Drupal 8.


Can I remove Zen Default Regions if Im not using them I want to remove regions such as 'navigation' & 'highlighted' from structure/blocks just so I can visually see what is in use, and not have a list of Blocks im not using sitting there.

You cannot remove regions that have blocks in them - at least not without consequences. If you will do so, blocks will disappear and there is a chance for Drupal and PHP errors. To get rid of unneeded regions, you need to proceed in that order:

Remove all blocks from them
Remove them from .tpl files, to be sure nothing will try to render region that does not exist anymore
Now you can delete them from .info file


grouping nodes with collapsible fieldset I use entityreference to link nodes to other nodes and field_group to display collapsible fieldsets with fields.

Assume I have node#1 which has a field related_nodes containing node#2, node#3 and node#4.

The display of this node looks like this:

node title

node body

related:
- node#2
- node#3
- node#4

I can use hook_node_view to remove nodes from the related_nodes field on the fly using something like:

unset($node->content['field_info_case_law_references']['#items'][?]);

I want to remove all those nodes (e.g based on their title) and place them in groups, each in a collapsible fieldset within that related: field. so it ends up looking something like this:

node title

node body

related:
+ starting with A (collapsible fieldset)
  - node#2
+ starting with B (collapsible fieldset)
  - node#3
  - node#4

The default collapsible behaviour, html and styling of that I can configure from admin/structure/types/manage/*/display is good enough.

Where should I look at?

OK I found it.

In the HOOK_node_view I can do:

if ($node->type=='CONTENT_TYPE') {

  // clone from a fieldset nearby
  $node->content['#fieldgroups']['group_FOO']=clone $node->content['#fieldgroups']['group_ORIG'];

  // modify fieldset
  $node->content['#fieldgroups']['group_FOO']->label="xxxxxxxxxxxxxxxxxxxxxxxx";
  $node->content['#fieldgroups']['group_FOO']->weight=-1;
  $node->content['#fieldgroups']['group_FOO']->identifier=...
  $node->content['#fieldgroups']['group_FOO']->group_name=...

  // clone from a field nearby
  $node->content['field_FOO'] = $node->content['field_ORIG'];

  // modify field
  unset($node->content['field_FOO']['#items'][0]);
  unset($node->content['field_FOO']['#items'][1]);
  unset($node->content['field_FOO']['#items'][2]);

  // position fieldset and field
  $node->content['#group_children']['group_FOO'] = 'group_ORIG';
  $node->content['#group_children']['field_FOO'] = 'group_FOO';

}


Reload Ajax from the js code I am having trouble reloading a page through Ajax from custom JS. There is a form which will change with your choices and this changes are made by Ajax.

How I can change the select list "Leistung" from the code so the price would be updated by Ajax?

As you all know I can't simply write $("select").click(); it doesn't work. Also I tried .trigger() and .mousedown(), actually .mousedown() would work if I use it for the submit button but I wanna change select list value and nothing works there.

What I think is I have two options: I could simulate a REAL click on the select list (which I know I can't), and the other way is to somehow tell the Ajax to reload after changing the select list value.

To be more clear:
That select list is the target that I wanna change. I mean if I click on the third row of the table, that click function should change the value of the select list and here is the problem! the Ajax won't reload the price!

The event you're looking to trigger is the onchange event. JQuery's val() does not trigger onchange automatically. You can either call change() or trigger the change event

$('selector').trigger("change");.

See Also: https://stackoverflow.com/questions/3179385/val-doesnt-trigger-change-in-jquery


Which should I use and when: node_load() or entity_load()? Title says it all.

I understand that entity_load provides a performant and efficient means to load multiple nodes whilst reducing database queries, so I presume in that instance I should be using entity_load(). But when I just want one node, which should I use? And will node_load() be deprecated in d8 in favour of the more generic entity_load() api?

I guess the same question goes for the familiar user_load() too.

node_load is just a fancy wrapper for entity_load.

That is node_load calls node_load_multiple which is a wrapper for entity_load. This means that performance wise there isn't really much of a difference, which function you use, unless you have to load a lot of nodes.

node_load has many advantages over entity_load

It's simpler
It increases code readability
it returns the node object instead of an array with the node object(s)

So in all, node_load is a convenience that you always should use whenever possible, then resort to node_load_multiple for cases where you need to load many more nodes.

entity_load should be used for loading entities when you don't know the type, or have it stored in a variable, in which case you can do

entity_load($type, ...);


Is there a way to get Views Bulk Operation to place field options in the main VBO exposed dropdown I am using VBO to set the author for a one of my content types.  Currently, when you want to use the change author page, you have to..

Navigate to the page.
Select the target content items
Select 'Change Author' from the VBO drop down list (this is the only option)
Wait for the new page to load
Select the new author form the (only) drop down lost on this page.
Submit

It seems that there are a lot of extra steps here.  Is there a way to set-up the primary VBO drop down list (refereed to in step 3) so that it displays the different authors (like the drop down refereed to in step 5?)

If you check the "Skip confirmation step" box below the "Change the author of content" action, you can remove the confirmation step.

As for making it a one-click change, that would probably require either extending VBO with another module, or somehow invoking ctools modal windows with VBO. I haven't found any success stories with the latter, but there's this: Ctools Modal + Views Bulk Operations? (drupal.org)


How do I access node body from template.php? Here is my code so far:

if (!empty($page['content']['system_main']['nodes']) && is_array($page['content']['system_main']['nodes'])) {
    foreach ($page['content']['system_main']['nodes'] as $nid => &$content) {

        // Blog
        if ($content['#node']->type == 'blog') {
            $description = ???;
        }

    }
}

I can't figure out how to access the node's unformatted body field, I can't believe it's so difficult to achieve such a simple task..

It all depends where exactly you want to access it from.

For example in template_preprocess_node() you have full node object in $variables['node'], including body field ($variables['node']->body).


Best practice for third-party PHP class-based library I am currently working on a module that requires a third-party PHP library, which is essentially a single PHP class.  Normally, I would place it in an includes/ subdirectory and add

files[] = includes/Foo.php

to my .info file and let the Drupal 7 class auto loader do its thing when I do a  $foo = new Foo().

I have permission, though, to release this module to the public and would rather not include the library with the module.  I am well aware about the complications regarding licensing, but for the sake of this question, I would like to ignore it.

There is a similar question, How do I include a PHP library?, but I don't really think this answers my dilema.

This answers to this question essentially say to use the Libraries API, but every single module that I have found that uses this just does alibraries_get_path() to get the basepath (and includes fallback path when it isn't available) and then does a require or include with some error checking (or not).  All do something like:

if (!class_exists('Foo')) {
  $path = function_exists('libraries_get_path') ?
    libraries_get_path('foo') : 'sites/all/libraries/foo';
  if (!include($path . '/Foo.php')) {
      // handle this error
  }
}

In this case, the Libraries API isn't really doing anything.  I don't see the advantage to using this, over the old method of asking users to download a copy and place it in the module folder itself.  And, there is still the issue that the module developer still needs to manually do the load with include/require.  For example, the Facebook module just loads the library in a hook_init and the HTML Purifier module has an internal function to check-and-load every time the library is needed.

This may be a widespread practice, but it doesn't seem like a best practice.

Should my module take the initiative and declare a hook_libraries_info so I can use libraries_load('foo')?  This, too, seems odd.

Branch 2.x of the Libraries API module allows developers to define, through hook_libraries_info(), or a .info file for the library, the following information (see libraries.api):

The dependencies of the library
The version with which the library is compatible, for each of the dependencies
The list of the files that needs to be loaded (CSS, JavaScript, or PHP files)

The list of files that needs to be loaded is used to load those files, when the library is required. This means that your module doesn't need to load CSS, and JavaScript files with drupal_add_css(), or drupal_add_js(), as that is already done from the Libraries API module. Loading the dependencies is a task done from the Libraries API module, without the calling module doing anything.

All the module does is using the following code, for loading a library. (See Using Libraries API 2.x (as module-developer).)

// Try to load the library and check if that worked.
if (($library = libraries_load($name)) && !empty($library['loaded'])) {
  // Do something with the library here.
}

If you just need to detect if a library is present, the module should use code similar to the following one.

if (($library = libraries_detect($name)) && !empty($library['installed'])) {
  // The library is installed.
}
else {
  $error = $library['error'];
  $error_message = $library['error message'];
}

Between the properties hook_libraries_info() can return, there is also 'download url', which is not actually used, not even in the branch 3.x. Probably it will be used in future, or a third-party modules could hook into the Libraries API module, and download the libraries that are requested, but missing.


Add a class to a div depending on which term was clicked Since clicking on a taxonomy term opens a page showing all pages using that term, how do I identify which term was clicked so I can add a unique icon to each one? What do I type in template.php so I can add it to my page.tpl.php like so: class="<?php if(this-term-was-clicked) : ?> add-this-class <?php endif; ?>"

I have 3 terms right now and would like to customize the display of each one by adding a unique icon before the title.

The taxonomy term that is click will already have the class "active" applied to it.

The selector .field-type-taxonomy-term-reference a.active is the one you are probably looking for.


view and Content:user issue while customizing front page i can not find 'Content: User' to add author name field in views. but i can find something like Content: Author uid how to show author name in front page?
another question i cant add new fields while selecting grid view, how to fix it too.

If you are using the Unformatted list format used by default from the front page view, you would see the author of the node. This happens if you selected Display author and date information on the settings page for the content type (admin/structure/types/manage/[content type]).

Supposing that you change the format to, for example, Table (which allows you to add fields), when you add the new fields you will notice that Content: Author uid field has the following description:

  The user authoring the content. If you need more fields than the uid add the content: author relationship.

So, you just add a relationship.

Once you do that, you will find the author name between the fields you can add.

As for the Grid format, it doesn't uses fields; that is why you cannot select them.


How do I create a contant managed list of linked images and display it as a block? On the homepage of the site I'm making I need to have a few CTAs (calls to action) linking to products in the shop, which is running Drupal Commerce. The CTAs comprise of:

An image
A link title
A URL to a product display node
A limit of 2 CTAs

Is there any way I can do this using Views 3 (I'm guessing that would be the best way, please correct me otherwise) without writing my own module? I only have  a very basic understanding of writing modules.

I would go down the views route as it will be the simplest. Just set the filters to only return products that have images and limit the view to output 2 items max. You could add an extra field onto the product content type that you then check for in views to allow the admin to control which products get sent to this block.


File upload through form type file My Drupal version is 8.6.10

I am trying to upload a file through the file_save_upload function and the function is looking for the file in

Symfony\Component\HttpFoundation\FileBag Object

$all_files = \Drupal::request()->files;
debug($all_files);

Symfony\Component\HttpFoundation\FileBag Object
(
    [parameters:protected] => Array
        (
        )

)

But my file is in

Symfony\Component\HttpFoundation\ParameterBag Object.

$all_files = \Drupal::request()->request;
debug($all_files);

Symfony\Component\HttpFoundation\ParameterBag Object
(
    [parameters:protected] => Array
        (
            [name] =>
            [type] => 4
            [files] => Array
                (
                    [image_section] => logo_capnord.png
                )

            [op] => Ajouter
            [form_build_id] => form-wMTrCGaN5mPlOOv8bqS7UsJ0lRiSN6QQp9UviA0cTIA
            [form_token] => 1hTMXJRfoQvFV9Lqq3TuJ29eYC6L-zt3U7Bow1P8yJ0
            [form_id] => capnord_section_form_list
        )

)

The field is generated through the reloading of the form in ajax.

  $form["base"]["fields"] += [
    "image_section" => [
      "#type" => "file",
      "#title" => "Image",
    ]
  ];

Solution

$form["#attributes"] = ["enctype" => "multipart/form-data"];

$form["base"]["fields"] += [
   "image_section" => [
    "#type" => "file",
    "#title" => "Image",
   ]
];

I solved my problem, as I only reloaded one part of the form, the form generator did not know that there was a file element, so it did not add "multipart enctype / form-data" to the form.

I hope this will help someone in the same situation as me in the future.


How to alter a function in a contributed module? I am using a module Simple hierarchical select in my website.

I have a taxonomy in which I have some parent terms and there children terms, I am getting two select list with this module. In one select list I am getting all parent terms, and the module is filtering the second select list as per the parent selected, showing children terms of parent term selected in select list 1.

I need to add some condition to the values I am getting in the select lists to alter this function shs_json_term_get_children using custom module.

The function declaration in the module is:

  function shs_json_term_get_children($vid, $parent = array(), $settings
  = array()) {}

So I tried using:

  function hook_shs_json_term_get_children_alter($vid, $parent =
  array(), $settings = array()) {}

and

  function hook_shs_json_term_get_children_alter(&$vid, $parent =
  array(), $settings = array()) {}

but neither worked.

Any suggestions?

As far as I know, you can only alter the functionality the module exposes using hooks defined by that module, and you cannot alter just any function defined in the module. For instance, shs_json_term_get_children is just a callback, and you cannot alter it.

The SHS module defines several hooks that are listed in the shs.api.php file. For instance, there is a hook called hook_shs_term_get_children_alter, that allows you to modify the list of terms displayed to the user: http://cgit.drupalcode.org/shs/tree/shs.api.php?h=7.x-1.x#n73

/**
 * Alter the list of terms within a level of the term hierarchy.
 *
 * @param array $terms
 *   List of terms displayed to the user (single hierarchy level).
 * @param array $alter_options
 *   - vid: ID of vocabulary or field name
 *   - parent: ID of parent term
 *   - settings: Additional settings (for example "language", etc.,)
 */
function hook_shs_term_get_children_alter(&$terms, &$alter_options) {
}

In your module, you would need to implement that hook like that:

function YOURMODULENAME_shs_term_get_children_alter(&$terms, &$alter_options) {
  // Your code here.
}


Track Simplenews newsletter open per user I send newsletters from my Drupal 7 site, using the Simplenews module.  I'm using this tracking code, but it isn't tracking uniqueness:

<img src="http://www.google-analytics.com/collect?v=1&amp;tid=test-&#10;&#10;1&amp;cid=123445678&amp;t=event&amp;ec=email&amp;ea=open_my_newsletter_june2016&amp;el=recipient_id&amp;cs=newsletter&amp;cm=email&amp;cn=Campaign_Name">

I change the tid according to my Google Analytics account and the ea attribute to the name of my newsletter and the date, but these aren't unique URL's for users.

How can I track unique opens of my newsletter, using Google Analytics?

As you mentioned, you need a unique values for GA tracking pixel. You need to utilize Simplenews's integration with the Token module so you can insert unique values into the URL for each newsletter copy that goes out.

For example, the inserting the token [simplenews-subscriber:user:uid] will let embed the unique user id into each tracking pixel copy.

The tokens will vary depending on the details you need to track, but Token integration should provide almost every detail you need.


drupal 8.2 to 8.5 update error I am getting the following error.

  Recoverable fatal error: Argument 3 passed to
  Drupal\page_manager\Routing\VariantRouteFilter::__construct() must be
  an instance of Symfony\Component\HttpFoundation\RequestStack, none
  given, called in
  /home/ranjith/public_html/core/lib/Drupal/Component/DependencyInjection/Container.php
  on line 266 and defined in
  Drupal\page_manager\Routing\VariantRouteFilter->__construct() (line 64
  of
  sites/all/modules/contrib/page_manager/src/Routing/VariantRouteFilter.php).

What does it mean? How can I fix that error?

What you're seeing is the result of the Drupal service container failing to create a service because its cached definition doesn't match the class anymore: An extra constructor argument was added (in this change), and Drupal is not passing that argument.

This is a typical error that can happen after updating modules. Make sure to completely empty your cache manually. You might be able to do this using drupal cr all or drush cr or by visiting the admin backend, but not if the service is already loaded during bootstrap. In that case, try to empty the cache_container database table directly.


Difference between Minimum cache lifetime and Expiration of cached pages On Drupal Performance Page, under the fieldset Cache you have two options. One is Minimum Cache Lifetime and the other is Expiration of cached pages.

What is the difference between these two.

I have made following observations after spending a few hours. If there are any gaps or mistakes, do let me know. I will be happy to make editions.

First observer that none of the Options under the CACHING are interdependent. If they were you would have seen them under different field sets(or as dependent fields). Make a note of this observation and we will revisit that later.

Let us begin with the first option Cache Pages for anonymous users.

When you check this option you are basically telling Drupal

Hey Beast listen, when an anonymous user visits my site,

Store the generated HTML in the cache table
So that I can display the same result to all users as my pages
remain same for all anonymous users.
And don't clear the page caches until I say clear
all caches.

Also even when you don't enable the Cache Pages for anonymous users  the page can still be cached by external cache systems. Eg : Boost

Now lets move to the next options which you would end up using generally.

Expiration of cached pages

Note that this setting has nothing to do with the Drupal Database or
cache tables.
Read the description The maximum time an external cache can use an
old version of a page. As Molot pointed out the keyword is
external.
So what this option basically does is it sets the header Cache Control to public and the max-age value in the header to the specified value(1 day in this case).
This header tells the external Caching systems not to make a call
to the server for this page until the max age, as they can show this
page from their own cache. After the max-age the Caching system
should check back with the Drupal server to see if the content has
changed.
If its a Varnish server, it doesn't make a call to Apache and
returns the page from its cache. So assume that Varnish has cached a
page and thousand different users made a request to that page. So it
means that 1000 requests have been processed without hitting the
Apache Server even once.

Minimum Cache Life Time

If your site doesn't have a huge traffic or if you are not sure what this value is, it better to leave this value as none.

This value applies not just for the pages. But all the cache objects.
What this value tells is "Its ok to serve cache objects which are stale"
In our case the value is set to 5 mins.
If you have a page that lists the five latest blogs on your home
page. What the above values means is that, if a new blog is created
its ok for the blog not to appear on the listing for the five
minutes.
When this value is set, for the cache to be updated/recreated minimum
this much time must have passed and a cache clearing action must be
run[A cache clearing function should be run].


Help outputting Drupal View JSON data using getJSON function I'm trying to return the view data and display it in a list for verification.

It is sending for the data and seems to receive it (I get a 200), but it is not outputting the data.

Any help much appreciated!

$.ajax({
  url:'views/ajax',
  dataType: 'json',
  data:{
    view_name: 'my view name',
    view_display_id: 'default',
    view_args: 'view argument goes here',
  },
  success: function(data, textStatus, jqXHR){
    if(data[1].data !== undefined){
      // the view results will be in data[1].data
    }
  }
})


how to display array in div structure in drupal 7? How can I render arrays in div structure in drupal?. I am having a select list with ajax callback.Everytime I choose option, it's fields get fetched into an array. Now how can I show that array fields value?

$nodes = array();
    $output = array();
    $i=0;
    $nids = db_select('node', 'n')
      ->fields('n', array('nid'))
      ->condition('type', 'article', '=')
      ->execute()
      ->fetchCol();
    $nodes = node_load_multiple($nids);
     foreach ($nodes as $node => $value) {
      $output[$i]['title'] = $value->title;
      $output[$i]['body'] =$value->body['und']['0']['value'];
      $i++;
    }
    return output;

If I used return theme('item_list', array('items' => $output));, it is not working for me. Please help.

After a research of 20 minutes, I came to this answer.theme('item_list', array('items' => $output)); This function follows a simple array key value structure.It doesn't support multiple idexes. so remove $i from array, and it will work.


Change theme_image_widget in other theme I have a site, where I want to alter the form of the image widget.

I have a admin theme and overlay activated. The Admin theme is set to the default 'seven' theme from the core (V7.14)

Now I want to write

function seven_image_widget($vars){
    $vars['element']['alt']['#title'] = 'Foo';
    return theme_image_widget($vars);
}

If I add this in the template.php of seven theme, it works, if I put it in my custom theme, it does not work.
Can I access this theme hook of seven theme from my theme in any way?  I don't want to change the core themes code.

I found it myself.
If made a subtheme of seven (named sevensub) with just this special function in template.php

function sevensub_image_widget($vars){
    $vars['element']['alt']['#title'] = 'Foo';
    return theme_image_widget($vars);
}


Is it possible to host private files on remote file server in Drupal 8? I want to know, In drupal 8, is there any way to host all private files on remote file server separated from host server.
Files must be uploaded or removed from remote server directly from Drupal site.
Is it possible?

Yes, the private file system is just another folder on your server, configured in settings.php
For example, you could

Mount a separate storage volume there via NFS
Add another EBS volume (if AWS)


HybridAuth registration I am using HybridAuth as my login module and I want that user have to register with email and password. How can I do that ?

In the current process, user gets mail only and then sets the password instead of doing it on the registration form.

Thanks for the help

User Registration Password Module will do the job for you;)

  By default, users can create accounts directly on the registration form, set their password and be immediately logged in, or they can create their account, wait for a verification e-mail, and then create their password. With this module, users are able to create their account along with their password and simply activate their account when receiving the verification email.


Enable filter format per field? Is there a simple way in Drupal 8 to set a filter format on a field and not show other format options that are accessible by the role of the current user?

I want to have a field with a very stripped down editor and default to that format, but I also do not want to show the formatting options on this field. I already tried the Simplify module, not quite what I am looking for.

EDIT: Sure, you can form alter... just wondering if someone solved it in a more modular way for 8.2.x.

The Better Formats module provides this type of functionality.

See Better Formats Module.

  Better formats is a module to add more flexibility to Drupal's core
  input format system.
  Features
  Set allowed text formats per field. Set default order of text
  formats per field. Hide format tips per role. Hide more format
  tips link per role. Hide format selection per role per entity.


How do I add description and keyword to the front page? I would like to know how to set description and meta keywords for the front page. I use the Meta tags module for articles, but it is not working for the front page.

I use Panel as my front page.

My website is http://www.techiestuffs.com, and runs on Drupal 7.

if you see the HTML source of the front page, it only contains the following HTML:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link rel="shortcut icon" href="http://www.techiestuffs.com/sites/default/files/favicon.png" type="image/png"/>
<meta name="Generator" content="Drupal 7 (http://drupal.org)"/>
<title>TechieStuffs | Stuffs for Geeks</title>

I had tried adding these functions in template.php:

function yourtheme_page_alter($page) {
  $meta_description = array(
    '#type' => 'html_tag',
    '#tag' => 'meta',
    '#attributes' => array(
    'name' => 'description',
    'content' =>  'Description about the site'
  ));

  $meta_keywords = array(
    '#type' => 'html_tag',
    '#tag' => 'meta',
    '#attributes' => array(
    'name' => 'keywords',
    'content' =>  'Some Keywords about the site'
  ));

  drupal_add_html_head($meta_description, 'meta_description');
  drupal_add_html_head($meta_keywords, 'meta_keywords');
}

But this function does not seems to work as you can see in my websites source code.

Does anyone know how to work out this?

In drupal 6 I used Nodewords which allowed you to set meta tags on the front page as a configuration. In D7 this has been replaced by Meta Tags which may do the same thing or you.


I am trying to create user registration form in js which beautiful and flexible I am using drupal 7. I am trying to create user registration form with javascript which beautiful and flexible. Something like this:

How can I achieve this?

You can do it by using these modules :

Fancy Login

  Fancy Login adds javascript based, lightbox-style login functionality
  to your site. When the user clicks on any link that links to
  /user/login, they screen dims and a login box is created in the center
  of the screen.

Better Login

  Styling Drupal login/password/registration forms are a mission most of
  the time because they form part of the theme... This module removes
  that issue, it is slightly inspired by the way Wordpress login forms
  work, and uses three page templates to change the style of the forms.
  It is very simple to use, just install the Better Login module and it
  starts working immediately.

Model Form

  Modal forms make use of the modal feature in the ctools module to open
  some common forms in a modal window.


Cannot use object of type stdClass as array I'm very new to Drupal and I'm receiving the error:

Cannot use object of type stdClass as array

in the following code:

$toolbar = $page['toolbar'];
foreach( $toolbar['menu_menu-smart-resources'] as $id => $object ) {
  $toolbar['menu_menu-smart-resources'][$id]['#localized_options']['attributes']['data-role'] = 'foo';
}
print render($page['toolbar']);

Can someone help.

You are able to change menu attributes using Menu Attributes module . If any customization is needed on top of that then you can follow the below process.

You can able to override theme links using theme_menu_link in template.php. Follow below step to override.

Go to your active theme folder might be in sites/all/theme or if you are using default theme then themes folder
Go to the active theme folder
Look for template.php
Override theme_menu_link by copy pasting entire function and replacing theme with your theme name.
Do your changes inside function wherever necessary!


Improving Site Speed and Cache for Authenticated Users I am building an intranet site. I have the site set up with single sign on via the server authentication module meaning there are no anonymous users. This means large parts of the cache are worthless.

The site is now set up how I want, however it's running extremely slowly for the first couple of page loads if the site hasn't been visited in a couple of hours. The speed picks backup once you've looked at a couple of pages.

We now have cron set up running every two hours with a scheduled task, so I now know cron isn't slowing the site down. I have the Devel module enabled, and some of the queries are clearly slowing things down and a lot of these seem to be cache related.

Below are all of the queries ran that took over 100ms when I visited the site's home page first thing this morning. (Speed in ms followed by task)

421.91 system_list
890.69 DrupalDatabaseCache::set
171.89 DrupalDatabaseCache::getMultiple
125.01 DrupalDatabaseCache::getMultiple
125.01 PagerDefault::execute
125.01 DrupalDatabaseCache::getMultiple
109.38 comment_num_new
390.65 DrupalDatabaseCache::getMultiple
140.64 ctools_export_load_object
187.51 DrupalDatabaseCache::set
328.15 DrupalDatabaseCache::getMultiple
421.91 admin_menu_tree_dynamic
390.65 admin_menu_tree_dynamic
1000.07 DrupalDatabaseCache::getMultiple
421.91 DrupalDatabaseCache::getMultiple
578.17 DrupalDatabaseCache::set
281.27 menu_get_item
343.77 statistics_exit
140.64 _drupal_session_write

Clearly there's enough here to slow the site down. However truth be told I don't have much of a clue how to a) decode what all the above really mean and b) what to do about any of it.

I would be grateful for any advice or pointing in the right direction anyone can give me.

I created a presentation that covers some of the basics of of performance https://docs.google.com/presentation/d/1AgnurTWsWdMAFjfFmSU7mk2zfJu8jG_KmVdZ7-o6Pok/edit#slide=id. In your case I would make sure poormans cron in core is disabled, use an IP for your database connection (very important on IIS), make sure you have some sort of op code caching enabled, and follow this guide (linked in the presentation under Basic database tuning) to fix database issues at the drupal level, and be sure to adjust some MySQL defaults as well.


How can I only show the first image of an image field in the teaser? I have a content type with an image field that can contain an unlimited number of images. The field is used to display an image gallery in the full node view, but I also want to use the first image of the field in the teaser.

I vaguely remember doing something like this years ago in Drupal 6, but now I can't find any option to do this in Drupal 8. I'm not sure if I'm misremembering, or just looking in the wrong place.

How can I display only the first image of an image field in the teaser?

Create a custom image formatter by copying the default ImageFormatter.php from the image module into a new custom module, rename everything properly and then add only one simple break; at the last line of the foreach in viewElements(). Choose that formatter under display settings for your teaser view mode of your content type. Works in views, too.

Done that for you in a quick custom module: image_first_formatter.


Percentage save issue on form submit I am working in drupal8.I have created five forms all belonging to a single content type.i have around 50 fields in this content type.I have ten fields in a single form.This form has to be filled by the applicant.For each form we have given 20% completion.If i fill one form i shld get 20% completed.If i fill next from i shld get 40% completed and so on.I have created my form and basic crud operations are done.i dont know how to give this percentage of completion.Plz can anyone suggest how this completion percentage has to be done.

The reason your current code isn't working is because your submit handler doesn't follow the correct naming convention (i.e. FORM_FUNCTION_NAME_submit) and you don't explicitly attach the submit handler to the form anywhere so it's not being run.

You can solve this by simply changing the nameof your submit handler:

function example_form_form1_submit($form, $form_state){

Or you could look at system_settings_form() which automates much of this process for you.


How to hide the (-) sign from facet filter block? I am displaying faceted blocks and current search block on the search page.

When I select a filter from any faceted block, it appears in the current search block and also in that faceted block with this sign (-).

When I click on this sign it removes the filter from the search.

It is fine in current search block. But It should not appear in the faceted block.

Suppose If I select category1 from the facet block. In the current search block and in its facet block it appears like this (-) category1.

And I want that in the current search block it should appear like (-) category1 and in its facet block it should on display its name like category1 without the (-) sign.

Any one who know how to hide this in the facet block?

There are a couple of theme functions you can use to work with the display of these filters.

theme_facetapi_deactivate_widget($variables)

theme_facetapi_link_active($variables)

In your case, you could place the following in your theme's template.php file to edit the display of the deactivation 'button' of your facet:

function THEME_facetapi_deactivate_widget($variables) {
  return '';
}


Is it OK to programatically access fields defined through the UI? This is a question about "best practise". I've taken over a project which I'm working on right now, and the custom modules this project comes with all access fields defined through the UI. In other words, the field names are "hard coded" in code - even though the fields are not defined in code. Is this alright?

I'm thinking that the code depends on data (in fields) which it has no guarantee will be there. Anyone could delete the fields at any time.

If you need to access fields from code, how do you make sure that the fields exist? Do you make sure that the modules define the field (programatically)?

I usually use the entity_metadata_wrapper() function to create a wrapper, and deal with fields through that. But if the field doesn't exist, you can get some not-very-helpful wrapper errors.

To see if a field exists, you don't need a wrapper. You can use:

if ($node->my_field) {
...
}

You can create content types in code, but nothing (except common sense) is stopping a rogue user from deleting fields after they are created. So if you are really worried about fields disappearing, you should check that they exist before using them, as above.


How to show "Add to compare" button in views using "dynamic properties" module in d7? I need to list the products to compare using views. I have used "Dynamic Properties" module to compare the products.

On each product node I can see a "Add to compare" button. But how to show this button in views?

I've referred this demo site
http://p.worldempire.ch/products

It will not support by views at the moment, see the Issues for Dynamic properties.

Check this also http://drupal.org/node/1852656


How to override node_search_execute() to implement partial matching search? I would like to override node_search_execute, so the search query will find partial match of a word instead of full word match i.e coffee, I would like partial match coff should return coffee result.

How can I override node_search_execute() to implement partial matching search?

hook_search_execute() is a hook that modules integrating with the Search module implement to execute the search. As such, hook_search_execute() is invoked only for those modules that have a tab in the search page, not for every modules implementing it. Since the Search module doesn't use hook_search_execute_alter() there isn't a quick method to totally override node_search_execute().

There are some way to make Drupal call another function instead of node_search_execute(), but those involve writing code. The quicker is probably altering the search/node menu to change the page callback, which normally is
search_view().

foreach (search_get_info() as $module => $search_info) {
  $path = 'search/' . $search_info['path'];
  $items[$path] = array(
    'title' => $search_info['title'],
    'page callback' => 'search_view',
    'page arguments' => array($module, ''),
    'access callback' => '_search_menu_access',
    'access arguments' => array($module),
    'type' => MENU_LOCAL_TASK,
    'file' => 'search.pages.inc',
    'weight' => $module == $default_info['module'] ? -10 : 0,
  );
  $items["$path/%menu_tail"] = array(
    'title' => $search_info['title'],
    'load arguments' => array('%map', '%index'),
    'page callback' => 'search_view',
    'page arguments' => array($module, 2),
    'access callback' => '_search_menu_access',
    'access arguments' => array($module),
    // The default local task points to its parent, but this item points to
    // where it should so it should not be changed.
    'type' => MENU_LOCAL_TASK,
    'file' => 'search.pages.inc',
    'weight' => 0,
    // These tabs are not subtabs.
    'tab_root' => 'search/' . $default_info['path'] . '/%',
    // These tabs need to display at the same level.
    'tab_parent' => 'search/' . $default_info['path'],
  );
}

Since the goal you are trying to achieve is allowing searching by partial matching, you just need to install one of the modules that allows this, such as:

The Porter-Stemmer module
The Fuzzy Search module
The Apache Solr Search Integration module

The first module is the lighter one, since it doesn't depend from other modules, while the second one requires the Search API module, which in turn requires the Entity API module; the third one integrates with Apache Solr, and it is just a possibility for you if you have a server running Apache Solr. The Search API module also integrates with Apache Solr.

Reference

Drupal 7: Partial word search


Sync free tagging vocabulary I've a content type article, where user can create new terms to a vocabulary through free-tagging for example content, color and so on . When the user creates a new content, he can add new terms to the categories. Now I'd like to provide the new created terms also to be available in my forum vocabulary, so user can discuss about this terms in the forum.
I've assigned the vocabulary to my article and to my forum. But that alone does not work the way, I'd like to.
In the meanwhile I'm using the Taxonomy Manager for just copying the terms from the 'article' vocabulary to the 'forum' vocabulary.
But that's not the best solution for me, cause I've to manually do this for every added term.
It would be great, if this could happened 'on the fly', some kind of automatically.
Can anybody please help me to get this working?
Please also let me know, if the problem is not getting clear to you.
Thanx for your suggestions.

Assign the same vocab to both content types.
Install the Tagging module
Now the fields should have auto suggest for the fields, as the user types


Remove "Generator" meta tag? How can I remove the Generator meta-tag in Drupal 8?
<meta name="Generator" content="Drupal 8 (https://www.drupal.org)" />

Can this be done with few lines of code?

Basing on the patch provided in Remove Generator META tag & X-Generator for Drupal 8 version! this is the code that would achieve that.
/**
 * Implements hook_page_attachments_alter().
 */
function HOOK_page_attachments_alter(array &$attachments) {
  foreach ($attachments['#attached']['html_head'] as $key => $attachment) {
    if ($attachment[1] == 'system_meta_generator') {
      unset($attachments['#attached']['html_head'][$key]);
    }
  }
}


Theming book navigation block to generate drop-down menus I have a 3 level deep book navigation block. I'd like to change the menu tree HTML output in the following way: For each level of the tree, create a li and inside it put an anchor tag with the active-trail link for that level, and afterwards a ul with the rest of the siblings for that level.

    Level[x] active trail link

Level[x] sibling1

Level[x] sibling2

Level[x] sibling3

Level[x] sibling4

The order of sibling links appearance should be according to their corresponding node weight.

I thought this could be done via the theme_menu_link() function but I can't seem to find a way to pass the current item's depth to the function.

What function do I have to work with in order to achieve what I'm after? Can someone offer some guidance?

Thanks,
Avner

There is a specific theme function, which is used from the Book module for outputting its own block of links to book pages. I am not sure if it suits your case, but you can always use that code to build your own theme function.

The theme function is called from book_block(), using the following code:

  if (variable_get('book_block_mode', 'all pages') == 'all pages') {
    $block['subject'] = t('Book navigation');
    $book_menus = array();
    $pseudo_tree = array(0 => array('below' => FALSE));
    foreach (book_get_books() as $book_id => $book) {
      if ($book['bid'] == $current_bid) {
        // If the current page is a node associated with a book, the menu
        // needs to be retrieved.
        $book_menus[$book_id] = menu_tree_output(menu_tree_all_data($node->book['menu_name'], $node->book));
      }
      else {
        // Since we know we will only display a link to the top node, there
        // is no reason to run an additional menu tree query for each book.
        $book['in_active_trail'] = FALSE;
        $pseudo_tree[0]['link'] = $book;
        $book_menus[$book_id] = menu_tree_output($pseudo_tree);
      }
    }
    $block['content'] = theme('book_all_books_block', $book_menus);
  }

The theme_book_all_books_block() function is empty, because the theme is using a template (book-all-books-block.tpl.php); as far as I can see, there isn't a preprocess function for that template file.


drupal_validate_form not validating more than one time on listing page i am using drupal_validate_form on a node listing page .
it is validating it correctly only for 1st item after that it is not checking validation.

here is my code

     foreach($result as $r){
        $node_form = (object) array(
          'uid' => $user->uid,
          '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'));

        $old_fs = @unserialize($r->form_state);
        $old_fs['values']['uid'] = $user->uid;
        $node = (object) array(
          'uid' => $user->uid,
          'type' => 'MY_CONTENT_TYPE',
          'language' => LANGUAGE_NONE,
        );
        node_object_prepare($node);
        $form_state = array();
        $form_state['build_info']['args'] = array($node);
        $form_state['values'] = $old_fs['values'];
        $form_state['values']['op'] = t('Save');
        $form_state['submitted'] = 1;
        $form_state['complete form'] = array();
        $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);
        }
        form_clear_error();
    }

thank You in advance

i just change the validated flag of every form in the foreach and after that it works fine


Composer won't update Drupal Core, can't determine what is stopping it I am trying to update Drupal Core 8.6.3 to 8.6.5 (which is the latest Core update at time of writing this).

Using this CLI Composer command:

composer update drupal/core --with-dependencies

completes the whole process without errors.

But after clearing Drupal's cache and checking Status Report, it still shows the previous version (8.6.3).

I'm assuming a dependency may be blocking the Core update.

To test this I ran this CLI Composer command:

composer prohibits

and received this error:

[Symfony\Component\Console\Exception\RuntimeException]
  Not enough arguments (missing: "package").

After searching a few forums I could not find a definite explanation of that error's meaning or how to address it.

UPDATE - As per my answer below, I found a solution which was:

I noticed in a few threads that this inclusion kept being referred to as a potential Core update issue:

webflo/drupal-core-require-dev

So I checked my composer.json require list and it was there, specifying the earlier Core version:

    "require-dev": {
    "webflo/drupal-core-require-dev": "8.6.3"
},

To correct this, I ran this CLI Composer Command:

composer update drupal/core webflo/drupal-core-require-dev --with-dependencies

After clearing cache (drush cr) I checked back on my composer.json and the require had changed to:

    "require-dev": {
    "webflo/drupal-core-require-dev": "^8.6.0"
},

This then triggered a Status Report Warning that 2 Tables required update.
To fix this I ran this CLI Command:

drush updatedb

I then successfully run this CLI Composer command:

composer update drupal/core --with-dependencies

After another cache clear, I checked Drupal's Status Report which showed the update to Core had worked.
I was happy with this so (as I was in maintanenace mode during this time) I then used this CLI command to turn off maintenance mode:

drush sset system.maintenance_mode 0

And all is well and working correctly.

I found some other threads that highlighted webflo/drupal-core-require-dev as being an issue,
In CLI I ran

composer show

This showed me that webflo/drupal-core-require-dev was set to 8.6.3

So I ran update in CLI:

composer update drupal/core webflo/drupal-core-require-dev --with-dependencies

This updated the require version to 8.6.5.
Upon checking Drupal Status Report it also triggered a warning requiring Database updates, so I ran:

drush updatedb

and approved"yes" to the 2 updates.

This removed the Database error from Status Report and I then ran the core update CLI again:

composer update drupal/core --with-dependencies

This time it worked, so I cleared cache and turned off maintenance mode:

drush cr
drush sset system.maintenance_mode 0

and the Status Report is now clear of errors and warnings.


How to Pass a Variable to Commerce Order Twig Template I have located commerce-order-receipt.html.twig in commerce/order/templates/ and I have copied it to my theme directory, properly overriding it. My basic changes all work.

Now I am trying to figure out how to pass my own variable to it. I can't figured out which hook_preprocess function I need to use in order to do this. I have figured out how the suggestion and original variables were made in commerce_order.module but this has not helped me hook into it and add more variables.

Can someone point me in the right direction?

I think this should work, in THEME_NAME.theme add

function THEME_NAME_preprocess_commerce_order_receipt(&$variables) {
  $variables['test'] = "test";
}

Note: replace THEME_NAME with actual name of theme

Then doing {{ test }} should output "test".

Note: remember to flush all cache to see changes.


Module enhancement file Hi guys (and gals) I'm trying to create a simple enhancement to one of my modules .inc files and am messing something up somewhere, and was hoping someone with sharp eyes can point it out. Even though it is extremely easy to just insert one line into the contrib file, do to our companies "best practices" I need to add this in another way.

I am trying add one extra variable into the $services array of the gigya_get_networks function, the function in gigya.inc is

function gigya_get_networks() {
  $services = array(
    'facebook' => 'Facebook',
    'myspace' => 'MySpace',
    'twitter' => 'Twitter',
    'google' => 'Google',
    'yahoo' => 'Yahoo',
    'aol' => 'AOL',
    'blogger' => 'blogger',
    'wordpress' => 'WordPress',
    'typepad' => 'typepad',
    'liveJournal' => 'liveJournal',
    'hyves' =>  'hyves' ,
    'veriSign' => 'veriSign',
    'linkedin' =>  'LinkedIn',
    'liveid' => 'Windows Live ID',
    'openid' => 'OpenID',
    'orkut' => 'Orkut',
  );
  return $services;
}

I created a new module in /custom/utilities/gigya_enhancements with the following

gigya_enhancements.info

name = Gigya Enhancements
description = Provides Gigya enhancements.
package = Gigya
php = 5.2

files[] = gigya_enhancements.module

dependencies[] = gigya

version = 7.x-3.1
core = 7.x

and a gigya_enhancements.module with the following

<?php
/**
 * Implements hook_get_networks().
 */
function gigyas_enhancements_get_networks() {

  // Add Vkontakte to existing services.
  $services = array(
    'vkontakte' => 'VKontakte',
  );

    // shortcode: return $services['vkontakte'] = 'VKontakte';

  return $services;
}

But I'm not returning my additional array parameter, would someone mind explaining what I (evidently) have done wrong? Is it something to do with
me trying to operate on an *.inc file maybe?

Thanks everyone.

Just adding an extra module with a similarly-named function won't guarantee that gigya will call that function. If Gigya's module has hooks (Google doesn't seem to be able to tell me at a glance), then that's the source for how to do what you're trying to do.

Also, you never need to put your .module file in files[]. That's only for files in the module that declare classes.


CCK field in node template If I have a custom CCK field, for example "temperature", is there any way I can directly call it from the node template? Like would there be a $temperature variable?

Thanks!

You can access it directly from the node variable like: $node->field_temperature[0]['view'].

If you want to see what values are actually on the node, I'd suggest var_dump($node); in the template to check out what fields/values you can access.