示例#1
0
 function save_field()
 {
     if (!isset($this->_data['DatasetField'])) {
         $this->dataError();
         sendBack();
     }
     $dataset = $this->_uses[$this->modeltype];
     $data = $this->_data['DatasetField'];
     $data['old_name'] = $data['name'];
     $data['name'] = strtolower(str_replace(' ', '_', $data['title']));
     if (!empty($data['module_component_id'])) {
         $data['name'] .= '_id';
         $data['type'] = $dataset::get_fk_field_type();
     }
     $booleans = array('mandatory', 'searchable', 'display_in_list');
     foreach ($booleans as $field) {
         if (!isset($data[$field])) {
             $data[$field] = FALSE;
         } else {
             $data[$field] = TRUE;
         }
     }
     $db = DB::Instance();
     $flash = Flash::Instance();
     $errors = array();
     if (empty($data['id'])) {
         $action = 'add';
     } else {
         $action = 'alter';
         $current_field = DataObjectFactory::Factory('DatasetField');
         $current_field->load($data['id']);
     }
     $db->StartTrans();
     $dataset->load($data['dataset_id']);
     if ($data['mandatory']) {
         $model = $this->newModel($dataset);
         $cc = new ConstraintChain();
         if ($action == 'alter') {
             $cc->add(new Constraint($data['name'], 'IS', 'NULL'));
         }
         if ($model->getCount($cc) > 0) {
             if (!$action == 'alter') {
                 $errors[] = 'Data exists so first add the field then make it mandatory';
             } elseif ($data['default_value'] == '') {
                 $errors[] = 'Default Value required to make this field mandatory';
             } else {
                 $collection = new DataObjectCollection($model);
                 $sh = new SearchHandler($collection);
                 $sh->addConstraintChain($cc);
                 if (!$collection->update($data['name'], $data['default_value'], $sh)) {
                     $errors[] = 'Error updating existing data for ' . $data['title'] . ' with default value';
                 }
             }
         }
     }
     $datasetfield = DataObject::Factory($data, $errors, 'DatasetField');
     // TODO: if this is an update, only change table if field details have changed
     // otherwise do the change table to add the new field
     if (count($errors) > 0 || !$datasetfield || !$datasetfield->save() || !$this->change_table($data, $action)) {
         $errors[] = 'Error ' . (action == 'alter' ? 'updating' : 'inserting') . ' ' . $data['title'] . ' field definition : ' . $db->ErrorMsg();
         $db->FailTrans();
         $db->CompleteTrans();
     } else {
         $db->CompleteTrans();
         $this->createOverview($dataset, $errors);
     }
     if (count($errors) > 0) {
         $flash->addErrors($errors);
     } else {
         $flash->addMessage('"' . $data['title'] . '" field saved OK');
     }
     sendTo($this->name, 'view', $this->_modules, array($dataset->idField => $data['dataset_id']));
 }