Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough
Feb 13 2012
Feb 13

Need a simpler UI to let administrators manage fields? We recently created a new contributed module called Simple Field. This module simplifies the UI for creating fields and adding them to content types and entities. It also provides granular permissions, so you're not stuck with a single catch-all permission for managing fields. You can see a demo of the module in action at simplefield-demo.ewdev.ca (login: demo/demo).

Why do I need Simple Field?

Imagine you're creating a Drupal site and you want to let your users create fields, but you don't want to give them the 'Manage Fields UI'. The Manage Fields UI is very powerful, but it also provides a lot of settings and configuration that can be confusing for non-technical users. Giving users permission to manage fields allows them to delete fields, and you might want more granular permissions to prevent users from deleting data on the site.

Simple Field Types

The Simple Field module includes a set of Field Types. Instead of a long list of cryptic types which can intimidate non-technical users, field types are things like 'Multiple Choice' or 'Yes/No'.


List of built-in Simple Field types

Simple Field types include a core field type, plus some field widget settings. For example, rather than choosing 'Boolean', users can choose 'Yes/No', which is a Boolean field with pre-configured options for yes or no. The user adding the Simple Field will not see the 'Options' field and won't be able to change the option values.

Of course, we can't anticipate all the Simple Field types that other sites will need, so the module is extensible and allows developers to define additional Simple Field types in code.

Creating Fields is as Easy as Pie

With pre-defined field settings, creating fields becomes much easier for users. Users just need to enter the label, whether the field is required, and help text. Some Simple Field types, such as 'Multiple Choice', have an options field, but that's it.


Creating a 'Yes or No' Simple Field

Attaching Simple Fields to Content Types

You can enable Simple Field on a per content type basis, which provides a nice UI for managing the Simple Fields for that content type. The module uses modals to keep the UI concise. You can create and attach files from the same page.


UI for attaching Simple Fields to a Customer content type

An Alternative UI for Creating Fields

The Simple Field module provides an alternative UI for creating fields, which only exposes some of the field settings to users. Other administrative roles can still be given access to all of the more advanced settings through the Manage Fields UI. The fields are stored in the database in exactly the same way, so everything like Views integration still works. All settings and weights are synchronized between the two interfaces.


Simple Fields appear in the Manage Fields UI

Granular Permissions for Fields

Permissions for the Simple Field module are very granular. You can control which roles have access to which field types and whether users can delete fields or remove fields from a particular content type or entity. For example, you can configure your site so that the users with the 'service rep' role can add Yes/No, Multiple Choice, and Short Answer simple fields to the customer content type. This way, service reps can add fields on-the-fly if they realize that collecting a particular piece of information from customers is valuable.


Simple Field Permissions

Adding Simple Fields to Entities: Fields as Content

While the Simple Field module can be used to add fields to bundles (i.e. content types) it can also be used for adding fields to entities. This opens up a ton of new possibilities. For example, you can create a survey entity and allow users to attach fields to each individual entity. Used this way, the Simple Field module is kind of like an alternative to the Webform module, allowing you to add fields to pieces of content.

Presentation at DrupalCamp NJ

Alex Dergachev presented a case study at Drupal Camp NJ on February 4, 2012 and included a demo of the Simple Field module. The case study shows our original use case for the module in the context of a Drupal project for a university.

Documentation

For information on creating new types, among other things, take a look at the documentation.

Oct 04 2011
Oct 04

We've been hearing a lot about responsive design and the future of the web recently. At DrupalCamp Montreal this September, Jen Simmons and Jake Strawn talked about why responsive design is taking hold. I was inspired to try out some of the techniques they talked about, and decided to convert evolvingweb.ca to be more responsive.

Unlike creating an iPhone app for your website or throwing together a mobile theme, applying responsive design to your existing site requires you to change the design of your website. What I thought would be a few small adjustments to the theme turned into a larger project to make our design and theme more flexible and robust.

What is Responsive Design?

Rather than designing a site that works for one screen size, or designing separate themes that work for different devices, the goal of responsive design is to build a website that adapts to the width of the user's screen and works for both large and small screens. This involves creating a flexible-width layout that will adapt as the screen size changes, and writing some CSS specific to screens with a particular size so that you can trim down or hide certain elements at smaller widths and restrict the width of the page at large screen widths.

Media Queries

Currently, the main technique for implementing responsive design is to use media queries. Media queries allow you to include CSS files based on the size of the user's screen or device. At different screen widths (or device widths), you can load different CSS files which change the layout and styling of the page. You can do this either by targeting screens with a particular minimum width, maximum width, or both.

CSS for Larger Screens

To include CSS files for screens larger than a certain width, you can use the following in your mytheme.info file:

stylesheets[screen and (min-width: 760px)][] = css/screen-760.css
stylesheets[screen and (min-width: 960px)][] = css/screen-960.css

The screen-760.css file is loaded for browsers the width of 760px, but also larger screens. It allows for a total page width of 760px and also defines a layout for the columns to fit in that width.

The screen-960.css file is loaded for any a screen width of 960px or larger. It restricts the width of the page to 960px and allows for normal-sized column widths (i.e. 640px for the main content and 320px for the sidebar). If you're converting an existing theme to be responsive, this will contain a lot of what used to be in your layout CSS file.

CSS for Smaller Screens

Include the following in your .info file to include CSS for screens smaller than a certain width:

stylesheets[screen and (max-width: 320px)][] = css/screen-320.css
stylesheets[screen and (max-width: 480px)][] = css/screen-480.css

The screen-320.css file would only be loaded for screens 320px wide or narrower. The screen-480.css file would be loaded for screens 480px or narrower. Notice that since a device that is 480px wide will load both files, it makes sense to load the screen-480.css file second so it overrides the styles in the 320px stylesheet.

CSS for a Range of Screen Sizes

You can also effectively set a range of screen sizes that your CSS will target by combining a min-width and min-width in your media query.

stylesheets[screen and (min-width: 480px) and (max-width: 760px)][] = css/screen-480-760.css

Inline Media Queries

Depending on your design, you might end up with a lot of screen-size-specific CSS files. Sometimes it's more appropriate to use several media queries within a CSS file, using the @media rule.

@media screen and (max-width: 480px) {
  #page {
      width: 480px;
  }
}

Device Width vs. Browser Width

I should clarify that using min-width means that the CSS file will be loaded based on the browser width, so this will apply to users of large monitors who resize their browser. This is really useful for testing your responsive design, since you don't need to switch devices to see your design change, just change the width of your browser. If you only want to detect the device width only, use min-device-width or max-device-width.

It's Not Working on Android!

In addition to adding these media queries, Android devices need a 'viewport' meta tag to being able to detect their own screen width. Adding the media queries above won't have any effect on Android devices until you add this meta tag to your site. You can add it from your mytheme_preprocess_html() function using drupal_add_html_head() like this:

<?php
  $meta_viewport 
= array(
    
'#type' => 'html_tag',
    
'#tag' => 'meta',
    
'#attributes' => array(
      
'name' => 'viewport',
      
'content' => 'width=device-width'
    
)
  );
  
drupal_add_html_head($meta_viewport'viewport');
?>

What to do about Internet Explorer?

Internet Explorer versions 6-8 don't implement media queries. For these versions of IE, you can either implement some kind of responsive solution with javascript, or you can decide not provide the responsive layout for IE users, which the approach I took. In this case, you still need to provide CSS targeting IE so that users viewing your website on a larger device with IE will not see a full-width design. To implement this approach, the CSS you'll want to add for IE will likely be the same as what you added for screens that have a min-width of 960px (or whatever your widest page layout is). Drupal doesn't allow you to add a CSS file more than once, so you'll have to create a duplicate CSS file. My solution was to create a separate screen-960-ie.css file and use @import to include in it all the CSS from the screen-960.css file.

You can add a CSS file for IE only using the Conditional Stylesheets module. You can also add the file from your template.php file using drupal_add_css() and setting the browsers parameter.

Designing for Mobile

The instructions above will get you started adding media queries to your Drupal theme, but I think there's a lot to be said about how to actually create a 'mobile first' design. As themers, we're not used to designing and writing flexible-width themes for tiny devices. Even though you might like the idea of 'mobile first', your client probably expects you to design for standard-sized monitors and adapt the design for smaller devices afterwards.

Adapting a design to be responsive after it's fleshed out for a fixed-width screen is not an easy task. You can stack columns on top of each other at smaller widths, make certain elements smaller, and remove others altogether, but some elements are going to be hard to adapt. If you resize your browser to a smaller width, you'll notice a lot of awkward layouts (i.e. an image that takes up almost the full width of a column, with just a couple words wrapping to the right of it).

The best approach is to start thinking about how to make your theme responsive as you're designing and building it, and testing it at various screen widths as you go. This is going to be a challenge when the designer and themer are different people, especially if the designer is working exclusively in Illustrator or Photoshop.

Writing CSS for Responsive Design

Here are some tips to get you started writing CSS for responsive design.

  • Watch out for elements that are positioned absolutely. Will they overlap with other items at smaller screen widths?
  • Make sure your horizontal menus items wrap gracefully. Try centering them on smaller screens and using the CSS3 white-space: nowrap property.
  • Check the line-height on text that wraps at smaller screen widths.
  • Set a max-width for images of 100%, as well as for the HTML tag that wraps each image.
  • Set a max-width of 100% for form elements as well.
  • Watch out for elements with a fixed height or width. Try setting a min or max width or height instead.
  • Watch out for elements that are altered with javascript, including slideshows and text replacement tools.
  • Watch out for text that floats next to images. Do you need to change this behaviour for smaller width screens?

What do do with Tables and Panels

I found dealing with tables and Panels to be a huge challenge. Columns could be removed at smaller widths, or stacked on top of each other rather than sitting next to each other.

  • Panels layouts with more than one or two columns will not work well on smaller screens. Try writing CSS to remove columns or float columns differently at smaller widths.
  • If you're using grid-style Views to display non-tabular data, consider another display technique.
  • If you need to display data in a table, consider using advanced CSS techniques as described in this article.
  • Some of your mobile users will have an app for displaying spreadsheets on their device, so consider generating a CSV for users to download if you have a lot of tabular data to display.

Resources

Beyond Responsive Design

For some use cases when mobile performance is a priority, you'll probably want to go beyond responsive design and actually change the markup of the page for different devices. To get started doing this in Drupal, try the Mobile Tools or Context User Agent. However, mobile detection doesn't replace responsive design, and using device detection is probably out-of-scope for most Drupal projects.

Responsive design is really exciting and a great challenge for both designers and themers. While using a base theme that provides a responsive layout is great, it doesn't mean that you don't have to think about responsive design. We need to understand how different screen sizes effect our designs and how to meet the challenge of responsive design by creating more robust and more flexible themes.

Sep 27 2011
Sep 27

In Drupal 6, module developers often use Nodes as an all-purpose method for having objects that can be saved into the database. This hack avoids having to write a lot of boilerplate CRUD for all custom data used in your modules. Nodes in D6 are a powerful tool for this use case when combined with the flexibility of CCK's custom fields, and the simplified integration with contrib modules. However, using Nodes for every piece of specialized content means a lot of overhead; contributed modules often modify Nodes and added hooks that operated on them. This is a major performance concern, not to mention a bad architecture for unrelated data.

In Drupal 7, we have entities. Entities not only provide all functionality available with Nodes in D6, but they offer much more. Many modules in core are now using Entities for their database records, including node.module and user.module. In this post, we'll discuss what Entities are, some poignant examples of Entities, and why you would want to use them.

What is an Entity?

Entities can be thought of as the parent class of nodes. They are the abstraction of functionality common between Nodes, Taxonomy Terms, and Users (among others). You can see this very clearly by looking at the Drupal 7 version of user_load_multiple() and node_load_multiple().

<?php
function user_load_multiple$uids = array(), 
                             
$conditions = array(),
                             
$reset FALSE) {
  return 
entity_load('user'$uids$conditions$reset);
}
function 
node_load_multiple$nids = array(),
                             
$conditions = array(),
                             
$reset FALSE) {
  return 
entity_load('node'$nids$conditions$reset);
}
?>

As you can see, the loading behaviour of nodes and users is almost identical. This makes a lot of code in Drupal 7 core more maintainable and much cleaner. Building on this, the API defines a consistent set of functions for getting information such as label and uri for an entity, which was often annoying extra work in D6. One of the biggest benefits, however, is that you can define your own custom entities, and they can also be fieldable. In short, you get all of the convenience of nodes without the overhead and unnecessary code.

Entities also have revision tracking support baked in, just like the the Node module. This lets you have multiple versions of the entity stored in the database, but without having to define the revision-loading logic yourself. For example, if you made a “Wiki page” entity, you could track changes to pages and, with some ingenuity, show a diff between two revisions. Setting up these tables and writing boilerplate SQL and loading code would be time consuming and error-prone, but with entities, you can get Drupal to d the hard work for you.

Examples of entities

Some notable Entity types are Nodes, Users, and Taxonomy Terms. However, many contributed modules have moved to Entities for this kind of functionality. Here are some notable modules that use Entities:

  • Wysiwyg: Uses entities for profiles.
  • Organic Groups: Uses entities for groups, membership types, and memberships.
  • Commerce: Uses entities for products, customers, payments, and line items.
  • Field Collection: Uses entities for “Field-collection items.” The Field collection module allows you to add fields to the “Field-collection items,” which then appear to be added to the entity that the field collection was originally attached to.
  • Relation: Uses entities for — you guessed it — relations. These entities link two other entities together. But, since relations are entities, the relationships themselves can have fields.

Benefits of Entities

Why are entities so cool? Here’s a short list:

Avoiding Boilerplate loading logic and SQL

Writing loading functions like node_load and boilerplate SQL is tedious and hard to maintain. With Entities, we can focus on the important functionality that is specific to our data type.

Consistent functionality between types

As I said before, entities have a standard interface. They have URIs, labels, and you can use a standard function to load them. This means more flexible, reliable code.

Not having to work with Nodes

Not having to work with Nodes for every main chunk of data makes your architecture better. Separating Node functionality from your own module’s functionality leads to more stable code. Even contributed modules that abuse nodes won’t get in your way. And the multitude of hooks running on Node operations can be trimmed down.

The contrib Entity API Module

The confusingly named contrib Entity API module provides even more functionality than Drupal core. In addition to all the benefits mentioned above, it provides saving, deleting, and updating entities, along with a ton of extra functionality. We’ll talk about this in the next part of this series.

Related Links

Want to learn more about Entities? Here are some links to get you started.

  • Ronald Ashri of Istos has an excellent three part series on building entities.

Slides and Video

At Drupalcamp Montreal, I gave a presentation of most of this. The slides are embedded and the video is available here: Videos

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web