public function setAttributeMetadataFromForm(AttributeForm $attributeForm) { $modelClassName = get_class($this->model); $attributeName = $attributeForm->attributeName; $attributeLabels = $attributeForm->attributeLabels; $elementType = $attributeForm->getAttributeTypeName(); $isRequired = (bool) $attributeForm->isRequired; $isAudited = (bool) $attributeForm->isAudited; $contactStatesData = $attributeForm->contactStatesData; $contactStatesLabels = $attributeForm->contactStatesLabels; $startingStateOrder = (int) $attributeForm->startingStateOrder; $contactStatesDataExistingValues = $attributeForm->contactStatesDataExistingValues; if ($contactStatesDataExistingValues == null) { $contactStatesDataExistingValues = array(); } if ($attributeForm instanceof ContactStateAttributeForm) { //update order on existing states. //delete removed states $states = ContactState::getAll('order'); $stateNames = array(); foreach ($states as $state) { if (in_array($state->name, $contactStatesData)) { $stateNames[] = $state->name; $state->order = array_search($state->name, $contactStatesData); $state->serializedLabels = $this->makeSerializedLabelsByLabelsAndOrder($contactStatesLabels, (int) $state->order); $saved = $state->save(); assert('$saved'); } elseif (in_array($state->name, $contactStatesDataExistingValues)) { $order = array_search($state->name, $contactStatesDataExistingValues); $state->name = $contactStatesData[$order]; $state->order = $order; $state->serializedLabels = $this->makeSerializedLabelsByLabelsAndOrder($contactStatesLabels, (int) $state->order); $saved = $state->save(); assert('$saved'); $stateNames[] = $state->name; } else { $stateNames[] = $state->name; $state->delete(); } } //add new states with correct order. foreach ($contactStatesData as $order => $name) { if (!in_array($name, $stateNames)) { $state = new ContactState(); $state->name = $name; $state->order = $order; $state->serializedLabels = $this->makeSerializedLabelsByLabelsAndOrder($contactStatesLabels, (int) $order); $saved = $state->save(); assert('$saved'); } } //Set starting state by order. ContactsUtil::setStartingStateByOrder($startingStateOrder); ModelMetadataUtil::addOrUpdateRelation($modelClassName, $attributeName, $attributeLabels, $elementType, $isRequired, $isAudited, 'ContactState'); } else { throw new NotSupportedException(); } }
public function testContactsUtilSetStartingStateByOrder() { $startingStateId = ContactsUtil::getStartingStateId(); $startingState = ContactState::getById($startingStateId); $startingState->delete(); $this->assertEquals(6, count(ContactState::GetAll())); ContactsUtil::setStartingStateByOrder(2); $startingStateId = ContactsUtil::getStartingStateId(); $states = ContactState::getAll('order'); $this->assertEquals($states[1]->id, $startingStateId); $startingState = ContactState::getByName('Recycled'); $this->assertEquals(1, count($startingState)); $this->assertEquals($startingState[0]->id, $startingStateId); }