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.

    My developer is trying to persuade me to move
    to .net from PHP. I have always disliked the idea
    because of the expenses. But he's tryiong none the less.

    I've been using Movable-type on several websites for about a year and am
    concerned about switching to another platform.

    I have heard great things about blogengine.net. Is there a way I
    can import all my wordpress content into it? Any help would be greatly appreciated!

    La salle Party est propriétaire des tournois World Poker Tour.

    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.

    I'd like to find out more? I'd like to find
    out more details.

    I read this paragraph fully concerning the resemblance of hottest and preceding technologies, it's remarkable article.

    Good post. I learn something totally new and challenging on websites I stumbleupon every day.
    It's always interesting to read articles from other authors and use a little something from other sites.

    Have you ever thought about adding a little bit more than just your articles?
    I mean, what you say is valuable and everything.
    Nevertheless imagine if you added some great images 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 greatest in its field.
    Very good blog!

    Our Master of Scientific research in Advertising program has a number of trainee ambassadors hired to offer assistance and also information through e-mail
    for possible or new pupils on numerous subjects such as
    the Dallas environment, housing, living expenses, scholastic and social
    life.

    I read tis paragraph completely about the comparison of hottest and previous
    technologies, it's awesome article.

    I was recommended thyis website byy mү cousin. ӏ'm
    not ѕure ѡhether thіs post is written ƅy ɦim as nobߋdy eⅼse know ѕuch detailed аbout my trouble.
    Үou aгe incredible! Thanks!

    Highly energetic article, I loved that bit. Will there be a part
    2?

    This is very interesting, You're a very skilled blogger.
    I've joined your feed and look forward to seeking more of your
    fantastic post. Also, I have shared your web site in my social networks!

    Thank you, I've just been searching for information approximately this subject for a
    while and yours is the best I've discovered till now. However, what concerning the bottom line?
    Are you certain concerning the source?

    Very good post! We are linking to this particularly
    great post on our site. Keep up the great writing.

    Hi my family member! I wish to saay that this post is awesome, great written and come
    with almost all iimportant infos. I'd like to see more posts like this .

    Hey very interesting blog!

    Saved as a favorite, I really like your website!

    A person essentially lend a hand to make seriously posts I would state.
    That is the first time I frequented your web page and thus far?
    I surprised with the analysis you made to make this particular put up extraordinary.
    Magnificent job!

    * If possible, install your automatic washer on either the other floor
    of your property or inside the basement to relieve the impact and harshness
    of damage if failure were to occur. Flood barriers are
    one with the most effective ways of preventing flood waters from entering your house.
    Water damage repair companies have to basically be capable of perform according towards demand and requirement in the work.

    Woah! I'm really enjoying the template/theme of this site.
    It's simple, yet effective. A lot of times it's very hard to get that "perfect balance" between user friendliness and visual appearance.
    I must say you have done a fantastic job with this.
    In addition, the blog loads very fast for me on Chrome.
    Superb Blog!
    Hi, i think that i saw you visited my blog so i came to “return the favor”.I'm attempting to find things to enhance my
    web site!I suppose its ok to use a few of y
    \

    It's simply not one of the most powerful cooler on the planet and also it
    lcks height adjustment, so ensure you obtain comfy due to the faht that the Havit HV-F2056 won't do you
    any favors because division.

    Pretty nice post. I just stumbled upon your blog and wished to say that I've truly enjoyed surfing
    around your blog posts. In any case I will be subscribing to your
    feed and I hope you write again soon!

    I’m not that much of a online reader to be
    honest but your sites really nice, keep it up! I'll go ahead and bookmark your website to come back down the road.
    Cheers

    I really like your blog.. very nice colors & theme. Did you
    make this website yourself or did you hire someone to do it for you?
    Plz respond as I'm looking to design my own blog and would like to find out where
    u got this from. kudos

    Howdy! Do you know if they make any plugins to assist with SEO?

    I'm trying to get my blog to rank for some targeted keywords but I'm not seeing
    very good results. If you know of any please
    share. Thank you!

    I really did not notice too much difference,
    other than it should have been better for towing and hauling.

    Previously on double cab models, the reverse opening rear doors could not be opened when the front doors were closed.
    An increasing share of pickup trucks sold by all manufacturers
    each year are crew cab models that are being purchased to
    be used for work and play interchangeably by families - making the crew cab pickup
    truck the new family vehicle of choice.

    2-liter (available only on SLT and Denali trims) delivers 420 hp and 460 lb.
    The new Sierra has been a long time coming and GMC truck
    enthusiasts have been patient year after year as the 'other guys' brought new trucks to market leaving
    the Sierra brand getting a bit longer in the tooth year after year.
    An increasing share of pickup trucks sold by all manufacturers each year
    are crew cab models that are being purchased to be used
    for work and play interchangeably by families - making the crew cab
    pickup truck the new family vehicle of choice.

    Hey there! Do you use Twitter? I'd like to follow you
    if that would be okay. I'm undoubtedly enjoying your blog and look forward
    to new posts.

    Pages

    Your thoughts