/** * Updates a particular model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id the ID of the model to be updated */ public function actionUpdate($id) { $model = $this->loadModel($id); $users = User::getNames(); $fields = Fields::model()->findAllByAttributes(array('modelName' => 'Product')); foreach ($fields as $field) { if ($field->type == 'link') { $fieldName = $field->fieldName; $type = ucfirst($field->linkType); if (is_numeric($model->{$fieldName}) && $model->{$fieldName} != 0) { eval("\$lookupModel={$type}::model()->findByPk(" . $model->{$fieldName} . ");"); if (isset($lookupModel)) { $model->{$fieldName} = $lookupModel->name; } } } } if (isset($_POST['Product'])) { $temp = $model->attributes; $model->setX2Fields($_POST['Product']); // generate history $action = new Actions(); $action->associationType = 'product'; $action->associationId = $model->id; $action->associationName = $model->name; $action->assignedTo = Yii::app()->user->getName(); $action->completedBy = Yii::app()->user->getName(); $action->dueDate = time(); $action->completeDate = time(); $action->visibility = 1; $action->complete = 'Yes'; $action->actionDescription = "Update: {$model->name}\n Type: {$model->type}\n Price: {$model->price}\n Currency: {$model->currency}\n Inventory: {$model->inventory}"; $action->save(); parent::update($model, $temp, '0'); } $this->render('update', array('model' => $model, 'users' => $users)); }
public function nameFields() { if (!isset($this->_nameFields)) { $this->_nameFields = array(); $this->_nameFields[] = Fields::model()->findByAttributes(array('fieldName' => 'firstName', 'modelName' => 'Contacts')); $this->_nameFields[] = Fields::model()->findByAttributes(array('fieldName' => 'lastName', 'modelName' => 'Contacts')); } return $this->_nameFields; }
protected function queryFields() { if (!isset(self::$_fields[$this->tableName()])) { // only look up fields if they haven't already been looked up if (get_class($this) === 'Product' || get_class($this) === 'Quote') { self::$_fields[$this->tableName()] = Fields::model()->findAllByAttributes(array('modelName' => get_class($this) . 's')); } else { self::$_fields[$this->tableName()] = Fields::model()->findAllByAttributes(array('modelName' => get_class($this))); } } //Yii::app()->db->createCommand()->select('*')->from('x2_fields')->where('modelName="'.get_class($this).'"')->queryAll(); }
public static function statusList() { $field = Fields::model()->findByAttributes(array('modelName' => 'Quotes', 'fieldName' => 'status')); $dropdown = Dropdowns::model()->findByPk($field->linkType); return json_decode($dropdown->options); /* return array( 'Draft'=>Yii::t('quotes','Draft'), 'Presented'=>Yii::t('quotes','Presented'), "Issued"=>Yii::t('quotes','Issued'), "Won"=>Yii::t('quotes','Won') ); */ }
* Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Powered by * X2Engine" logo. If the display of the logo is not reasonably feasible for * technical reasons, the Appropriate Legal Notices must display the words * "Powered by X2Engine". *****************************************************************************************/ ?> <?php echo '<div class="form no-border" style="float:left;width:590px;">'; $form = $this->beginWidget('CActiveForm', array('id' => 'accounts-form', 'enableAjaxValidation' => false)); $attributeLabels = $model->attributeLabels(); $fields = Fields::model()->findAllByAttributes(array('modelName' => 'Accounts')); if (isset($_GET['version'])) { $version = $_GET['version']; $version = FormVersions::model()->findByAttributes(array('name' => $version)); $sizes = json_decode($version->sizes, true); $positions = json_decode($version->positions, true); $tempArr = array(); foreach ($fields as $field) { if (isset($positions[$field->fieldName])) { $field->coordinates = $positions[$field->fieldName]; $field->size = $sizes[$field->fieldName]; $tempArr[] = $field; } } $fields = $tempArr; }
/** * Clean up custom field columns */ public static function tearDownAfterClass() { $fields = Fields::model()->findAllByAttributes(array('custom' => 1)); foreach ($fields as $field) { assert($field->delete()); } Yii::app()->db->schema->refresh(); Yii::app()->cache->flush(); Contacts::model()->refreshMetaData(); Contacts::model()->resetFieldsPropertyCache(); AuxLib::debugLogR('Contacts::model ()->getAttributes () = '); AuxLib::debugLogR(Contacts::model()->getAttributes()); parent::tearDownAfterClass(); }
/** * Creates contact record * * Call this function from createRecords */ public function createContact($model, $oldAttributes, $api) { $model->createDate = time(); $model->lastUpdated = time(); if (empty($model->visibility) && $model->visibility != 0) { $model->visibility = 1; } if ($api == 0) { parent::create($model, $oldAttributes, $api); } else { $lookupFields = Fields::model()->findAllByAttributes(array('modelName' => 'Contacts', 'type' => 'link')); foreach ($lookupFields as $field) { $fieldName = $field->fieldName; if (isset($model->{$fieldName})) { $lookup = X2Model::model(ucfirst($field->linkType))->findByAttributes(array('name' => $model->{$fieldName})); if (isset($lookup)) { $model->{$fieldName} = $lookup->id; } } } return parent::create($model, $oldAttributes, $api); } }
/** * @return array customized attribute labels (name=>label) */ public function attributeLabels() { $fields = Fields::model()->findAllByAttributes(array('modelName' => 'Products')); $arr = array(); foreach ($fields as $field) { $arr[$field->fieldName] = Yii::t('app', $field->attributeLabel); } return $arr; return array('id' => Yii::t('module', 'ID'), 'name' => Yii::t('module', 'Name'), 'description' => Yii::t('module', 'Description'), 'createDate' => Yii::t('module', 'Create Date'), 'lastUpdated' => Yii::t('module', 'Last Updated'), 'updatedBy' => Yii::t('module', 'Updated By')); }
* * You can contact X2Engine, Inc. P.O. Box 66752, Scotts Valley, * California 95067, USA. or at email address contact@x2engine.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Powered by * X2Engine" logo. If the display of the logo is not reasonably feasible for * technical reasons, the Appropriate Legal Notices must display the words * "Powered by X2Engine". *****************************************************************************************/ // get field names $fields = Fields::model()->findAllByAttributes(array('modelName' => 'Quote')); $attributeLabel = array(); $fieldType = array(); foreach ($fields as $field) { $attributeLabel[$field->fieldName] = $field->attributeLabel; $fieldType[$field->fieldName] = $field->type; } ?> <div class="row viewQuote" style="overflow: visible;" > <?php $viewButton = CHtml::link('[' . Yii::t('products', 'View') . ']', Yii::app()->createUrl('/quotes/quotes/view', array('id' => $quote->id)), array('title' => 'View Quote')); $strict = Yii::app()->params['admin']['quoteStrictLock']; $updateButton = $canDo['QuickUpdate'] ? ' ' . CHtml::link('[' . Yii::t('products', 'Update') . ']', 'javascript:void(0);', array('title' => 'Update Quote', 'onclick' => "x2.inlineQuotes.toggleUpdateQuote({$quote->id}, {$quote->locked}, " . ($strict ? 'true' : 'false') . ");")) : ''; $deleteButton = $canDo['QuickDelete'] ? ' ' . CHtml::ajaxLink('[' . Yii::t('quotes', 'Delete') . ']', Yii::app()->createUrl('/quotes/quotes/quickDelete', array('id' => $quote->id, 'recordId' => $recordId)), array('success' => "function(html) { x2.inlineQuotes.reloadAll(); }", 'beforeSend' => 'function(){ return confirm(' . json_encode(Yii::t('quotes', 'Are you sure you want to delete this quote?')) . ');
/** * Search X2Engine for a record. * * This is the action called by the search bar in the main menu. */ public function actionSearch() { ini_set('memory_limit', -1); $term = isset($_GET['term']) ? $_GET['term'] : ""; if (empty($term)) { $dataProvider = new CArrayDataProvider(array()); Yii::app()->user->setFlash('error', Yii::t('app', "Search term cannot be empty.")); $this->render('search', array('dataProvider' => $dataProvider)); } else { if (substr($term, 0, 1) != "#") { $modules = Modules::model()->findAllByAttributes(array('searchable' => 1)); $comparisons = array(); $other = array(); foreach ($modules as $module) { $module->name == 'products' ? $type = ucfirst('Product') : ($type = ucfirst($module->name)); $module->name == 'quotes' ? $type = ucfirst('Quote') : ($type = $type); $module->name == 'opportunities' ? $type = ucfirst('Opportunity') : ($type = $type); $criteria = new CDbCriteria(); $fields = Fields::model()->findAllByAttributes(array('modelName' => $type, 'searchable' => 1)); $temp = array(); $fieldNames = array(); if (count($fields) < 1) { $criteria->compare('id', '<0', true, 'AND'); } foreach ($fields as $field) { $temp[] = $field->id; $fieldNames[] = $field->fieldName; $criteria->compare($field->fieldName, $term, true, "OR"); if ($field->type == 'phone') { $tempPhone = preg_replace('/\\D/', '', $term); $phoneLookup = PhoneNumber::model()->findByAttributes(array('modelType' => $field->modelName, 'number' => $tempPhone, 'fieldName' => $field->fieldName)); if (isset($phoneLookup)) { $criteria->compare('id', $phoneLookup->modelId, true, "OR"); } } } if (Yii::app()->user->getName() != 'admin' && X2Model::model($type)->hasAttribute('visibility') && X2Model::model($type)->hasAttribute('assignedTo')) { $condition = 'visibility="1" OR (assignedTo="Anyone" AND visibility!="0") OR assignedTo="' . Yii::app()->user->getName() . '"'; /* x2temp */ $groupLinks = Yii::app()->db->createCommand()->select('groupId')->from('x2_group_to_user')->where('userId=' . Yii::app()->user->getId())->queryColumn(); if (!empty($groupLinks)) { $condition .= ' OR assignedTo IN (' . implode(',', $groupLinks) . ')'; } $condition .= 'OR (visibility=2 AND assignedTo IN (SELECT username FROM x2_group_to_user WHERE groupId IN (SELECT groupId FROM x2_group_to_user WHERE userId=' . Yii::app()->user->getId() . ')))'; $criteria->addCondition($condition); } if ($module->name == 'actions') { $criteria->with = array('actionText'); $criteria->compare('actionText.text', $term, true, "OR"); } if (class_exists($type)) { $arr = X2Model::model($type)->findAll($criteria); $comparisons[$type] = $temp; $other[$type] = $arr; } } $high = array(); $medium = array(); $low = array(); $userHigh = array(); $userMedium = array(); $userLow = array(); $records = array(); $userRecords = array(); $regEx = "/" . preg_quote($term, '/') . "/i"; foreach ($other as $key => $recordType) { $fieldList = $comparisons[$key]; foreach ($recordType as $otherRecord) { if ($key == 'Actions') { if ($otherRecord->hasAttribute('assignedTo') && $otherRecord->assignedTo == Yii::app()->user->getName()) { $userHigh[] = $otherRecord; } else { $high[] = $otherRecord; } } else { foreach ($fieldList as $field) { $fieldRecord = Fields::model()->findByPk($field); $fieldName = $fieldRecord->fieldName; if (preg_match($regEx, $otherRecord->{$fieldName}) > 0) { switch ($fieldRecord->relevance) { case "High": if (!in_array($otherRecord, $high, true) && !in_array($otherRecord, $medium, true) && !in_array($otherRecord, $low, true) && !in_array($otherRecord, $userHigh, true) && !in_array($otherRecord, $userMedium, true) && !in_array($otherRecord, $userLow, true)) { if ($otherRecord->hasAttribute('assignedTo') && $otherRecord->assignedTo == Yii::app()->user->getName()) { $userHigh[] = $otherRecord; } else { $high[] = $otherRecord; } } break; case "Medium": if (!in_array($otherRecord, $high, true) && !in_array($otherRecord, $medium, true) && !in_array($otherRecord, $low, true) && !in_array($otherRecord, $userHigh, true) && !in_array($otherRecord, $userMedium, true) && !in_array($otherRecord, $userLow, true)) { if ($otherRecord->hasAttribute('assignedTo') && $otherRecord->assignedTo == Yii::app()->user->getName()) { $userMedium[] = $otherRecord; } else { $medium[] = $otherRecord; } } break; case "Low": if (!in_array($otherRecord, $high, true) && !in_array($otherRecord, $medium, true) && !in_array($otherRecord, $low, true) && !in_array($otherRecord, $userHigh, true) && !in_array($otherRecord, $userMedium, true) && !in_array($otherRecord, $userLow, true)) { if ($otherRecord->hasAttribute('assignedTo') && $otherRecord->assignedTo == Yii::app()->user->getName()) { $userLow[] = $otherRecord; } else { $low[] = $otherRecord; } } break; default: if ($otherRecord->hasAttribute('assignedTo') && $otherRecord->assignedTo == Yii::app()->user->getName()) { $userLow[] = $otherRecord; } else { $low[] = $otherRecord; } } } elseif ($fieldRecord->type == 'phone') { $tempPhone = preg_replace('/\\D/', '', $term); if (strlen($tempPhone) == 10) { $phoneLookup = PhoneNumber::model()->findByAttributes(array('modelType' => $fieldRecord->modelName, 'number' => $tempPhone, 'fieldName' => $fieldName)); if (!in_array($otherRecord, $high, true) && !in_array($otherRecord, $medium, true) && !in_array($otherRecord, $low, true) && !in_array($otherRecord, $userHigh, true) && !in_array($otherRecord, $userMedium, true) && !in_array($otherRecord, $userLow, true)) { if (isset($phoneLookup) && $otherRecord->id == $phoneLookup->modelId) { if ($otherRecord->hasAttribute('assignedTo') && $otherRecord->assignedTo == Yii::app()->user->getName()) { $userHigh[] = $otherRecord; } else { $high[] = $otherRecord; } } } } } } } } } $records = array_merge($high, $medium); $records = array_merge($records, $low); $userRecords = array_merge($userHigh, $userMedium); $userRecords = array_merge($userRecords, $userLow); $records = array_merge($userRecords, $records); $records = Record::convert($records, false); if (count($records) == 1) { // Only one match, so go straight to it. // // The record's corresponding model class must have // X2LinkableBehavior for this to be possible. if (!empty($records[0]['#recordUrl'])) { $this->redirect($records[0]['#recordUrl']); } } $dataProvider = new CArrayDataProvider($records, array('id' => 'id', 'pagination' => array('pageSize' => Profile::getResultsPerPage()))); $this->render('search', array('records' => $records, 'dataProvider' => $dataProvider, 'term' => $term)); } else { Yii::app()->user->setState('vcr-list', $term); $_COOKIE['vcr-list'] = $term; $tagQuery = "\n SELECT * \n FROM x2_tags\n WHERE tag=:tag\n group BY tag, type, itemId"; $params = array(':tag' => $term); // group by type and itemId to prevent display of duplicate tags $sql = Yii::app()->db->createCommand($tagQuery); $totalItemCount = Yii::app()->db->createCommand("\n SELECT count(*)\n FROM ({$tagQuery}) as t1;\n ")->queryScalar($params); $results = new CSqlDataProvider($sql, array('totalItemCount' => $totalItemCount, 'sort' => array('defaultOrder' => 'timestamp DESC'), 'pagination' => array('pageSize' => Profile::getResultsPerPage()), 'params' => $params)); $this->render('searchTags', array('tags' => $results, 'term' => $term)); } } }
public function actionSearch() { ini_set('memory_limit', -1); $term = $_GET['term']; if (substr($term, 0, 1) != "#") { /*$contactsCriteria = new CDbCriteria(); $contactsCriteria->compare('firstName', $term, true, 'OR'); $contactsCriteria->compare('lastName', $term, true, 'OR'); $contactsCriteria->compare('name', $term, true, 'OR'); $contactsCriteria->compare('backgroundInfo', $term, true, 'OR'); $contactsCriteria->compare('email', $term, true, 'OR'); $contactsCriteria->compare('phone', $term, true, 'OR'); if(is_numeric($term)){ $temp=$term; $first=substr($temp,0,3); $second=substr($temp,3,3); $third=substr($temp,6,4); $contactsCriteria->compare('phone', "($first) $second-$third", true, 'OR'); $contactsCriteria->compare('phone', "$first-$second-$third", true, 'OR'); $contactsCriteria->compare('phone', "$first $second $third", true, 'OR'); $contactsCriteria->compare('phone2', "($first) $second-$third", true, 'OR'); $contactsCriteria->compare('phone2', "$first-$second-$third", true, 'OR'); $contactsCriteria->compare('phone2', "$first $second $third", true, 'OR'); } $contacts=Contacts::model()->findAll($contactsCriteria); $actionsCriteria=new CDbCriteria(); $actionsCriteria->compare('actionDescription',$term,true,'OR'); $actions=Actions::model()->findAll($actionsCriteria); $accountsCriteria=new CDbCriteria(); $accountsCriteria->compare("name",$term,true,"OR"); $accountsCriteria->compare("description",$term,true,"OR"); $accountsCriteria->compare('tickerSymbol',$term,true,'OR'); $accounts=Accounts::model()->findAll($accountsCriteria); $quotesCriteria=new CDbCriteria(); $quotesCriteria->compare("name",$term,TRUE,"OR"); $quotes=Quote::model()->findAll($quotesCriteria); $disallow=array( 'contacts', 'actions', 'accounts', 'quotes', );*/ $modules = Modules::model()->findAllByAttributes(array('searchable' => 1)); $comparisons = array(); foreach ($modules as $module) { $module->name == 'products' ? $type = ucfirst('Product') : ($type = ucfirst($module->name)); $module->name == 'quotes' ? $type = ucfirst('Quote') : ($type = $type); $criteria = new CDbCriteria(); $fields = Fields::model()->findAllByAttributes(array('modelName' => $type, 'searchable' => 1)); $temp = array(); foreach ($fields as $field) { $temp[] = $field->id; $criteria->compare($field->fieldName, $term, true, "OR"); } $arr = CActiveRecord::model($type)->findAll($criteria); $comparisons[$type] = $temp; $other[$type] = $arr; } $high = array(); $medium = array(); $low = array(); $records = array(); $regEx = "/{$term}/i"; foreach ($other as $key => $recordType) { $fieldList = $comparisons[$key]; foreach ($recordType as $otherRecord) { foreach ($fieldList as $field) { $fieldRecord = Fields::model()->findByPk($field); $fieldName = $fieldRecord->fieldName; if (preg_match($regEx, $otherRecord->{$fieldName}) > 0) { switch ($fieldRecord->relevance) { case "High": if (!in_array($otherRecord, $high) && !in_array($otherRecord, $medium) && !in_array($otherRecord, $low)) { $high[] = $otherRecord; } break; case "Medium": if (!in_array($otherRecord, $high) && !in_array($otherRecord, $medium) && !in_array($otherRecord, $low)) { $medium[] = $otherRecord; } break; case "Low": if (!in_array($otherRecord, $high) && !in_array($otherRecord, $medium) && !in_array($otherRecord, $low)) { $low[] = $otherRecord; } break; default: $low[] = $otherRecord; } } } } } $records = array_merge($high, $medium); $records = array_merge($records, $low); $records = Record::convert($records, false); $dataProvider = new CArrayDataProvider($records, array('id' => 'id', 'pagination' => array('pageSize' => ProfileChild::getResultsPerPage()))); $this->render('search', array('records' => $records, 'dataProvider' => $dataProvider, 'term' => $term)); } else { $results = new CActiveDataProvider('Tags', array('criteria' => array('condition' => 'tag="' . $term . '"'))); $this->render('searchTags', array('tags' => $results)); } }
<?php echo $form->error($model, 'modelName'); ?> </div> <div class="row"> <?php echo $form->labelEx($model, 'fieldName'); ?> <?php $modelSet = !empty($model->modelName); $fieldList = array(); $fieldOptions = array(); $customOrMod = false; if ($modelSet) { $fields = Fields::model()->findAll(array('order' => 'attributeLabel', 'condition' => 'modelName = :mn', 'params' => array(':mn' => $model->modelName))); foreach ($fields as $existingField) { $name = $existingField->fieldName; $fieldList[$name] = $existingField->attributeLabel; if ($existingField->custom == 1) { $fieldOptions[$name] = array('class' => 'field-option field-custom'); $customOrMod = true; } else { if ($existingField->modified == 1) { $fieldOptions[$name] = array('class' => 'field-option field-modified'); $customOrMod = true; } else { $fieldOptions[$name] = array('class' => 'field-option'); } } }
public function mergeLinkFields(X2Model $model, $logMerge = false) { $ret = array(); $linkFields = Fields::model()->findAllByAttributes(array('type' => 'Link', 'linkType' => get_class($model))); foreach ($linkFields as $field) { if ($logMerge) { $ids = Yii::app()->db->createCommand()->select('id')->from(X2Model::model($field->modelName)->tableName())->where($field->fieldName . ' = :id', array(':id' => $model->nameId))->queryColumn(); if (!empty($ids)) { $ret[$field->modelName]['field'] = $field->fieldName; $ret[$field->modelName]['ids'] = $ids; } } Yii::app()->db->createCommand()->update(X2Model::model($field->modelName)->tableName(), array($field->fieldName => $this->nameId), $field->fieldName . ' = :id', array(':id' => $model->nameId)); } return $ret; }
/** * Ensure that view/edit permissions are calculated and updated correctly. */ public function testUpdatePermissions() { //For some reason, re-using longTimeout preserves the state changes to //the private internal variables and makes this test fail, so using //shortTimeout role instead. $role = $this->role('shortTimeout'); $initialUsers = $role->getUsers(); $totalFields = Fields::model()->count(); //Test no permissions $role->setViewPermissions(array()); $role->setEditPermissions(array()); $role->save(); $this->checkPermissionUpdates($role, $totalFields, array(0, 0, $totalFields)); $this->assertEquals($initialUsers, $role->getUsers()); //Test all permissions $role->setViewPermissions(range(1, $totalFields)); $role->setEditPermissions(range(1, $totalFields)); $role->save(); $this->checkPermissionUpdates($role, $totalFields, array(0, $totalFields, 0)); $this->assertEquals($initialUsers, $role->getUsers()); //Test view-only permissions $role->setViewPermissions(range(1, $totalFields)); $role->setEditPermissions(array()); $role->save(); $this->checkPermissionUpdates($role, $totalFields, array($totalFields, 0, 0)); $this->assertEquals($initialUsers, $role->getUsers()); //Test bad input permissions $role->setViewPermissions(array()); $role->setEditPermissions(range(1, $totalFields)); $role->save(); $this->checkPermissionUpdates($role, $totalFields, array(0, 0, $totalFields)); $this->assertEquals($initialUsers, $role->getUsers()); //Test random permissions $range = range(1, $totalFields); shuffle($range); $newView = array_slice($range, 0, rand(1, $totalFields - 1)); shuffle($range); $newEdit = array_slice($range, 0, rand(1, $totalFields - 1)); $edit = array_intersect($newView, $newEdit); $view = array_diff($newView, $newEdit); $none = array_diff(range(1, $totalFields), $newView); //Have to do pre-processing to get accurate counts, but that screws up //the same preprocessing happening in the roles model. View = view + edit //fixes the double array_intersect creating an empty array. $role->setViewPermissions($view + $edit); $role->setEditPermissions($edit); $role->save(); $this->checkPermissionUpdates($role, $totalFields, array(count($view), count($edit), count($none))); $this->assertEquals($initialUsers, $role->getUsers()); }
/** * Parse the given keys and attributes to ensure required fields are * mapped and new fields are to be created. The verified map will be * stored in the 'importMap' key for the $_SESSION super global. * @param string $model name of the model * @param array $keys * @param array $attributes * @param boolean $createFields whether or not to create new fields */ protected function verifyImportMap($model, $keys, $attributes, $createFields = false) { if (!empty($keys) && !empty($attributes)) { // New import map is the provided data $importMap = array_combine($keys, $attributes); $conflictingFields = array(); $failedFields = array(); // To keep track of fields that were mapped multiple times $mappedValues = array(); $multiMappings = array(); foreach ($importMap as $key => &$value) { if (in_array($value, $mappedValues) && !empty($value) && !in_array($value, $multiMappings)) { // This attribute is mapped to two different fields in X2 $multiMappings[] = $value; } else { if ($value !== 'createNew') { $mappedValues[] = $value; } } // Loop through and figure out if we need to create new fields $origKey = $key; $key = Formatter::deCamelCase($key); $key = preg_replace('/\\[W|_]/', ' ', $key); $key = mb_convert_case($key, MB_CASE_TITLE, "UTF-8"); $key = preg_replace('/\\W/', '', $key); if ($value == 'createNew' && !$createFields) { $importMap[$origKey] = 'c_' . strtolower($key); $fieldLookup = Fields::model()->findByAttributes(array('modelName' => $model, 'fieldName' => $key)); if (isset($fieldLookup)) { $conflictingFields[] = $key; continue; } else { $customFieldLookup = Fields::model()->findByAttributes(array('modelName' => $model, 'fieldName' => $importMap[$origKey])); if (!$customFieldLookup instanceof Fields) { // Create a custom field if one doesn't exist already $columnName = strtolower($key); $field = new Fields(); $field->modelName = $model; $field->type = "varchar"; $field->fieldName = $columnName; $field->required = 0; $field->searchable = 1; $field->relevance = "Medium"; $field->custom = 1; $field->modified = 1; $field->attributeLabel = $field->generateAttributeLabel($key); if (!$field->save()) { $failedFields[] = $key; } } } } } // Check for required attributes that are missing $requiredAttrs = Yii::app()->db->createCommand()->select('fieldName, attributeLabel')->from('x2_fields')->where('modelName = :model AND required = 1', array(':model' => str_replace(' ', '', $model)))->query(); $missingAttrs = array(); foreach ($requiredAttrs as $attr) { // Skip visibility, it can be set for them if (strtolower($attr['fieldName']) == 'visibility') { continue; } // Ignore missing first/last name, this can be inferred from full name if ($model === 'Contacts' && ($attr['fieldName'] === 'firstName' || $attr['fieldName'] === 'lastName') && in_array('name', array_values($importMap))) { continue; } // Otherwise, a required field is missing and should be reported to the user if (!in_array($attr['fieldName'], array_values($importMap))) { $missingAttrs[] = $attr['attributeLabel']; } } if (!empty($conflictingFields)) { echo CJSON::encode(array("2", implode(', ', $conflictingFields))); } else { if (!empty($missingAttrs)) { echo CJSON::encode(array("3", implode(', ', $missingAttrs))); } else { if (!empty($failedFields)) { echo CJSON::encode(array("1", implode(', ', $failedFields))); } else { if (!empty($multiMappings)) { echo CJSON::encode(array("4", implode(', ', $multiMappings))); } else { echo CJSON::encode(array("0")); } } } } $_SESSION['importMap'] = $importMap; } else { echo CJSON::encode(array("0")); $_SESSION['importMap'] = array(); } }
// Yii::app()->clientScript->registerScriptFile(Yii::app()->getBaseUrl().'/js/multiselect/js/jquery-ui-1.7.1.custom.min.js'); //Yii::app()->clientScript->registerScriptFile(Yii::app()->getBaseUrl().'/js/multiselect/js/ui.multiselect.js'); //Yii::app()->clientScript->registerCssFile(Yii::app()->getBaseUrl().'/js/multiselect/css/ui.multiselect.css','screen, projection'); //Yii::app()->clientScript->registerCss('multiselectCss'," //.multiselect { // width: 460px; // height: 200px; //} //#switcher { // margin-top: 20px; //} //",'screen, projection'); Yii::app()->clientScript->registerScript('renderMultiSelect', "\n\$(document).ready(function() {\n\t \$('.multiselect').multiselect();\n});\n", CClientScript::POS_HEAD); $selected = array(); $unselected = array(); $fields = Fields::model()->findAllBySql("SELECT * FROM x2_fields ORDER BY modelName ASC"); foreach ($fields as $field) { $unselected[$field->id] = X2Model::getModelTitle($field->modelName) . " - " . $field->attributeLabel; } $users = User::getNames(); unset($users['']); unset($users['Anyone']); unset($users['admin']); $users = array_map(array('CHtml', 'encode'), $users); /* x2temp */ $groups = Groups::model()->findAll(); foreach ($groups as $group) { $users[$group->id] = CHtml::encode($group->name); } /* end x2temp */ ?>
public function search() { // Warning: Please modify the following code to remove attributes that // should not be searched. $criteria = new CDbCriteria(); $fields = Fields::model()->findAllByAttributes(array('modelName' => 'Accounts')); foreach ($fields as $field) { $fieldName = $field->fieldName; switch ($field->type) { case 'boolean': $criteria->compare($field->fieldName, $this->compareBoolean($this->{$fieldName}), true); break; case 'link': $criteria->compare($field->fieldName, $this->compareLookup($field, $this->{$fieldName}), true); break; case 'assignment': $criteria->compare($field->fieldName, $this->compareAssignment($this->{$fieldName}), true); break; default: $criteria->compare($field->fieldName, $this->{$fieldName}, true); } } $dataProvider = new SmartDataProvider(get_class($this), array('sort' => array('defaultOrder' => 'name ASC'), 'pagination' => array('pageSize' => ProfileChild::getResultsPerPage()), 'criteria' => $criteria)); $arr = $dataProvider->getData(); foreach ($arr as $account) { $account->assignedTo = User::getUserLinks($account->assignedTo); $account->associatedContacts = Contacts::getContactLinks($account->associatedContacts); } $dataProvider->setData($arr); return $dataProvider; }
/** * Retrieves a list of models based on the current search/filter conditions. * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions. */ public function search() { // Warning: Please modify the following code to remove attributes that // should not be searched. $criteria = new CDbCriteria(); $fields = Fields::model()->findAllByAttributes(array('modelName' => 'Templates')); foreach ($fields as $field) { $fieldName = $field->fieldName; switch ($field->type) { case 'boolean': $criteria->compare($field->fieldName, $this->compareBoolean($this->{$fieldName}), true); break; case 'link': $criteria->compare($field->fieldName, $this->compareLookup($field, $this->{$fieldName}), true); break; case 'assignment': $criteria->compare($field->fieldName, $this->compareAssignment($this->{$fieldName}), true); break; default: $criteria->compare($field->fieldName, $this->{$fieldName}, true); } } return new CActiveDataProvider(get_class($this), array('criteria' => $criteria, 'pagination' => array('pageSize' => ProfileChild::getResultsPerPage()))); }
$str2 .= "<a href='?model=" . $_GET['model'] . "&version=" . CHtml::encode($version->name) . "'>" . $version->name . "</a> | "; } } $str2 = substr($str2, 0, -3); $str2 .= "</h4><br />"; echo $str2; } if ($formUrl == "") { } elseif ($model instanceof Contacts) { $this->renderPartial($formUrl, array('contactModel' => $model, 'users' => User::getNames(), 'editor' => true)); } elseif ($model instanceof Actions) { $this->renderPartial($formUrl, array('actionModel' => $model, 'users' => User::getNames(), 'editor' => true)); } else { $this->renderPartial($formUrl, array('model' => $model, 'users' => User::getNames(), 'contacts' => Contacts::getAllNames(), 'editor' => true)); } $fields = Fields::model()->findAllByAttributes(array('modelName' => get_class($model)), array('order' => 'tabOrder')); if (isset($_GET['version'])) { $version = $_GET['version']; $version = FormVersions::model()->findByAttributes(array('name' => $version)); $sizes = json_decode($version->sizes, true); $positions = json_decode($version->positions, true); $visibilities = json_decode($version->visibility, true); $tempArr = array(); foreach ($fields as $field) { if (isset($positions[$field->fieldName])) { $field->coordinates = $positions[$field->fieldName]; $field->size = $sizes[$field->fieldName]; $field->visible = $visibilities[$field->fieldName]; $tempArr[] = $field; } }
$showWorkflow = Yii::app()->params->profile->showWorkflow; if ($modelName == 'contacts' || $modelName == 'sales') { Yii::app()->clientScript->registerScript('toggleWorkflow', "\nfunction showWorkflow() {\n\t\$('tr#workflow-row').show();\n\t\$('tr#workflow-toggle').hide();\n}\nfunction hideWorkflow() {\n\t\$('tr#workflow-row').hide();\n\t\$('tr#workflow-toggle').show();\n}\n\$(function() {\n" . ($showWorkflow ? "showWorkflow();\n" : "hideWorkflow()\n") . "});", CClientScript::POS_HEAD); Yii::app()->clientScript->registerScript('setFormName', "\nwindow.formName = '{$modelName}';\n", CClientScript::POS_HEAD); } $layout = FormLayout::model()->findByAttributes(array('model' => ucfirst($modelName), 'defaultView' => 1)); if (isset($layout)) { echo '<div class="x2-layout">'; $fields = array(); // remove this later, once all models extend X2Models if (method_exists($model, 'getFields')) { foreach ($model->fields as $fieldModel) { $fields[$fieldModel->fieldName] = $fieldModel; } } else { foreach (Fields::model()->findAllByAttributes(array('modelName' => ucfirst($modelName))) as $fieldModel) { $fields[$fieldModel->fieldName] = $fieldModel; } } $layoutData = json_decode($layout->layout, true); $formSettings = ProfileChild::getFormSettings($modelName); if (isset($layoutData['sections']) && count($layoutData['sections']) > 0) { $fieldPermissions = array(); if (!empty(Yii::app()->params->roles)) { $rolePermissions = Yii::app()->db->createCommand()->select('fieldId, permission')->from('x2_role_to_permission')->join('x2_fields', 'x2_fields.modelName="' . $modelName . '" AND x2_fields.id=fieldId AND roleId IN (' . implode(',', Yii::app()->params->roles) . ')')->queryAll(); foreach ($rolePermissions as &$permission) { if (!isset($fieldPermissions[$permission['fieldId']]) || $fieldPermissions[$permission['fieldId']] < (int) $permission['permission']) { $fieldPermissions[$permission['fieldId']] = (int) $permission['permission']; } } }
echo '<div class="x2-layout form-view">'; // $temp=RoleToUser::model()->findAllByAttributes(array('userId'=>Yii::app()->user->getId(),'type'=>'user')); // $roles=array(); // foreach($temp as $link){ // $roles[]=$link->roleId; // } // /* x2temp */ // $groups=GroupToUser::model()->findAllByAttributes(array('userId'=>Yii::app()->user->getId())); // foreach($groups as $link){ // $tempRole=RoleToUser::model()->findByAttributes(array('userId'=>$link->groupId, 'type'=>'group')); // if(isset($tempRole)) // $roles[]=$tempRole->roleId; // } /* end x2temp */ $fields = array(); $fieldModels = Fields::model()->findAllByAttributes(array('modelName' => ucfirst($modelName))); foreach ($fieldModels as &$fieldModel) { $fields[$fieldModel->fieldName] = $fieldModel; } unset($fieldModel); echo $form->errorSummary($model) . ' '; $layoutData = json_decode($layout->layout, true); $formSettings = ProfileChild::getFormSettings($modelName); if (isset($layoutData['sections']) && count($layoutData['sections']) > 0) { $fieldPermissions = array(); if (!empty(Yii::app()->params->roles)) { $rolePermissions = Yii::app()->db->createCommand()->select('fieldId, permission')->from('x2_role_to_permission')->join('x2_fields', 'x2_fields.modelName="' . $modelName . '" AND x2_fields.id=fieldId AND roleId IN (' . implode(',', Yii::app()->params->roles) . ')')->queryAll(); foreach ($rolePermissions as &$permission) { if (!isset($fieldPermissions[$permission['fieldId']]) || $fieldPermissions[$permission['fieldId']] < (int) $permission['permission']) { $fieldPermissions[$permission['fieldId']] = (int) $permission['permission']; }
public static function getFieldOptions(array $layout, $modelName) { // format layout options $model = new $modelName(); $labelled = array(); foreach ($layout as $fieldName) { $field = $model->getField($fieldName); if ($field) { $labelled[$fieldName] = $field->attributeLabel; } } $layout = $labelled; // get all field options $fields = Fields::model()->findAllByAttributes(array('modelName' => $modelName), new CDbCriteria(array('order' => 'attributeLabel ASC', 'condition' => 'keyType IS NULL OR (keyType!="PRI" AND keyType!="FIX")'))); // format field options $labelled = array(); foreach ($fields as $field) { $labelled[$field->fieldName] = $field->attributeLabel; } $fields = $labelled; $unselected = array_diff_key($fields, $layout); return array($layout, $unselected); }
/** * Updates a particular model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id the ID of the model to be updated */ public function actionUpdate($id) { $model = $this->loadModel($id); $groups = array(); foreach (Groups::model()->findAll() as $group) { $groups[$group->id] = CHtml::encode($group->name); } $selectedGroups = array(); foreach (GroupToUser::model()->findAllByAttributes(array('userId' => $model->id)) as $link) { $selectedGroups[] = $link->groupId; } $roles = array(); foreach (Roles::model()->findAll() as $role) { $roles[$role->id] = CHtml::encode($role->name); } $selectedRoles = array(); foreach (RoleToUser::model()->findAllByAttributes(array('userId' => $model->id)) as $link) { $selectedRoles[] = $link->roleId; } // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if (!isset($model->userAlias)) { $model->userAlias = $model->username; } if (isset($_POST['User'])) { $old = $model->attributes; $temp = $model->password; $model->attributes = $_POST['User']; if ($model->password != "") { $model->password = PasswordUtil::createHash($model->password); } else { $model->password = $temp; } if (empty($model->userKey)) { $model->userKey = substr(str_shuffle(str_repeat('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789', 32)), 0, 32); } if ($model->save()) { $profile = $model->profile; if (!empty($profile)) { $profile->emailAddress = $model->emailAddress; $profile->fullName = $model->firstName . ' ' . $model->lastName; $profile->save(); } if ($old['username'] != $model->username) { $fieldRecords = Fields::model()->findAllByAttributes(array('fieldName' => 'assignedTo')); $modelList = array(); foreach ($fieldRecords as $record) { $modelList[$record->modelName] = $record->linkType; } foreach ($modelList as $modelName => $type) { if ($modelName == 'Quotes') { $modelName = "Quote"; } if ($modelName == 'Products') { $modelName = 'Product'; } if (empty($type)) { $list = X2Model::model($modelName)->findAllByAttributes(array('assignedTo' => $old['username'])); foreach ($list as $item) { $item->assignedTo = $model->username; $item->save(); } } else { $list = X2Model::model($modelName)->findAllBySql("SELECT * FROM " . X2Model::model($modelName)->tableName() . " WHERE assignedTo LIKE '%" . $old['username'] . "%'"); foreach ($list as $item) { $assignedTo = explode(", ", $item->assignedTo); $key = array_search($old['username'], $assignedTo); if ($key >= 0) { $assignedTo[$key] = $model->username; } $item->assignedTo = implode(", ", $assignedTo); $item->save(); } } } $profile = Profile::model()->findByAttributes(array('username' => $old['username'])); if (isset($profile)) { $profile->username = $model->username; $profile->save(); } } foreach (RoleToUser::model()->findAllByAttributes(array('userId' => $model->id)) as $link) { $link->delete(); } foreach (GroupToUser::model()->findAllByAttributes(array('userId' => $model->id)) as $link) { $link->delete(); } if (isset($_POST['roles'])) { $roles = $_POST['roles']; foreach ($roles as $role) { $link = new RoleToUser(); $link->roleId = $role; $link->type = "user"; $link->userId = $model->id; $link->save(); } } if (isset($_POST['groups'])) { $groups = $_POST['groups']; foreach ($groups as $group) { $link = new GroupToUser(); $link->groupId = $group; $link->userId = $model->id; $link->username = $model->username; $link->save(); } } $this->redirect(array('view', 'id' => $model->id)); } } $this->render('update', array('model' => $model, 'groups' => $groups, 'roles' => $roles, 'selectedGroups' => $selectedGroups, 'selectedRoles' => $selectedRoles)); }
public function afterSave($event) { $oldAttributes = $this->owner->getOldAttributes(); $linkFields = Fields::model()->findAllByAttributes(array('modelName' => get_class($this->owner), 'type' => 'link')); foreach ($linkFields as $field) { $nameAndId = Fields::nameAndId($this->owner->getAttribute($field->fieldName)); $oldNameAndId = Fields::nameAndId(isset($oldAttributes[$field->fieldName]) ? $oldAttributes[$field->fieldName] : ''); if (!empty($oldNameAndId[1]) && $nameAndId[1] !== $oldNameAndId[1]) { $oldTarget = X2Model::model($field->linkType)->findByPk($oldNameAndId[1]); $this->owner->deleteRelationship($oldTarget); } $newTarget = X2Model::model($field->linkType)->findByPk($nameAndId[1]); $this->owner->createRelationship($newTarget); } parent::afterSave($event); }
public function searchBase($criteria) { $fields = Fields::model()->findAllByAttributes(array('modelName' => 'Actions')); foreach ($fields as $field) { $fieldName = $field->fieldName; switch ($field->type) { case 'boolean': $criteria->compare($field->fieldName, $this->compareBoolean($this->{$fieldName}), true); break; case 'link': $criteria->compare($field->fieldName, $this->compareLookup($field, $this->{$fieldName}), true); break; case 'assignment': $criteria->compare($field->fieldName, $this->compareAssignment($this->{$fieldName}), true); break; default: $criteria->compare($field->fieldName, $this->{$fieldName}, true); } } $criteria->addCondition('(type != "workflow" AND type!="email") OR type IS NULL'); $dataProvider = new SmartDataProvider('Actions', array('sort' => array('defaultOrder' => 'completeDate DESC, dueDate DESC'), 'pagination' => array('pageSize' => ceil(ProfileChild::getResultsPerPage())), 'criteria' => $criteria)); return $dataProvider; }
protected function generateModuleSqlData($moduleName) { $sql = ""; $disallow = array("id", "assignedTo", "name", "nameId", "description", "createDate", "lastUpdated", "updatedBy"); $fields = Fields::model()->findAllByAttributes(array('modelName' => ucfirst($moduleName))); foreach ($fields as $field) { if (array_search($field->fieldName, $disallow) === false) { $fieldType = $field->type; $columnDefinitions = Fields::getFieldTypes('columnDefinition'); if (isset($columnDefinitions[$fieldType])) { $fieldType = $columnDefinitions[$fieldType]; } else { $fieldType = 'VARCHAR(250)'; } $linkType = $field->linkType; if ($field->type === 'dropdown') { // Export associated dropdown values $dropdown = Dropdowns::model()->findByPk($field->linkType); if ($dropdown) { $sql .= "/*&*/INSERT INTO x2_dropdowns " . "(name, options, multi, parent, parentVal) " . "VALUES " . "('{$dropdown->name}', '{$dropdown->options}', '{$dropdown->multi}', " . "'{$dropdown->parent}', '{$dropdown->parentVal}');"; // Temporarily set the linkType to the dropdowns name: this is to avoid // messy ID conflicts when importing a module to existing installations $linkType = $dropdown->name; } } $sql .= "/*&*/ALTER TABLE x2_{$moduleName} ADD COLUMN {$field->fieldName} {$fieldType};"; $sql .= "/*&*/INSERT INTO x2_fields " . "(modelName, fieldName, attributeLabel, modified, custom, type, linkType) " . "VALUES " . "('{$moduleName}', '{$field->fieldName}', '{$field->attributeLabel}', '1', '1', " . "'{$field->type}', '{$linkType}');"; } } $formLayouts = X2Model::model('FormLayout')->findAllByAttributes(array('model' => $moduleName)); foreach ($formLayouts as $layout) { $attributes = $layout->attributes; unset($attributes['id']); $attributeKeys = array_keys($attributes); $attributeValues = array_values($attributes); $keys = implode(", ", $attributeKeys); $values = "'" . implode("', '", $attributeValues) . "'"; $sql .= "/*&*/INSERT INTO x2_form_layouts ({$keys}) VALUES ({$values});"; } return $sql; }
/** * Updates a particular model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id the ID of the model to be updated */ public function actionUpdate($id) { $model = $this->loadModel($id); $users = User::getNames(); $fields = Fields::model()->findAllByAttributes(array('modelName' => "Products")); foreach ($fields as $field) { if ($field->type == 'link') { $fieldName = $field->fieldName; $type = ucfirst($field->linkType); if (is_numeric($model->{$fieldName}) && $model->{$fieldName} != 0) { eval("\$lookupModel={$type}::model()->findByPk(" . $model->{$fieldName} . ");"); if (isset($lookupModel)) { $model->{$fieldName} = $lookupModel->name; } } } } if (isset($_POST['Product'])) { $temp = $model->attributes; foreach ($_POST['Product'] as $name => $value) { if ($value == $model->getAttributeLabel($name)) { $_POST['Product'][$name] = ''; } } foreach ($_POST as $key => $arr) { $pieces = explode("_", $key); if (isset($pieces[0]) && $pieces[0] == 'autoselect') { $newKey = $pieces[1]; if (isset($_POST[$newKey . "_id"]) && $_POST[$newKey . "_id"] != "") { $val = $_POST[$newKey . "_id"]; } else { $field = Fields::model()->findByAttributes(array('fieldName' => $newKey)); if (isset($field)) { $type = ucfirst($field->linkType); if ($type != "Contacts") { eval("\$lookupModel={$type}::model()->findByAttributes(array('name'=>'{$arr}'));"); } else { $names = explode(" ", $arr); $lookupModel = Contacts::model()->findByAttributes(array('firstName' => $names[0], 'lastName' => $names[1])); } if (isset($lookupModel)) { $val = $lookupModel->id; } else { $val = $arr; } } } $model->{$newKey} = $val; } } foreach (array_keys($model->attributes) as $field) { if (isset($_POST['Product'][$field])) { $model->{$field} = $_POST['Product'][$field]; $fieldData = Fields::model()->findByAttributes(array('modelName' => 'Products', 'fieldName' => $field)); if ($fieldData->type == 'assignment' && $fieldData->linkType == 'multiple') { $model->{$field} = Accounts::parseUsers($model->{$field}); } elseif ($fieldData->type == 'date') { $model->{$field} = strtotime($model->{$field}); } } } // generate history $action = new Actions(); $action->associationType = 'product'; $action->associationId = $model->id; $action->associationName = $model->name; $action->assignedTo = Yii::app()->user->getName(); $action->completedBy = Yii::app()->user->getName(); $action->dueDate = time(); $action->completeDate = time(); $action->visibility = 1; $action->complete = 'Yes'; $action->actionDescription = "Update: <b>{$model->name}</b>\n\t\t\t\tType: <b>{$model->type}</b>\n\t\t\t\tPrice: <b>{$model->price}</b>\n\t\t\t\tCurrency: <b>{$model->currency}</b>\n\t\t\t\tInventory: <b>{$model->inventory}</b>"; $action->save(); parent::update($model, $temp, '0'); } $this->render('update', array('model' => $model, 'users' => $users)); }
/** * update calendar with id $id */ public function actionUpdate($id) { $model = $this->loadModel($id); if (isset($_POST['X2Calendar'])) { // check for empty permissions if (!isset($_POST['X2Calendar']['viewPermission'])) { $model->viewPermission = ''; } if (!isset($_POST['X2Calendar']['editPermission'])) { $model->editPermission = ''; } // copy $_POST data into Calendar model foreach (array_keys($model->attributes) as $field) { if (isset($_POST['X2Calendar'][$field])) { $model->{$field} = $_POST['X2Calendar'][$field]; $fieldData = Fields::model()->findByAttributes(array('modelName' => 'Calendar', 'fieldName' => $field)); if ($fieldData->type == 'assignment' && $fieldData->linkType == 'multiple') { $model->{$field} = Fields::parseUsers($model->{$field}); } elseif ($fieldData->type == 'date') { $model->{$field} = strtotime($model->{$field}); } } } $model->updatedBy = Yii::app()->user->name; $model->lastUpdated = time(); $model->save(); $this->redirect(array('view', 'id' => $model->id)); } $admin = Yii::app()->settings; $googleIntegration = $admin->googleIntegration; $this->render('update', array('model' => $model, 'googleIntegration' => $googleIntegration)); }
/** * Build a json-encoded form layout for models whose Forms are not editable or * for custom modules that do not yet have a user-created form. * @param string $modelname The model for which to build a default layout. * @return json The default layout for the selected model. */ public static function getDefaultFormLayout($modelName) { $model = X2Model::model($modelName); $fields = Fields::model()->findAllByAttributes(array('modelName' => $modelName), new CDbCriteria(array('order' => 'attributeLabel ASC'))); $layout = array('sections' => array(array('collapsible' => false, 'title' => ucfirst($modelName) . ' Info', 'rows' => array(array('cols' => array(array('items' => array()))))))); foreach ($fields as $field) { if ($field->readOnly) { continue; } // hide associationType, it will be set in the dialog by associationName if ($field->fieldName == 'associationType') { continue; } $newField = array('name' => 'formItem_' . $field->fieldName, 'labelType' => 'left', 'readOnly' => $field->readOnly, 'height' => 30, 'width' => 155); $layout['sections'][0]['rows'][0]['cols'][0]['items'][] = $newField; } return json_encode($layout); }
/** * Updates a particular model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id the ID of the model to be updated */ public function actionUpdate($id) { $model = $this->loadModel($id); $users = User::getNames(); $fields = Fields::model()->findAllByAttributes(array('modelName' => "Templates")); foreach ($fields as $field) { if ($field->type == 'link') { $fieldName = $field->fieldName; $type = ucfirst($field->linkType); if (is_numeric($model->{$fieldName}) && $model->{$fieldName} != 0) { eval("\$lookupModel={$type}::model()->findByPk(" . $model->{$fieldName} . ");"); if (isset($lookupModel)) { $model->{$fieldName} = $lookupModel->name; } } } elseif ($field->type == 'date') { $fieldName = $field->fieldName; $model->{$fieldName} = date("Y-m-d", $model->{$fieldName}); } } if (isset($_POST['Templates'])) { $temp = $model->attributes; foreach ($_POST['Templates'] as $name => $value) { if ($value == $model->getAttributeLabel($name)) { $_POST['Templates'][$name] = ''; } } foreach ($_POST as $key => $arr) { $pieces = explode("_", $key); if (isset($pieces[0]) && $pieces[0] == 'autoselect') { $newKey = $pieces[1]; if (isset($_POST[$newKey . "_id"]) && $_POST[$newKey . "_id"] != "") { $val = $_POST[$newKey . "_id"]; } else { $field = Fields::model()->findByAttributes(array('fieldName' => $newKey)); if (isset($field)) { $type = ucfirst($field->linkType); if ($type != "Contacts") { eval("\$lookupModel={$type}::model()->findByAttributes(array('name'=>'{$arr}'));"); } else { $names = explode(" ", $arr); if (count($names) > 1) { $lookupModel = Contacts::model()->findByAttributes(array('firstName' => $names[0], 'lastName' => $names[1])); } } if (isset($lookupModel)) { $val = $lookupModel->id; } else { $val = $arr; } } } $model->{$newKey} = $val; } } $temp = $model->attributes; foreach (array_keys($model->attributes) as $field) { if (isset($_POST['Templates'][$field])) { $model->{$field} = $_POST['Templates'][$field]; $fieldData = Fields::model()->findByAttributes(array('modelName' => 'Templates', 'fieldName' => $field)); if ($fieldData->type == 'assignment' && $fieldData->linkType == 'multiple') { $model->{$field} = Accounts::parseUsers($model->{$field}); } elseif ($fieldData->type == 'date') { $model->{$field} = strtotime($model->{$field}); } } } parent::update($model, $temp, '0'); } $this->render('update', array('model' => $model, 'users' => $users)); }