Setting a CCK default value for old nodes

by jenny on 26 August 2008 - 9:21pm in

I added a brand-new cck field to a content type which already had a bunch of nodes, but previously had no cck fields. This new field needed to have a default value set for all existing nodes. Of course, editing an old node and saving it without making any changes would set an appropriate default value... but I couldn't manually do that for all the nodes.

Usually at this point, I'd go run a simple query on the content_type table to set a default value for all the nodes of that type. However, since this was the very first cck field for this content type, there were only a handful of entries in the content_type table (corresponding to nodes of this type that had been edited since adding the cck field). I needed a way to set a default for all nodes of this type.

I thought about just inserting an nid value for all the appropriate nodes into the table, but I wasn't sure where the vid value was coming from or how to generate it. After banging my head against the wall for quite some time, I finally realized that the nid and vid value pairs I was missing in my content_type table were sitting there in the node_revisions table the whole time:

select r.nid, r.vid from node_revisions r join node n on n.nid = r.nid where n.type = 'image';

I decided to only grab the latest vids (version ids), since that's what seemed to be happening upon an edit-and-save cycle:

select r.nid, max(r.vid) from node_revisions r join node n on n.nid = r.nid where n.type = 'image' group by r.nid;

...so long story short, I didn't need to generate anything, just copy the latest nid, vid pair over to my content_type table:

insert ignore into content_type_image (nid, vid) select r.nid, max(r.vid) from node_revisions r join node n on n.nid = r.nid where n.type = 'image' group by r.nid;

...which worked like a charm. MySQL was already configured by cck to give the default value I had in mind if none was specified, so I didn't need to go any further.

Note that the ignore directive to the insert command means leave alone any values that were already in this table... just insert the keys that didn't exist yet... which is exactly what we want in this case.