Created
July 20, 2012 02:29
-
-
Save jedateach/3148284 to your computer and use it in GitHub Desktop.
Custom form field to model field mapping.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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