Skip to content

Instantly share code, notes, and snippets.

@jedateach
Created July 20, 2012 02:29
Show Gist options
  • Save jedateach/3148284 to your computer and use it in GitHub Desktop.
Save jedateach/3148284 to your computer and use it in GitHub Desktop.
Custom form field to model field mapping.
<?php
class MyForm extends Form{
/**
* Override saveInto to allow custom form field to model field mapping.
*/
function saveInto($dataObject,$fieldList = null){
$this->mapFieldNames($fieldList);
parent::saveInto($dataObject,$fieldList);
$this->restoreFieldNames($fieldList);
}
/**
* Override loadDataFrom to allow custom form field to model field mapping.
*/
function loadDataFrom($data,$clearMissingFields = false, $fieldList = null){
$this->mapFieldNames($fieldList);
parent::loadDataFrom($data,$clearMissingFields,$fieldList);
$this->restoreFieldNames($fieldList);
}
protected function mapFieldNames($fieldList){
if(!is_array($fieldList) || empty($fieldList))
return false;
//rename other fields temporarly, incase they get overwritten
$savableFields = $this->fields->saveableFields();
foreach($savableFields as $field){
$field->originalFieldName = $field->Name();
$field->setName($field->originalFieldName."_renamed");
}
foreach($fieldList as $formfield => $modelfield){
if(!is_int($formfield) && isset($savableFields[$formfield]) && $field = $savableFields[$formfield]){
$field->originalFieldName = $formfield;
$field->setName($modelfield);
}
}
}
protected function restoreFieldNames($fieldList){
if(!is_array($fieldList) || empty($fieldList))
return false;
foreach($this->fields->saveableFields() as $field){
if($field->originalFieldName){
$field->setName($field->originalFieldName);
$field->originalFieldName = null;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment