Symfony 1.1 Time/Code Saver using Model->fromArray()
I found a pretty nice time and code saver in the fromArray() method. Currently, we’re translating our arrays from the form’s POST data into what works for the models’ fromArray() method.
Here’s an example:
$pet_txt->fromArray(array(
“PetInfoId” => $params[‘pet_info_id’],
“VetInfo” => $params[‘vet_info’],
“SpecialCare” => $params[‘special_care’],
));
Apparently there’s an easier way:
$pet_txt->fromArray($params, BasePeer::TYPE_FIELDNAME);
What that does is use the underscored field_name style rather than the default CamelCase TYPE_PHPNAME when inserting the new variables. Please note that fromArray() will only insert the parts of the array that match the model (ie. ‘password’ won’t get set on the Pet model). It will also overwrite anything you’ve set previously.
If you need to set other keys that are not in the array, you can use the Model->setFieldName() methods, or you can use Model->setByName(‘pet_id’, $params[‘pet_id’], BasePeer::TYPE_FIELDNAME).
Here’s the other options available:
/**
* phpname type
* e.g. ‘AuthorId’
*/
const TYPE_PHPNAME = ‘phpName’;
/**
* column (peer) name type
* e.g. ‘book.AUTHOR_ID’
*/
const TYPE_COLNAME = ‘colName’;
/**
* column fieldname type
* e.g. ‘author_id’
*/
const TYPE_FIELDNAME = ‘fieldName’;
/**
* num type
* simply the numerical array index, e.g. 4
*/
const TYPE_NUM = ‘num’;