Planet Drupal

Subscribe to Planet Drupal feed
Drupal.org - aggregated feeds in category Planet Drupal
Updated: 53 min 34 sec ago

Code Karate: An introduction to Git (part 1)

Tue, 20/01/2015 - 16:18

If you are not already using Git on your Drupal websites or projects, now is the time to learn.

Categories: Elsewhere

Sooper Drupal Themes: Drupal CMS Powerstart Tutorial 2: Responsive websites with Bootstrap 3 and Drupal

Tue, 20/01/2015 - 15:36

This tutorial will showcase how we have made Bootstrap 3 and especially its responsive grid system and integral part of the platform, and will show you how to use some easy tools to make any website component or content mobile friendly!

About Bootstrap 3 in CMS Powerstart

The Drupal CMS Powerstart disbitrution has made Bootstrap 3 an integral part of the platform. The main reason we did this is to leverage the Bootstrap 3 responsive grid system. This grid system is not just functional, practical and effective.. it's also widely used, widely understood and very well documented. On top of that, Bootstrap 3 is an active open source project, like Drupal, and also supported very well with Drupal through a basetheme and various modules. This tutorial will teach you about these integrations and how to use them to create awesome responsive websites with ease. This tutorial will focus more on Drupal integration than on the gridsystem itself. For a quick introduction to the grid system check out this tutorial. For real life examples check out our Drupal themes.

2.1 Bootstrap on blocks

Forget about themes with 16 regions, or 25 regions. If your'e using Bootstrap you really only need full-width regions that stack on top of one another. The horizontal division will be provisioned by block classes, with responsive layout switching that is customized for your content, not for your theme (-designer) or for an outdated wireframe.

In Drupal CMS Powerstart I added the block_class module and added a patch that assists in our responsive designing labours by auto-completing the Bootstrap 3 grid system classes. 

2.2 Bootstrap in Views

To use Bootstrap 3 in views we will use the views_bootstrap Drupal module. Let's take a look at how this module is used to create a Portfolio grid page for theDrupal CMS Powerstart Portfolio component.

powerstart-portoflio-grid-mock2.png

Live demo of portfolio grid.

The views_bootstrap module provides an array of new Views display plugins:

  • Bootstrap Accordion
  • Bootstrap Carousel
  • Bootstrap Grid
  • Bootstrap List Group
  • Bootstrap Media Object
  • Bootstrap Tab
  • Bootstrap Table
  • Bootstrap Thumbnails 

 

This grid of portfolio thumbnails uses the Bootstrap Grid views display plugin. The Bootstrap Grid plugin allows you to output any content in a grid using Bootstrap's grid html markup. A current shortcoming in the module is that it only allows you to select the number of columns for the 'large' media query. Fortunately, there is a patch for that:

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

The Drupal CMS Powerstart distribution has this patch included and uses it in views to create truly responsive grids, where you can set the number of columns per media query. It works quiet well out of the box. Here is the views format configuration used for the portfolio:

bootstrap-grid-views-plugin.jpg

As you can see it's real easy to create responsive views with this Views Bootstrap 3 integration! Without writing any code you can leverage the tried and tested responsive systems that are provided by Bootstrap. The views_bootstrap module gives you a whole set of tools that help you build responsive layouts and widgets using your trusted Views backend interface. This means site builders can rely less on themers/programmers and get work done quicker.

Using custom markup in views

The View Bootstrap module is great at organizing rows of data into responsive layouts, but it doesn't have the same level of support for fields inside a row of data. This is what we did to create a responsive events listing for the Drupal CMS Powerstart events component:

powerstart-events.jpg

Live demo of events view.

The events view uses the 'Unformatted list' plugin that is provided by the views module itself. This prints each row of data in a div container. There are 2 ways to make the contents of these rows responsive. One would be to generate node teasers inside the rows, and configure the content type's teaser display mode to use grid classes on the fields. This method will be covered in the next part of this tutorial. For the events view we don't use teasers, we are building a fields view because it gives us more flexibility in the fields we show in our view. Luckily the views interface makes it easy for us to add grid classes right where we need them. First, we will add a row class to each views row by clicking Settings under Format and adding row in the Row class field:

bootstap-rowclasses-views.jpg

Now we can add responsive column classes to our fields and they will be organized within each row. We simply add classes by clicking each field and editing the Style Settings CSS class field:

bootstap-classes-views.jpg

The only thing we need to do here is check the Create a CSS class checkbox, and a textbox will appear that allows us to add grid classes to the field. This field uses the class col-sm-6, which makes our event title use 50% of its parent container's width (because Bootstrap uses a 12 column grid) when on a small device. This means that on an extra small device there is not grid class active and the title will use 100% of it's parent container's width, as you can see in the mock-up above. We can't say this method is as easy as the point and click method discussed earlier but if you are familiar with the views interface already this method will become intuitive with a little bit of practice and will allow you to have very fine-grained control over responsive behaviors in your views.

2.3 Bootstrap in Fields

Often you want to organise content fields in a layout. A module that can be of help here is Display Suite, but even with the ds_bootstrap_layouts extension this will give you a limited set of layouts. We can easily build any layout by simply adding bootstral grid classes on fields. This is not to say I don't like Display Suite but since CMS Powerstart focuses on simplicity I will choose the simplest solution. 'Big' tools like Panels and Display Suite are definitely more appropriate for larger Drupal projects.

To make an example I will start building a new Drupal CMS Powerstart component. There was a feature request for a 'shop' component, so we will be building a content type as part of a simple component that will help brick and mortar shops display their inventory. First we will create a new content type called Object.  Since Bootstrap columns need to be wrapped in row classes, we are adding the field_group module. Once you have downloaded and enabled the field_group module, you will have a new option 'Add new group' under the manage fields tab of your Object content type. We are adding a group called Bootstrap row using the default widget fieldset. Now drag the image and body field to the indented position under the Bootstrap row field group. This will create a visual indication in the node/add and node/edit interface that fields belong to the same group. Your Manage Fields interface should now look like this:

bootstap-field-group.jpg

Next we will go to the Manage Display tab of the Object content type. This is where the Bootstrap magic happens. Our goal is to display the body text and image field beside eachother on big device and above one another in small devices. First, we have to create our Bootstrap row group again, this time we add a group named Bootstrap row and make it the 'Div' format. Give our field group the following configuration settings:

  • Fieldgroup settings: open
  • Show label: no
  • Speed: none
  • Effec none:
  • Extra CSS classes: row (you can remove the default classes)

Next we wil drag the Body and Image fields to the indented position under the field group. Now we simply configure the field formatters to use the Bootstrap grid classes of our choice. To add these classes in the Manage Display interface we are going to install another module: field_formatter_class. Once you have downloaded and enabled this module you can go back to the Manage Display interface and you will see an option to add a class on each field. You will now set both the Body and Image field to have the Field Formatter Class col-sm-6. This will create a 2 column layout on devices wider than 768px and a stacked layout on smaller devices. If you are using Drupal CMS Powerstart, you can set the Image style of your image field to Bootstrap 3 col6. This will resize the image to exactly fit the 6 column grid container.

Your Manage Display tab should now look like this: 

bootstap-field-group-display.jpg

Now if you create a node using your new content type it should look similar to this:

bootstap-field-group-node.jpg

Using our new fieldgroup tool we can easily add bootstrap rows and columns to any content type, and since classes are listed and edited in the Manage Fields interface, it's relatively quick and and easy to manage per-node layouts. At least it's a step up from managing a ton of node templates.

2.4 Bootstrap in Content: Shortcodes

Sometimes you (or a client) just want to create a special page that needs more attention than other pages of the same type. Unfortunately there aren't any free tools that give our clients a true WYSIWYG experience for creating responsive Bootstrap grids. If you know one please let me know! Our fallback option is the bs_shortcodes module that I ported from a Wordpres plugin. This module let's you add nearly all Bootstrap components, including grid elements, using a WYSIWYG-integrated form. 

To see the power and flexibility of what you can do with these shortcode check out this demo page:

http://glazed-demo.sooperthemes.com/content/responsive-columns

This system leverages the Drupal Shortcode API, which is a port of the Wordpress shortcode API. The Drupal CMS Powerstart distribution ships with a WYWISYG component that includes CKEditor 4 with the neccesary Shortcode API and shortcode-provisioning submodules. Since the configuration of this setup is complex and beyond the scope of this article I'm just going to assuming you are using Drupal CMS Powerstart and ready to use the WYSIWYG with Shortcodes integration.

To create a simple 2 column layout like in the previous examples we first add a row shortcode:

bootstrap-shortcode-row.png

Then we select the column shortcode and find the code that corresponds to 6 columns on a small devices:

bootstrap-shortcode-column.png

Now if we use 2 6 column shortcodes and put in the same content used in the Field and Field Group tutorial in will look like this in the editor:

bootstrap-shortcode-full.png

After saving the page it will look exactly as the Test Object page we created in the previous tutorial. I admit that shortcodes are a rather crude tool for a complex problem but anyone who is willing the learn the basic principles of a 12 column grid system will have a huge amount of flexibility and capability in creating responsive content. When you combine the Bootstrap 3 grid documentation, the WYSIWYG integration, and for emergencies the documentation of the Wordpress plugin you already have a fully documented tool for savvy clients who don't want to deal with raw HTML code. Shortcodes don't seem like the most userfriendly tool but I've seen clients pick it up quickly and appreciate the flexibility it gives them in organising their most important pages. In the future we migh see improvement in this area from tools like Visual Composer and the Drupal-compatible alternative Azexo Composer.

In Part 3 of this tutorial series I will write about using shortcodes as a site building tool and demonstrate what you can do with shortcodes in a real life Drupal CMS project. To get a sneak preview of the shortcode elements I will be using, check out our Drupal themes.

 

 

Tags planet drupal Bootstrap 3 Views Fields API Shortcodes cms powerstart Drupal 7.x
Categories: Elsewhere

Drupal core announcements: Drupal 8 beta 5 on Wednesday, January 28, 2014

Tue, 20/01/2015 - 15:36

The next beta for Drupal 8 will be beta 5! Here is the schedule for the beta release.

Tuesday, January 27, 2014 Only critical and major patches committed Wednesday, January 28, 2014 Drupal 8.0.0-beta5 released. Emergency commits only.
Categories: Elsewhere

VM(doh): Be Careful with Large Select Lists on Drupal Commerce Line Item Type Configuration

Mon, 19/01/2015 - 23:26

Recently, we were debugging some performance issues with a client's Drupal Commerce website. After doing the standard optimizations, we hooked up New Relic so we could see exactly what else could be trimmed.

The site is using different line item types to differentiate between products that should be taxed in different ways. Each line item type has a field where administrators can select the tax code to use for that line item type. The options for the select list are populated via an API call to another service provider. The call for the list was using the static cache because it was thought that the list would only be populated when needed on the line item type configuration page. In reality, that's not the case.

When an Add to Cart form is displayed in Drupal Commerce, it also loads the line item type and the line item type's fields. When loading the fields, it loads all of the options even if the "Include this field on Add to Cart forms for line items of this type" option is not enabled for that field. In this case, it resulted in 90 HTTP calls to populate the list of tax codes every time someone viewed a page with an Add to Cart form.

The solution was to actually cache those results using Drupal's Cache API. You can see the improvement:

Categories: Elsewhere

InternetDevels: The module for changing login/registration form view

Mon, 19/01/2015 - 11:16

While developing a site, we have been often faced with the task of changing the way the login form (authorization unit) is displayed. Previously, in such cases a css file was used. InternetDevels team has simplified this task by creating a “Сustomize login form” module. This tool allows to change the view of the site's authorization/registration/"Forgot your password?” forms using administration tool.

Read more
Categories: Elsewhere

Web Omelette: Creating a custom Views field in Drupal 8

Mon, 19/01/2015 - 09:10

In this article I am going to show you how to create a custom Views field in Drupal 8. At the end of this tutorial, you will be able to add a new field to any node based View which will flag (by displaying a specific message) the nodes of a particular type (configurable in the field configuration). Although I will use nodes, you can use this example to create custom fields for other entities as well.

So let's get started by creating a small module called node_type_flagger (which you can also find in this repository):

node_type_flagger.info.yml:

name: Node Type Flagger description: 'Demo module that flags a particular node type in a View listing' type: module core: 8.x

In Drupal 7, whenever we want to create a custom field, filter, relationship, etc for Views, we need to implement hook_views_api() and declare the version of Views we are using. That is no longer necessary in Drupal 8. What we do now is create a file called module_name.views.inc in the root of our module and implement the views related hooks there.

To create a custom field for the node entity, we need to implement hook_views_data_alter():

node_type_flagger.views.inc:

/** * Implements hook_views_data_alter(). */ function node_type_flagger_views_data_alter(array &$data) { $data['node']['node_type_flagger'] = array( 'title' => t('Node type flagger'), 'field' => array( 'title' => t('Node type flagger'), 'help' => t('Flags a specific node type.'), 'id' => 'node_type_flagger', ), ); }

In this implementation we extend the node table definition by adding a new field called node_type_flagger. Although there are many more options you can specify here, these will be enough for our purpose. The most important thing to remember is the id key (under field) which marks the id of the views plugin that will be used to handle this field. In Drupal 7 we have instead a handler key in which we specify the class name.

In Drupal 8 we have something called plugins and many things have now been converted to plugins, including views handlers. So let's define ours inside the src/Plugin/views/field folder of our module:

src/Plugin/views/field/NodeTypeFlagger.php

<?php /** * @file * Definition of Drupal\node_type_flagger\Plugin\views\field\NodeTypeFlagger */ namespace Drupal\node_type_flagger\Plugin\views\field; use Drupal\Core\Form\FormStateInterface; use Drupal\node\Entity\NodeType; use Drupal\views\Plugin\views\field\FieldPluginBase; use Drupal\views\ResultRow; /** * Field handler to flag the node type. * * @ingroup views_field_handlers * * @ViewsField("node_type_flagger") */ class NodeTypeFlagger extends FieldPluginBase { /** * @{inheritdoc} */ public function query() { // Leave empty to avoid a query on this field. } /** * Define the available options * @return array */ protected function defineOptions() { $options = parent::defineOptions(); $options['node_type'] = array('default' => 'article'); return $options; } /** * Provide the options form. */ public function buildOptionsForm(&$form, FormStateInterface $form_state) { $types = NodeType::loadMultiple(); $options = []; foreach ($types as $key => $type) { $options[$key] = $type->label(); } $form['node_type'] = array( '#title' => $this->t('Which node type should be flagged?'), '#type' => 'select', '#default_value' => $this->options['node_type'], '#options' => $options, ); parent::buildOptionsForm($form, $form_state); } /** * @{inheritdoc} */ public function render(ResultRow $values) { $node = $values->_entity; if ($node->bundle() == $this->options['node_type']) { return $this->t('Hey, I\'m of the type: @type', array('@type' => $this->options['node_type'])); } else { return $this->t('Hey, I\'m something else.'); } } }

We are defining our NodeTypeFlagger class that extends FieldPluginBase (which is the base plugin abstract class for the views field many plugins extend from). Just above the class declaration we use the @ViewsField annotation to specify the id of this plugin (the same one we declared in the hook_views_data_alter() implementation). We also use the @ingroup annotation to mark that this is a views field handler.

In our example class, we have 4 methods (all overriding the parent class ones).

Query

First, we override the query() method but leave it empty. This is so that views does not try to include this field in the regular node table query (since the field is not backed by a table column).

DefineOptions

The second method is the defineOptions() method through which we specify what configuration options we need for this field. In our case one is enough: we need to specify the node type which we want flagged in the Views results. We set a sensible default as the article node type.

BuildOptionsForm

The third method, buildOptionsForm() is responsible for creating the form for the configuration options we declared earlier. In our case we just have a select list with which we can choose from the existing node types.

Render

Lastly, the render() method which is the most important and which deals with output. We use it to actually render the content of the field for each result. Here is where we perform some business logic based on the currently set node type option and flag with a message whether or not the current result is in fact of the type specified in the configuration.

The $resultRow object is an instance of Drupal\views\ResultRow which contains data returned for the current row by Views and the entity object at the base of the query (in our case the node). Based on this information we can perform our logic.

Keep in mind you can use depedency injection to inject all sorts of services into this class and make use of them in your logic. Additionally, you can override various other methods of the parent class in order to further customize your field.

Conclusion

There you have it. A small custom module that demonstrates how to create a custom Views field (plugin). Relationships, filters, sorters and others work in similar way. I will be covering those in later articles. Stay tuned.

var switchTo5x = true;stLight.options({"publisher":"dr-8de6c3c4-3462-9715-caaf-ce2c161a50c"});
Categories: Elsewhere

DrupalOnWindows: Node Comment and Forum working together to boost user participation

Mon, 19/01/2015 - 07:00

It is frequent that customers approach us asking for help to rescue their projects from site builders. Sometimes they have technological issues (mainly slow sites) but sometimes it's just plain bad usability os some wrong marketing concepts.

We recently were asked for help from a site that gets about 5,000 unique visitors a day. Despite the not so bad visitor numbers for their niche, this page was getting very low user interaction. They barely got a handful (<10) of comments and forum posts in a whole year timespan.

Language English
Categories: Elsewhere

Drupal core announcements: Drupal core security release window on Wednesday, January 21

Mon, 19/01/2015 - 06:51
Start:  2015-01-21 (All day) America/New_York Online meeting (eg. IRC meeting) Organizers:  David_Rothstein

The monthly security release window for Drupal 6 and Drupal 7 core will take place on Wednesday, January 21.

This does not mean that a Drupal core security release will necessarily take place on that date for either the Drupal 6 or Drupal 7 branches, only that you should prepare to look out for one (and be ready to update your Drupal sites in the event that the Drupal security team decides to make a release).

There will be no bug fix release on this date; the next window for a Drupal core bug fix release is Wednesday, February 4.

For more information on Drupal core release windows, see the documentation on release timing and security releases, and the discussion that led to this policy being implemented.

Categories: Elsewhere

3C Web Services: Creating a Drag &amp; Drop Sorting Interface for a Drupal View

Sun, 18/01/2015 - 21:45
How to create a drag and drop sorting interface for a Drupal 7 View.
Categories: Elsewhere

Danny Englander: Drupal Drush Segmentation Fault 11 Error: Avoiding the Rabbit Hole

Sun, 18/01/2015 - 21:02

I've been doing a lot lately with Grunt and LibSass within my drupal.org contrib theme, Gratis. Yesterday, I updated my Node modules locally. Shortly thereafter, I started getting a nasty Drush error.

line 1: 48475 Segmentation fault: 11  
/opt/local/bin/php /Users/danny/.composer/vendor/drush/drush/drush.php
--php=/opt/local/bin/php --backend=2
--root=/Users/danny/Sites/Drupal/gratis2/gratis2-site
--uri=http://default pm-updatestatus 2>&1 or sometimes just:

Segmentation fault: 11

Not only that but my local site's admin UI started WSODing. I didn't immediately connect the Node NPM update to the drush error. So I looked in my MacPorts Apache log and saw hundreds of these streaming down every few seconds:

[Sat Jan 17 13:03:56 2015] [notice] child pid 49312 exit signal Segmentation fault (11)

No joy

Doing a Google search led me to some varied and vague issues with regard to Apache and MySQL but none of theme really rang true to what I was experiencing. I decided to check some of my other local sites and they all seemed fine; no errors, WSODs, or otherwise. Bizarre! I worked for about an hour, but still no joy, I was headed down a rabbit hole. That being said, I let this rest for a while. I always let a problem to sit for a bit if I can't fix it right away or ask for help. More often than not, I'll come back later and end up fixing it.

The search

I got out for some air and went to downtown San Diego to take some photos. That usually gets my mind off things and is relaxing. Arriving back later in the day, I got back into it and decided to search for drush cache clear segmentation fault theme. Bingo! (and 50 browser tabs later). I don't know why I didn't search for this earlier in the day, I was just searching the pure Apache log error which knows nothing of drush.

Sure enough it's an error related to Node modules (from the node_modules folder) having a .info file. Drush sees that and thinks it's supposed to be part of Drupal. The problem is, in a Drush world, these files are malformed. Thus the errors. Right about now, I was wishing there was some kind of .drushignore file along the same lines as .gitignore.

With this new search, here's the relevant posts I found:

In turn, these led me to the main issue, Themes should not crash when .info file appears inside node_modules

It turns out there is a proposed patch for core to prevent this error. I somehow don't see this getting in anytime soon but there are some workarounds on the Node / Grunt end of things.

Custom script

Here is the fix that I arrived at based on all the suggestions and comments in this last issue. First, we need to write a Node NPM cleanup Bash script. The script will find any .info files and rename them to .inf0 (with a zero). This will not have any negative effects as you don't commit node_modules folder to your repo and the info files are not actually needed for Grunt to run properly. So we'll call our script,npm_post.sh

#!/bin/sh
# npm_post.sh

# This script finds any .info files in the node_modules directory and renames them so they don't
# conflict with drush. package.json runs this on completion of npm install.
# These files, if any are not actually needed to run grunt and compile LIbSass
# See this issue for more info: https://www.drupal.org/node/2329453

find -L ./node_modules -type f -name "*.info" -print0 | while IFS= read -r -d '' FNAME; do
    mv -- "$FNAME" "${FNAME%.info}.inf0"
done

Once you have this in the same folder as your package.json file (in my case the root of my theme), you'll need to call it with a postinstall method from your package.json file.

  "scripts": {
    "postinstall": "sh npm_post.sh"
  },

One caveat here is that you may run into an error that the script won't run. To solve this you can either run sudo npm install --unsafe-perm or alternatively create an .npmrc file with the code:

unsafe-perm = true

and then run sudo npm install as usual.

Conclusion

Running into errors like this is definitely not fun but I learned a lot in the process. I am not sure if this is the best fix in the world but it seems to work fine for my use case. It also shows us to not get tunnel vision when trying to fix a development problem.

Tags 
  • Drupal
  • Grunt
  • Node NPM
  • Drupal Planet
Categories: Elsewhere

Alexander Mikhailian: Data-mining Drupal users in a screenful of code

Sun, 18/01/2015 - 10:53
Objective

Select like-minded users from a local community website.

Pre-requisites
  1. A Drupal website with the votingapi module enabled and at least a few dozen votes by registered users.
  2. A working installation of the R language.
Exract data

For each user, select all other users that voted on same node and comments:

SELECT v1.uid uid1, v2.uid uid2, u.name name2, v2.entity_id entity_id, v1.value value1, v2.value value2 FROM votingapi_vote v1 JOIN (votingapi_vote v2, users u) ON (v1.uid != v2.uid AND v1.entity_id=v2.entity_id AND v1.entity_type=v2.entity_type AND v2.uid=u.uid) WHERE v1.uid

This produces a table

Categories: Elsewhere

Akshay Kalose: Drupal 8: Ajax in Forms

Sat, 17/01/2015 - 22:45

Why reload the whole page, when you can just update a certain parts of the DOM? Ajax allows you to do just this, to dynamically update content. Just one of the many great uses of Ajax is Form Validation. In this example, we will see how to implement this.

We will be making a simple form which will contain a text field that will validate if the username entered exists, and a button that will replace the text field value with a random existing username.

Building The Form

First, we need to define our two form elements:

$form['user_name'] = array( '#type' => 'textfield', '#title' => 'Username', '#description' => 'Please enter in a username', ); $form['random_user'] = array( '#type' => 'button', '#value' => 'Random Username', );

Next, to start using Ajax in Drupal, all you need to specify is the “callback“, or function to call, when the “event“, or trigger, is fired on that certain form element, in an array under the “#ajax” key:

$form['user_name'] = array( '#type' => 'textfield', '#title' => 'Username', '#description' => 'Please enter in a username', '#ajax' => array( // Function to call when event on form element triggered. 'callback' => 'Drupal\ajax_example\Form\AjaxExampleForm::usernameValidateCallback', // Javascript event to trigger Ajax. Currently for: 'onchange'. 'event' => 'change', );

In the “callback”, include the full namespaced class and function you want to call. The event can be any Javascript event without the “on”. A list of Javascript events can be found here.

Once you have added these two keys, you can add extra options such as “effect”, and “progress”. More options can be found on the Ajax API. Here are the finished elements:

$form['user_name'] = array( '#type' => 'textfield', '#title' => 'Username', '#description' => 'Please enter in a username', '#ajax' => array( // Function to call when event on form element triggered. 'callback' => 'Drupal\ajax_example\Form\AjaxExampleForm::usernameValidateCallback', // Effect when replacing content. Options: 'none' (default), 'slide', 'fade'. 'effect' => 'fade', // Javascript event to trigger Ajax. Currently for: 'onchange'. 'event' => 'change', 'progress' => array( // Graphic shown to indicate ajax. Options: 'throbber' (default), 'bar'. 'type' => 'throbber', // Message to show along progress graphic. Default: 'Please wait...'. 'message' => NULL, ), ), ); $form['random_user'] = array( '#type' => 'button', '#value' => 'Random Username', '#ajax' => array( 'callback' => 'Drupal\ajax_example\Form\AjaxExampleForm::randomUsernameCallback', 'event' => 'click', 'progress' => array( 'type' => 'throbber', 'message' => 'Getting Random Username', ), ), );

Creating The Callbacks

After creating our form elements, it is time to create the callback functions which will return the response of what to update on the page.

These callbacks will return an instance of \Drupal\Core\Ajax\AjaxResponse. Each AjaxResponse instance will contain jQuery commands that will execute on the form. You can use the “addCommand()” method on AjaxResponse to add commands that implement \Drupal\Core\Ajax\CommandInterface.

Some commands such as CssCommand and ChangedCommand did not work. Thankfully, there is InvokeCommand which allows you to run any jQuery command. You can construct it with a jQuery selector, method, and arguments:

public InvokeCommand::__construct($selector, $method, array $arguments = array())

Here are the two callbacks for our form:

public function usernameValidateCallback(array &$form, FormStateInterface $form_state) { // Instantiate an AjaxResponse Object to return. $ajax_response = new AjaxResponse(); // Check if Username exists and is not Anonymous User (''). if (user_load_by_name($form_state->getValue('user_name')) && $form_state->getValue('user_name') != false) { $text = 'User Found'; $color = 'green'; } else { $text = 'No User Found'; $color = 'red'; } // Add a command to execute on form, jQuery .html() replaces content between tags. // In this case, we replace the desription with wheter the username was found or not. $ajax_response->addCommand(new HtmlCommand('#edit-user-name--description', $text)); // CssCommand did not work. //$ajax_response->addCommand(new CssCommand('#edit-user-name--description', array('color', $color))); // Add a command, InvokeCommand, which allows for custom jQuery commands. // In this case, we alter the color of the description. $ajax_response->addCommand(new InvokeCommand('#edit-user-name--description', 'css', array('color', $color))); // Return the AjaxResponse Object. return $ajax_response; } public function randomUsernameCallback(array &$form, FormStateInterface $form_state) { // Get all User Entities. $all_users = entity_load_multiple('user'); // Remove Anonymous User. array_shift($all_users); // Pick Random User. $random_user = $all_users[array_rand($all_users)]; // Instantiate an AjaxResponse Object to return. $ajax_response = new AjaxResponse(); // ValCommand does not exist, so we can use InvokeCommand. $ajax_response->addCommand(new InvokeCommand('#edit-user-name', 'val' , array($random_user->get('name')->getString()))); // ChangedCommand did not work. //$ajax_response->addCommand(new ChangedCommand('#edit-user-name', '#edit-user-name')); // We can still invoke the change command on #edit-user-name so it triggers Ajax on that element to validate username. $ajax_response->addCommand(new InvokeCommand('#edit-user-name', 'change')); // Return the AjaxResponse Object. return $ajax_response; }

Finished Form

Here is our finished Ajax Example Form:

 

This blog post was created for Google Code-In 2014 to learn about a Drupal Core System.

Full Module Code .gist table { margin-bottom: 0; }

The post Drupal 8: Ajax in Forms appeared first on Akshay Kalose.

Categories: Elsewhere

3C Web Services: How to remove the Fieldset from a Drupal Address Field

Sat, 17/01/2015 - 16:57

INTRODUCTION

The Drupal Address Field Module is a great tool that we use often. There are, however, many times when the default output causes some issues for us. Be default, Address Field places all of its individual field components inside of a Feldset wrapper. This is usually a nice feature but there are times when you may want to remove this Fieldset wrapper for ascetics. Or, perhaps, you'd like to place additional fields within the Address Field's Fieldset. We'll show you how to do both.

Categories: Elsewhere

DrupalOnWindows: Node Comments and Forums working together to boost user engagement

Sat, 17/01/2015 - 13:07

It is frequent that customers approach us asking for help to rescue their projects from site builders. Sometimes they have technological issues (mainly slow sites) but sometimes it's just plain bad usability os some wrong marketing concepts.

We recently were asked for help from a site that gets about 5,000 unique visitors a day. Despite the not so bad visitor numbers for their niche, this page was getting very low user interaction. They barely got a handful (<10) of comments and forum posts in a whole year timespan.

Language English
Categories: Elsewhere

The Cherry Hill Company: Creating a Context Plugin

Fri, 16/01/2015 - 22:49

On a recent project I was using the combination of Field Collection, Entity Reference, Taxonomy Terms, and Context to make a reusable set of references to terms on various content types. Then, based on the referenced term, I wanted to satisfy a context condition.

Due to the somewhat complex structure, the context was not aware of the term referenced through entity reference and the field collection.

In a case like this, creating a custom context plugin was a good solution.

I got started by reading a couple of helpful posts by others: Custom Context Conditions and Extending Drupal's Context Module: Custom...

Read more »
Categories: Elsewhere

Advomatic: Views in Drupal 8: Improved Displays

Fri, 16/01/2015 - 20:09
Now that Drupal 8 is in beta, I’ve been trying to spend some more time with it. Reading articles and watching presentations are good ways to keep up with where things are (or are going), but nothing beats actually using it. Simplytest.me, Pantheon, and Acquia Cloud all now provide free ways to spin up an instance... Read more »
Categories: Elsewhere

Drupal Watchdog: Drush: The Swiss Army Knife for Drupal

Fri, 16/01/2015 - 17:41
Article

I’m personally amazed at the new features and advances of Drupal 8. There are so many changes to talk about, but for this article I want to cover configuration management. In case you haven't yet heard, with the new version of Drupal we see all configuration stored in files instead of in the database. With the new version of Drush there are some built in tools to help manage these files.

At the time of this writing, the recommended version of Drush is 6; however, this article uses commands that were introduced with version 7. Before you can try any of these, you’ll need to be running that version of Drush. The tricky part is that it currently does not have a full release. Typically, you would not want to install a project’s dev release in a production environment. I’m going to assume you will be working locally, on a development server, or are confident you can’t hurt anything otherwise.

In a previous article I explained how to install Drush using Pear; however, the project is shifting to Composer. You can still install via Pear, or even manually, but it's recommended you switch to Composer. Drush has also been moved to GitHub; you will find additional instructions for installing with something other than composer there.

Assuming your environment already has Composer installed, get the latest release of Drush 7 and issue the below command.

composer global require drush/drush:dev-master --prefer-source

Next, verify that it installed:

drush version

The output should indicate you have Drush 7.0-dev, or something along those lines. If it didn't work you may need to log out and back in again before your SSH user will know it's installed.

Now that we have the latest and greatest, the next thing to do is get Drupal 8. Using Drush you can request a specific version of Drupal, or any project, by providing the version number. If you don’t provide a version it will find the recommended version and download that instead.

To get the dev version of Drupal, type this:

drush dl drupal-8.x-dev

Next, let’s get a site installed. Keep in mind that you will need to configure your web server and database since this command only handles the install of Drupal.

Categories: Elsewhere

Lullabot: The RESTful Module

Fri, 16/01/2015 - 15:00
Categories: Elsewhere

Code Karate: Drupal 7 Superfish: An easy way to get dropdown menus

Fri, 16/01/2015 - 13:27
Episode Number: 191

Just like your grandparents, the Superfish menu module is an oldy but a goodie. Since 2010, Superfish has been helping site owners implement the infamous dropdown menu. Over the years Superfish has been improved to include various features for touch screens, and responsive needs.

Tags: DrupalDrupal 7Drupal PlanetUI/DesignJavascriptResponsive Design
Categories: Elsewhere

Doug Vann: Put your content center stage. Backdrop CMS 1.0 is here!

Fri, 16/01/2015 - 08:34

Today is a much anticipated day. Some said it would never come. Others said that if it did come it could ultimately mean nothing. Still others, and myself, believe that it is a red-letter date that will be long celebrated as the day that Backdrop CMS 1.0 was launched.

Backdrop CMS is a comprehensive CMS for non-profits and small to medium sized businesses. Not inconsequentially, it is a Drupal fork.

I am on the record as saying that Backdrop CMS supplies a need in the market place. I believe that Drupal 8 is charging ahead into new and innovative territory and leaving behind a disenfranchised segment of the Drupal community. This segment includes both those who need websites and those who create them. The Drupal 7 methodology is a proven success. Backdrop CMS builds upon that success and prepares the way for a continued bright and prosperous future.

 

Before I continue my take on all of this, Let me give you a brief glimpse of the early days of BackdropCMS.

  1. June 2012
    • Nate, Jen, and a few others have a conversation discussing the many changes in Drupal 8 and how those changes come with a cost. The idea comes up of getting "back" to the principles that lead to Drupal's amazing success. The phrase Backdrop is first coined.
  2. August 2013
    • Nate registers BackdropCMS.org and on the same date publishes the Backdrop repository
  3. September 11, 2013
  4. In the weeks and that months that followed, there were many blog posts and podcasts. Here are just a couple.

I don’t know how many people want to weed through all of those blogs and podcasts, but I can tell you that many of us lived through it and it was exciting! I was glued to my Mac trying to keep track of it all. I wanted to hear what the Drupal Easy guys had to say. I wanted to hear what Nate and Jen had to say on their interviews. I wanted some sense of what people thought about it, how they reacted, etc. In short, it was very important to me that I maintained some sense of how the Drupal Community at large felt about the whole idea of Backdrop CMS.

Why care what the Drupal community feels about BackdropCMS?

Well… Back on 9/11/13 when the twitter-sphere lit up about BackdropCMS, I too tweeted out that I supported it. Within minutes of my tweet, I got an email from Dries asking me why I supported it. We ended up discussing many aspects of the whole situation. We didn’t really end the exchange with anything concrete other than the fact that we started with different perspectives and feelings and we ended with those same different feelings and perspectives. Since then, I've enjoyed many conversations with community members as we discuss the impact that Backdrop CMS is having or will have on the Drupal Community.

Bottom Line:

As the title so boldly states, Backdrop CMS 1.0 is here! This is going to change many things. I look forward to watching as more and more people discover this new, and powerful tool and begin recommending it to their clients who already love Drupal and wish to enjoy increased functionality without the dramatic changes.

Drupal Planet

View the discussion thread.

Categories: Elsewhere

Pages