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 am really impressed with your writing skills as well as with the layout on your weblog.
    Is this a paid theme or did you customize it yourself?

    Anyway keep up the excellent quality writing,
    it is rare to see a great blog like this one these days.

    Hi there, I discovered your blog by the use of Google while searching for
    a comparable subject, your web site got here up, it appears to be like good.

    I have bookmarked it in my google bookmarks.
    Hello there, just turned into aware of your weblog thru Google,
    and located that it is truly informative. I am going to be careful for brussels.
    I'll be grateful if you happen to continue this in future.
    A lot of people will be benefited from your writing.

    Cheers!

    Please let me know if you're looking for a writer for your blog.
    You have some really great articles and I think I would be a good asset.

    If you ever want to take some of the load off, I'd absolutely love to write some content for your
    blog in exchange for a link back to mine.
    Please blast me an e-mail if interested. Many thanks!

    I am really enjoying the theme/design of your weblog. Do you ever run into any browser compatibility issues?
    A small number of my blog readers have complained about
    my site not operating correctly in Explorer but looks
    great in Chrome. Do you have any recommendations to help fix this issue?

    Peculiar article, exactly what I wanted to find.

    This web site truly has all the information and facts
    I wanted about this subject and didn't know who
    to ask.

    Thanks very interesting blog!

    I am regular visitor, how are you everybody? This post posted at this website is really nice.

    Loving the info on this site, you have donne great job
    on the blog posts.

    Hi there, You've done an incredible job. I will definitely digg it and personally suggest
    to my friends. I am confident they will be benefited from this
    web site.

    Helpful information. Lucky me I discovered your web
    site by chance, and I'm stunned why this twist of fate
    didn't came about in advance! I bookmarked it.

    Great post.

    I absolutely love your blog and find most of your post's to be precisely what I'm
    looking for. Would you offer guest writers to write content to suit your needs?
    I wouldn't mind producing a post or elaborating on a number of
    the subjects you write concerning here. Again, awesome web log!

    ハロー!自分は少しクールな男です。最近かなりつらい悩みを持っています。ですからちょっと負の毎日です。その悩みというのは、僕しかわからない包茎のことです。今から20年前でした。中学2年の時に修学旅行がありました。泊りだからみんなで温泉に入るときがありました。クラスごとに風呂に行ったんです。みんなでチェックし合いをしました。私だけが、包茎だったのです。20歳を超えてからでも、あの温泉ときに見られた恥ずかしさは絶対に消し去ることができません。ですが自分は包茎手術をやることにしました。包茎手術ができるところは全国的にあります。特に気になっているのは、ABCクリニックか上野クリニックですね。まず、うちから近いっていうのが決め手ですね。あとは、施術のお金が安いことです。でも急に施術するのは不安ですから、電話相談をしてみようと思います。ABCクリニックに行って相談しようかなと思います。

    Pretty section of content. I just stumbled uon your website and in accession capital to assert that I get in fact enjoyed account
    your blog posts. Any way I'll be subscribing to your augment and evesn I achievement you access consistently
    fast.

    An outstanding share! I've just forwarded this onto a colleague who
    had been conducting a little research on this.
    And he actually ordered me lunch because I stumbled upon it for him...
    lol. So let me reword this.... Thanks for the meal!!
    But yeah, thanks for spending the time to discuss this issue here on your web site.

    Why viewers still make use of to read news papers when in this
    technological globe all is available on web?

    I was curious if you ever considered changing the page layout of
    your website? 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 one or 2 pictures.
    Maybe you could space it out better?

    Ridiculous story there. What happened after? Thanks!

    What i do not understood is actually how you are no longer really much more smartly-liked than you may be right now.
    You're so intelligent. You understand therefore significantly in the case of
    this subject, made me in my view imagine it from so many varied
    angles. Its like women and men are not involved until it's something to accomplish with Girl gaga!
    Your individual stuffs great. All the time maintain it up!

    What's up to every single one, it's truly a pleasant for
    me to pay a visit this web page, it includes valuable Information.

    At this point, a movie studio might have to torch its headquarters, contribute its merchandising sales to
    charity, and create a seven-hour art film performed in Ukrainian sign language to do
    something that truly qualified as a gesture that is subversive.

    Way cool! Some very valid points! I appreciate you penning this post plus the rest of the site is extremely good.

    Merely a smiling visitor here to share the love (:, btw great
    layout.

    For latest news you have to pay a visit the web and on world-wide-web I found this
    web page as a most excellent web site for most up-to-date updates.

    You have brought up a very exxcellent points, thank you for the post.

    I was curious if you ever considered 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 one or 2 pictures.
    Maybe you could space it out better?

    After going over a few of the articles on your web site, I seriously like
    your technique of blogging. I book marked it to my bookmark website list and will be checking back soon. Please check out
    my web site as well and let me know how you feel.

    It's very trouble-free to find out any matter on net as compared to textbooks, as I found
    this post at this site.

    Hey there! This is my first visit to your blog!
    We are a collection of volunteers and starting a new initiative in a
    community in the same niche. Your blog provided us useful information to work on. You have
    done a extraordinary job!

    As for novice involvement in collectibles, it
    can be very risky business from an investing and financial
    point of view. Other critical information to include in the web pages are shipping policy, terms of sale, refund and return policy, and other relevant information such as a privacy policy.
    The most effective way to think about SEO
    is as the glue that connects the customer with the business.

    That song is just not in the movie, but Straus says the first
    drafts of the script did comprise a scene in which Dr.
    Dre viciously assaults TV host Dee Barnes during a record release party.

    It's important to note that any marketing effort needs to be carefully planned.
    Add images, graphics and video increase conversion. Human nature survives intact on the virtual
    showroom and it must be woven into the cloth of all communications,
    on the internet or in particular person.

    Yesterday, while I was at work, my cousin stole my iphone and tested to see if
    it can survive a 30 foot drop, just so she can be a youtube sensation. My iPad is now broken and she has 83 views.
    I know this is completely off topic but I had to share it with someone!

    Have you ever considered about adding a little bit more than just your articles?

    I mean, what you say is fundamental and all.
    However think of if you added some great visuals or video clips to
    give your posts more, "pop"! Your content is excellent but
    with pics and videos, this blog could certainly be one of the best
    in its niche. Wonderful blog!

    I feel that is one of the such a lot viotal information for me.
    Andd i'm satisfied studying your article. But wanna statement on some basic things, The website style iss wonderful, the artiicles is in point of fact excellent : D.

    Good activity, cheers

    Pages

    Your thoughts