Allowing CCK to handle the weight of your form elements

Lately I've been working on a project to allow drupal to intelligently manage legacy data, to display, edit, and work with all aspects of the data as securely as possible. Naturally, it's difficult to say the least but I've learned a great deal. One of the things I thought was going to be a pain but ended up easy was managing where the fields appeared on a form. Yes, I could set the weights manually through the Forms API but CCK actually gives us some really great tools to do this without sweating.

For reference, this is based on the wonderful if totally impossible to find article here: The Great Pretender.

So the essence of getting non-CCK nodes into the CCK manage fields page is only two hooks. The hook_content_extra_fields($type) which registers which fields are available to be weighted (based on the node type found in $type), and slapping

content_extra_field_weight($node->type, $drupal_attr)

onto your #weight attribute in your hook_view for each field defined. The weight will already be available in the form without any intervention on your part.

Here's how I'm using the two:

function wrapper_view($node, $teaser = FALSE, $page = FALSE) {
  $metadata = get_metadata($node);
 
  $node = node_prepare($node, $teaser);
 
  if ($metadata['rw_attribute_mapping']){
    foreach ($metadata['rw_attribute_mapping'] as $drupal_attr => $legacy_attr) {
      $column_name = column_name($legacy_attr);
      $node->content[$drupal_attr] = array(
        '#value' => theme('section', array('title' => t(titleize($drupal_attr)), 
          'elements' => array(t($node->$column_name)))),
        '#weight' => content_extra_field_weight($node->type, $drupal_attr),
      );
    }
  }
 
  return $node;
}
 
function wrapper_content_extra_fields($type) {
  $node = new stdClass();
  $node->type = $type;  
  $metadata = get_metadata($node);
 
  $extras = array();
 
  if (!empty($metadata['rw_attribute_mapping'])) {
    foreach ($metadata['rw_attribute_mapping'] as $drupal_attr => $legacy_attr) {
      // Don't weight the title, drupal will do this for us
      if ($drupal_attr != 'title') {
        // Otherwise, give a weight to all other rw attrs
        $extras[$drupal_attr] = array(
          'label' => t(titleize($drupal_attr)),
        );
      }
    }    
  }
 
  return $extras;
}

Comments

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <cpp>, <java>, <php>. The supported tag styles are: <foo>, [foo].
  • Web page addresses and email addresses turn into links automatically.
  • Lines and paragraphs break automatically.

Ready for transformation?