Thursday, September 18, 2008

Setting a field value by its fieldname (Archetypes)

Suppose you have a long list of fieldnames that you want to change on an Archetypes content type. You might want to do obj.setField1(), obj.setField2() etc. for all these fields, but it would be nicer to pass in a list of fieldnames. This is possible on Archetypes content types as follows:

# the fields to be set are in a dictionary adres_dict
for fieldname in adres_dict.keys():
# value to be set on the field
value = adres_dict[fieldname]
# get the field from the schema
field = obj.Schema().getField(fieldname)
# get the mutator name
mutator = field.mutator
# get the mutator function
func = getattr(obj, mutator)
# set the value using the mutator function
func(value)
print " Inserted value %s into field %s" % (value,fieldname,)

No comments: