Restored guide

Programmatically Create CCK Node Has ImageField

Archived 2008–2011 · 2 min read · Eric London's Drupal Blog

The original entry lived on this blog between 2008 and 2011. The explanation here is rewritten from public Drupal APIs so the same path can be read again. The note is titled “Programmatically Create CCK Node Has ImageField” and is written for Drupal 6.x unless a line below says otherwise.

What you are solving

Image work in this era means ImageCache presets, ImageField, and a derivative that is generated on demand. Generate heavy presets from Drush or a queue so a single anonymous page view does not exhaust the PHP memory limit. The moving parts in the historical title are: programmatically, create, cck, node, has, imagefield.

APIs and modules in play

  • Content Construction Kit, content_fields(), and field widgets
  • ImageField attached to a CCK node

A practical approach

  1. Step 1. Name the outcome in one sentence: Programmatically Create CCK Node Has ImageField.
  2. Step 2. Reproduce it on a development copy with the same modules enabled.
  3. Step 3. Keep the change in a custom module or in the theme, and leave contributed code untouched.
  4. Step 4. Define the preset (scale, crop, or scale-and-crop) before you write code that assumes a derivative path.
  5. Step 5. Flush only the presets you changed, and generate them from CLI when the source images are large.

Example

The sample is illustrative. Rename the function, swap in your machine names, and run it on a development copy.

// Programmatically Create CCK Node Has ImageField
function notes_programmatically_create_cck_node_has_imagefield_preset_url($filepath, $preset = 'thumbnail') {
  $preset = check_plain($preset);
  return file_create_url('imagecache/' . $preset . '/' . $filepath);
}

Check before you deploy

  • Confirm the change on a database copy, then again with the theme registry and page cache cleared.
  • Watch the PHP error log and the watchdog table for the first real request.
  • If the change alters markup, recheck the path with a keyboard and without JavaScript.

Restored guide. The original post was published by Eric London on this domain. This text is a new explanation of that subject, not a reproduction of the archived wording.