Drupal bad practices

Fri, 2014-05-09 18:47

Below is a list of bad practices I have seen from other people and myself. Feel free to comment if you have your own thoughts.

You are a bad Drupal developer if:

  • You have no idea what is the difference between uninstalling a disabling a module

  • Remember - Disabling module does not remove any database tables from the database, nor remove any variables the module might have stored. You must disable a module to uninstall it. Uninstalling will remove any tables defined using hook_schema, and it will also invoke hook_uninstall which modules use to remove their variables and other data.

  • You abuse variable_set() and system_settings_form

  • It's really easy to store a variable or create a settings form using them, but storing tons of data will cause your site to hold all the data in memory for each and every page request.

  • You don't really use Form API's #tree property.

  • If you want to get the values in form values array in a structured way, go ahead and use #tree property.
    When creating configuration forms that you store values Drupal core variable system, note that you can throw anything to the database. Drupal will serialize your data anyway. If you have forms that has dynamic number of variables to store (per-node-type configurations, etc), consider using the #tree in the parent fieldset. This will put only a few rows to the the variable table, and will perform faster in when unseriazing data.

    Example (don't do this!):

  $form = array();
  $types = node_type_get_names();
  foreach ($types as $type => $label) {
    $form['my_module_config_' . $type] = array(
      '#type' => 'select',
      '#options' => drupal_map_assoc(range(1, 10)),
      '#title' => t('Select value for %type', array('%type' => $label)),
      '#default_value' => variable_get('my_module_config_' . $type, 5),
    );
  }

  return system_settings_form($form);

Above snippet simply gets the list of node types available, and adds a select list for each node type.
Why this bad:

  • Many rows in the variable table
  • It's good in performance to unserialize() a large array than unserialize a number of small elements.
  • Deleting a node type will not remove the row from the variable table unless you hook into that process as well.
  • Form is ugly

Do this:

  $form = array();
  $types = node_type_get_names();
  $form['my_module_config_node'] = array(
    '#type' => 'fieldset',
    '#title' => 'Node type configuration',
    '#tree' => TRUE, //  $label) {
    $form['my_module_config_node'][$type] = array(
      '#type' => 'select',
      '#options' => $opts,
      '#title' => t('Select value for %type', array('%type' => $label)),
      '#default_value' => !empty($values[$type]) ? $values[$type] : 5,
    );
  }

  return system_settings_form($form);

Why this is good:

  • Only one row in the variable table
  • Requires only one unserialize() call.
  • If you delete a node type, it will be removed when saving the form next time
  • Only one variable_del('my_module_config_node') in hook_uninstall.
  • It's sexy to have fieldsets and big arrays. Drupal is all about giant arrays after all.

Even if you use system_settings_form, you can add your own form validation hooks to alter $form_state['values'] before saving them to database.

  • You use t() function in your installation hooks, hook_schema and hook_menu

  • Note that t() won't work well during installation. Also, don't wrap your schema definition labels with t() function calls. It's no use unless you are looking for some troubles. Same goes to hook_menu implementations. Drupal will pass the title and description to t() function automatically unless you override the title callback.

  • Don't use user_access() frequently enough

  • Don't check if the user has a particular role, path checks, or anything to work around an access check. Use user_access() to check proper permissions.

  • You edit the tpl.php file in module folder

  • Some modules provide template files to make it easier for you to override the default output. Copy the template file from the module to your theme's templates folder and make your changes in the copied file.

  • Drupal core is >=7.x and you still call drupal_add_js() and drupal_add_css()

  • It works, right? Not always. Cached pages won't probably have the the assets because you are not attaching them what Drupal tends to cache. Use #attached property to attach the assets in a cache-friendly way.

  • You haven't used #states at all and you still think your forms are sexy

  • Make your forms sexier without any single line or JavaScript. See the awesome documentations here and here.

  • You can't live without PHP module in core or Views PHP module

  • For the 132,946th time, don't enable PHP module, and try your best to avoid putting PHP snippets in the database. If you need a special Views field, filter or sort handler, just extend the most matching handler and ut your precious PHP code there. PHP in a block ? hook_block_info / hook_block_view. PHP in a node ? hook_menu, and a custom page callback.

  • You always use mail() function directly to send emails

  • It's just a drupal_mail call and a hook_mail implementation. Don't use mail() or call the send method in the mail class directly.

  • You don't enable CSS and JS aggregation in Drupal core

  • I live in the country that has cheapest access to the Internet (though I doubt the quality is good). No regular use wants to know how well commented your CSS files are. If you have forgotten, go to Administer > Site Configuration > Development > Performance and enable CSS/JS aggregation. If your site is broken after that, see my point above to not use drupal_add_js and drupal_add_css.

  • You have 10+ roles in your site

  • Slideshow manager, Developer, Administrator, Blog writer, Junior Blog writer, Content approver, Backup maker... it's messy isn't it?

    Edit: Removing this item. Number of roles will depend on the requirement, but nonetheless, try to keep the number of roles as little as possible. It will not only make administering permissions easier, but also the server use less memory (permissions are cached in a static array indexed by the roles the current user has. If you have too similar roles with a large number of granted permissions, that can make the memory use slightly high). Also see user_role_permissions().

  • phpmyadmin cries internally when you SHOW TABLES

  • Reuse the fields as they match, uninstall modules properly, and don't host all your sites in a single database.

  • You have Colorbox, Shadowbox, Views Slideshow and 10 more modal and slideshow plugins enabled

  • Note that many of those module tend to add the assets even if you don't use it anywhere. Try to keep the number of such module low and reuse them.

    You are probably not aware about this, but ctools module comes with an awesome modal framework. Custom forms, in-modal-form validation, graceful degradation, and almost everything Chuck Norris might need.

  • You include jQuery in a tpl.php file

  • The demo web page of almost every 989,947 jQuery plugins out there, they include jQuery in the page source. If you are copying anything from that demo file, don't copy jQuery. It comes with Drupal core, and reusing it can save you nearly 70kb of page size.

  • You have several page-* and node-*tpl.php files

  • For smaller variants, implement hook_preprocess_node in your theme and make those changes. You can change, remove and add custom elements there. Besides, adding too much logic to tpl.php files is not a very good idea either.

  • variable_set() calls in regular page loads

  • Note that if you change a variable, Drupal has to refresh its caches which can add up a lot of time. Doing it on each page is nearly a disaster.

    Comments

    Good stuff man, just keep posting more valueble points in drupal, meny thanks!

    Heya! I realize this is kind of off-topic but I needed to
    ask. Doees managing a well-established blog such as yours require a massive amount work?

    I am completely new to operating a blog but I ddo write in my journal every day.
    I'd like too start a blog so I can easily share my personal experience and feelings online.
    Please let me know if you hae any idea or tips for brand new asspiring bloggers.
    Thankyou!

    decrease of weight, lack of inches, or lower body fat percentage,
    this could indicate a desire to re-evaluate your plan and efforts.
    It's important that you are tracking how many calories you adopt in on a daily basis because that will make an extremely large difference in how much quicker it is possible to
    get a flat stomach. Drink Water-- The only liquid you ought to drink is water.

    Somebody essentially help to make seriously posts I'd state.
    This is the first time I frequented your website page and up to now?

    I surprised with the research you made to create this particular publish extraordinary.

    Fantastic job!

    God desires to break you out and break you into a new life.
    So would you like to understand the best way to get the very best iPhone Themes?
    With that said, there's a pattern that more android programmers will get to the trade.

    Save your money for something more worthwhile as the asking price simply
    doesn't out-weigh, let alone come close to matching, the benefits.
    They have succeeded in getting the gold mining town of Redding hooked on their products, which
    has resulted in their effectively owning the main supply of gold coinage produced in the Wasteland.
    Another option may be your local bank, the one that knows everything about
    you including your financial history, current holdings,
    and existing bank account.

    But there isn't a magic to steroids.

    For lateszt news you have to pay a quick visit
    internet and onn the web I found this web site as a best wweb site for latest updates.

    I love ont tendance à être trop. Ce type de rapports!
    Gardez les superbes travaille les gars, je suis
    ajout vous les gars à mon propre blogroll.

    Hello there! I know this is kinda off topic but I was wondering if you knew where I could
    find a captcha plugin for my comment form? I'm using the same blog platform as
    yours and I'm having difficulty finding one? Thanks a lot!

    There's certainly a lot to learn about this issue. I like all of the points you've
    made.

    I was recommended this blog by my cousin. I'm not sure whether
    this post is written by him as no one else know such detailed
    about my trouble. You're wonderful! Thanks!

    What's up, just wanted to tell you, I loved this article.
    It was helpful. Keep on posting!

    My brother recommended I might like this blog.
    He used to be totally right. This post truly made
    my day. You cann't believe just how a lot time I had spent for this information! Thanks!

    I love it when people come together and share opinions.
    Great site, stick with it!

    Hello! I could have sworn I've been to this site before but
    after going through many of the articles I realized it's new to
    me. Anyways, I'm definitely delighted I came across it and I'll be bookmarking it and checking back frequently!

    Spot on with this write-up, I really feel this web site needs much more attention. I'll probably be back again to
    see more, thanks for the info!

    Get out off debt today. Bankruptcy is a dirty scary word. But once yoou learn the ins and outs of bankruptcy it iss not so scary anymore.

    In fact, yyou may conclude it is your best chance at startinmg a new
    future.

    Superb post however I was wondering if you could write a litte more on this subject?

    I'd be very grateful if you could elaborate a little bit further.

    Bless you!

    My spouse and I stumbled over here different web address and thought I might check things out.
    I like what I see so i am just following you. Look forward to finding out about your web page again.

    Effectively intended as a piece of propaganda, the artist has
    proven the Emperor mounted on a 'fiery steed' against an ominous sky.

    Greate article. Keep posting such kind of info on your page.
    Im really impressed by your site.
    Hey there, You've done an incredible job. I'll definitely digg it and personally recommend
    to my friends. I am sure they'll be benefited from this website.

    It's an amazing piece of writing for all the online people; they
    will obtain benefit from it I am sure.

    Everyone loves it whenever people get together and share thoughts.

    Great blog, keep it up!

    It's going to be end of mine day, but before finish I am reading this wonderful piece of
    writing to improve my knowledge.

    Hi! Quick question that's completely off topic. Do you know how
    to make your site mobile friendly? My site looks weird when viewing from my
    apple iphone. I'm trying to find a template or plugin that might be able to resolve this issue.
    If you have any recommendations, please share. Appreciate it!

    I simply could not depart your web site before suggesting that I really enjoyed the standard information an individual provide in your
    visitors? Is gonna be again ceaselessly in order to check out new posts

    Hey There. I found your blog using msn. This is
    a really well written article. I'll be sure to bookmark it and come
    back to read more of your useful info. Thanks for the post.
    I will definitely comeback.

    I was curious if you ever thought of changing the structure
    of your site? Its very well written; I love what youve got to say.
    But maybe you could a little more in the way of content so people could connect with
    it better. Youve got an awful lot of text for only having 1 or two images.
    Maybe you could space it out better?

    Thanks for another magnificent post. The place else could anyone
    get that kind of information in such an ideal manner of writing?
    I've a presentation subsequent week, and I am at the look for such
    info.

    Awesome article.

    I have been exploring for a little bit for any high quality articles or blog posts on this sort of house .
    Exploring in Yahoo I finally stumbled upon this website. Reading this info So i'm
    happy to exhibit that I've a very just right uncanny feeling I
    found out just what I needed. I most for sure will make
    certain to do not put out of your mind this website and give it a look regularly.

    That is a really good tip especially to those fresh to the
    blogosphere. Brief but very precise info… Many thanks for sharing this one.
    A must read article!

    That is a great tip especially to those new to the
    blogosphere. Short but very precise information… Thanks for sharing this one.
    A must read article!

    You really make it appear so easy with your presentation but I to find this matter
    to be actually something which I think I would by no means
    understand. It seems too complicated and extremely large for me.

    I am taking a look forward to your next submit, I will attempt to get the hang of it!

    I don't even know the way I stopped up right here, however I thought this post used to be great.
    I do not realize who you might be but certainly you are going to a famous blogger should you
    aren't already. Cheers!

    It's going to be ending of mine day, except before ending I am reading this great article to improve my experience.

    I'm truly enjoying the design and layout of your site.
    It's a very easy on the eyes which makes it
    much more enjoyable for me to come here and visit more often. Did you hire out a designer to create your theme?

    Fantastic work!

    Hi Dear, are you in fact visiting this web page daily, if so after
    that you will without doubt obtain pleasant know-how.

    I'm really inspired along with your writing talents and also with the format in your weblog.
    Is this a paid subject matter or did you customize it yourself?

    Either way stay up the excellent high quality writing,
    it's rare to peer a nice blog like this one these days..

    After I initially commented I seem to have clicked on the -Notify me when new comments are added- checkbox and from now on every time a comment is added I recieve
    4 emails with the same comment. Is there a way you can remove me from that service?
    Cheers!

    Having read this I believed it was really enlightening.
    I appreciate you finding the time and energy to put this informative article together.
    I once again find myself spending way too much time both reading
    and leaving comments. But so what, it was still worthwhile!

    Hello Dear, are you in fact visiting this website regularly, if so after that you will without doubt get fastidious experience.

    WOW just what I was looking for. Came here by
    searching for http://finance.yahoo.com/news/vitapulse-reviews-important-news-reported-...

    I think this is one of the most significant info
    for me. And i'm glad reading your article. But wanna remark on few general things, The site style is ideal, the articles is really excellent : D.
    Good job, cheers

    I am sure this piece of writing has touched all the internet people, its
    really really fastidious piece of writing on building up new
    web site.

    Hi, I check your new stuff daily. Your writing style is awesome, keep it up!

    Thanks on your marvelous posting! I certainly enjoyed
    reading it, you will be a great author.I will be sure to bookmark your blog and will eventually come back later in life.
    I want to encourage one to continue your great posts, have a nice afternoon!

    I've read several excellent stuff here. Definitely price bookmarking for revisiting.
    I surprise how much attempt you put to make any such magnificent informative web site.

    Hey there I am so glad I found your webpage, I really found you by accident, while I was searching on Bing for something else,
    Nonetheless I am here now and would just like to say kudos for a incredible post and
    a all round exciting blog (I also love the theme/design), I don’t have time to look over it all
    at the moment but I have book-marked it and also added your RSS feeds,
    so when I have time I will be back to read much more, Please do
    keep up the excellent jo.

    Pages