public function run() { Yii::app()->clientScript->registerScriptFile(Yii::app()->theme->getBaseUrl() . '/css/gridview/jquery.yiigridview.js'); $relationships = Relationships::model()->findAllByAttributes(array('firstType' => 'quotes', 'secondType' => 'contacts', 'secondId' => $this->contactId)); echo '<div id="quotes-form">'; echo '<div id="wide-quote-form" class="wide form" style="overflow: visible;">'; echo '<span style="font-weight:bold; font-size: 1.5em;">' . Yii::t('quotes', "Quotes") . '</span>'; echo '<br /><br />'; // get a list of products for adding to quotes $products = Product::model()->findAll(array('select' => 'id, name')); $productNames = array(0 => ''); foreach ($products as $product) { $productNames[$product->id] = $product->name; } $quotes = Quote::model()->findAllByAttributes(array('associatedContacts' => $this->contactId)); foreach ($quotes as $quote) { $products = Product::model()->findAll(array('select' => 'id, name, price')); $quoteProducts = QuoteProduct::model()->findAllByAttributes(array('quoteId' => $quote->id)); // find associated products and their quantities $quotesProducts = QuoteProduct::model()->findAllByAttributes(array('quoteId' => $quote->id)); $orders = array(); // array of product-quantity pairs $total = 0; // total price for the quote foreach ($quotesProducts as $qp) { $price = $qp->price * $qp->quantity; if ($qp->adjustmentType == 'percent') { $price += $price * ($qp->adjustment / 100); $qp->adjustment = "{$qp->adjustment}%"; } else { $price += $qp->adjustment; } $orders[] = array('name' => $qp->name, 'id' => $qp->productId, 'unit' => $qp->price, 'quantity' => $qp->quantity, 'adjustment' => $qp->adjustment, 'price' => $price); $order = end($orders); $total += $order['price']; } $dataProvider = new CArrayDataProvider($orders, array('keyField' => 'name', 'sort' => array('attributes' => array('name', 'unit', 'quantity', 'price')), 'pagination' => array('pageSize' => false))); $newProductId = "new_product_" . $quote->id; $this->render('viewQuotes', array('quote' => $quote, 'contactId' => $this->contactId, 'dataProvider' => $dataProvider, 'products' => $products, 'productNames' => $productNames, 'orders' => $quoteProducts, 'total' => $total)); } // Mini Create Quote Form $model = new Quote(); $this->render('createQuote', array('model' => $model, 'contactId' => $this->contactId, 'productNames' => $productNames)); echo "</div>"; echo "</div>"; }
/** * * @param type $id * @return string */ public function returnRelationship($id) { $model = Relationships::model()->findByPk($id); return empty($model) ? null : $model->relationship; }
/** * REST-ful API method for adding and removing relationships between records. */ public function actionRelationship() { $rType = Yii::app()->request->requestType; switch ($rType) { case 'GET': // Look up relationships on a model $attr = array('firstType' => $_GET['model']); $relationships = Relationships::model()->findAllByAttributes(array_merge(array_intersect_key($_GET, array_flip(Relationships::model()->safeAttributeNames)), $attr)); if (empty($relationships)) { $this->_sendResponse(404, Yii::t('api', 'No relationships found.')); } else { $this->_sendResponse(200, array_map(function ($r) { return $r->attributes; }, $relationships), 1); } case 'POST': // Add a new relationship to model $relationship = new Relationships('api'); $relationship->attributes = $_POST; $relationship->firstType = $_GET['model']; if ($relationship->validate()) { $existingRelationship = Relationships::model()->findByAttributes(array_intersect_key($relationship->attributes, array_flip(array('firstType', 'secondType', 'firstId', 'secondId')))); if ($existingRelationship) { $this->_sendResponse(200, Yii::t('api', 'Such a relationship already exists.')); } if ($relationship->save()) { $this->_sendResponse(200, Yii::t('api', 'Successfully saved a relationship.')); } else { $this->_sendResponse(500, Yii::t('api', 'Failed to save relationship record for unknown reason.')); } } else { $this->response['modelErrors'] = $relationship->errors; $this->_sendResponse(400, $this->validationMsg('create', $relationship)); } break; case 'DELETE': if (!isset($_GET['secondType'], $_GET['firstId'], $_GET['secondId'])) { $this->_sendResponse(400, Yii::t('api', 'Cannot delete; no parameters specified for finding a relationship record to delete.')); } $relationships = Relationships::model()->findAllByAttributes(array_merge(array('firstType' => $_GET['model']), array_intersect_key($_GET, array_flip(Relationships::model()->attributeNames())))); if (empty($relationships)) { $this->_sendResponse(404, Yii::t('api', 'No relationships deleted; none were found matching specfied parameters.')); } $n_d = 0; $n_d_t = count($relationships); foreach ($relationships as $model) { $n_d += $model->delete() ? 1 : 0; } if ($n_d == $n_d_t) { $this->_sendResponse(200, Yii::t('api', '{n} relationships deleted.', array('{n}' => $n_d))); } else { $this->_sendResponse(500, Yii::t('api', 'One or more relationships could not be deleted.')); } break; default: $this->_sendResponse(400, Yii::t('api', 'Request type not supported for this action.')); break; } }
?> . </td> <td style="text-align: justify"><?php echo $spouse->name; ?> </td> <td style="text-align: center"><?php echo $spouse->idno; ?> </td> <td style="text-align: center"><?php echo $spouse->alive == 1 ? 'Yes' : 'No'; ?> </td> <td style="text-align: center"><?php echo Relationships::model()->returnRelationship($spouse->relationship); ?> </td> <td style="text-align: center"><?php echo $spouse->mobileno; ?> </td> <td style="text-align: justify"><?php echo $spouse->postaladdress; ?> </td> </tr> <?php } ?> <?php
?> . </td> <td style="text-align: justify"><?php echo $parent->name; ?> </td> <td style="text-align: center"><?php echo $parent->idno; ?> </td> <td style="text-align: center"><?php echo $parent->alive == 1 ? 'Yes' : 'No'; ?> </td> <td style="text-align: center"><?php echo Relationships::model()->returnRelationship($parent->relationship); ?> </td> <td style="text-align: center"><?php echo $parent->mobileno; ?> </td> <td style="text-align: justify"><?php echo $parent->postaladdress; ?> </td> </tr> <?php } ?> <?php
public function hasRelationship($target) { $rel1 = Relationships::model()->countByAttributes(array('firstType' => get_class($this->owner), 'firstId' => $this->owner->id, 'secondType' => get_class($target), 'secondId' => $target->id)); $rel2 = Relationships::model()->countByAttributes(array('firstType' => get_class($target), 'firstId' => $target->id, 'secondType' => get_class($this->owner), 'secondId' => $this->owner->id)); return $rel1 || $rel2; }
/** * Clear out records associated with this quote before deletion. */ public function beforeDelete() { QuoteProduct::model()->deleteAllByAttributes(array('quoteId' => $this->id)); // for old relationships generated with incorrect type name Relationships::model()->deleteAllByAttributes(array('firstType' => 'quotes', 'firstId' => $this->id)); // generate action record for history $contact = $this->contact; if (!empty($contact)) { $action = new Actions(); $action->associationType = 'contacts'; $action->type = 'quotesDeleted'; $action->associationId = $contact->id; $action->associationName = $contact->name; $action->assignedTo = Yii::app()->getSuModel()->username; $action->completedBy = Yii::app()->getSuModel()->username; $action->createDate = time(); $action->dueDate = time(); $action->completeDate = time(); $action->visibility = 1; $action->complete = 'Yes'; $action->actionDescription = "Deleted Quote: <span style=\"font-weight:bold;\">{$this->id}</span> {$this->name}"; // Save after deletion of the model so that this action itself doensn't get deleted $action->save(); } return parent::beforeDelete(); }
/** * Transfers all relationships of $model to $this */ public function mergeRelationships(X2Model $model, $logMerge = false) { $ret = array(); $modelType = get_class($model); $targetModelType = get_class($this); if ($logMerge) { $ids = Yii::app()->db->createCommand()->select('id')->from('x2_relationships')->where('firstType = :type AND firstId = :id', array(':type' => $modelType, ':id' => $model->id))->queryColumn(); if (!empty($ids)) { $ret['first'] = $ids; } $ids = Yii::app()->db->createCommand()->select('id')->from('x2_relationships')->where('secondType = :type AND secondId = :id', array(':type' => $modelType, ':id' => $model->id))->queryColumn(); if (!empty($ids)) { $ret['second'] = $ids; } } Relationships::model()->updateAll(array('firstId' => $this->id, 'firstType' => $targetModelType), 'firstType = :type AND firstId = :id', array(':type' => $modelType, ':id' => $model->id)); Relationships::model()->updateAll(array('secondId' => $this->id, 'secondType' => $targetModelType), 'secondType = :type AND secondId = :id', array(':type' => $modelType, ':id' => $model->id)); return $ret; }
$this->renderPartial('application.components.views._detailView', array('model' => $model, 'modelName' => 'sales')); $this->endWidget(); // render workflow box // $this->renderPartial('application.components.views._workflow',array('model'=>$model,'modelName'=>'sales','currentWorkflow'=>$currentWorkflow)); $this->widget('WorkflowStageDetails', array('model' => $model, 'modelName' => 'sales', 'currentWorkflow' => $currentWorkflow)); ?> <div id="attachment-form" style="display:none;"> <?php $this->widget('Attachments', array('type' => 'sales', 'associationId' => $model->id)); ?> </div> <?php $contactModel = new Contacts(); $links = Relationships::model()->findAllByAttributes(array('secondType' => 'Sales', 'secondId' => $model->id)); $str = "("; foreach ($links as $link) { $str .= $link->firstId . ", "; } if ($str != "(") { $flag = true; $str = substr($str, 0, -2) . ")"; } else { $flag = false; } $contactDataProvider = new CActiveDataProvider('Contacts', array('criteria' => array('order' => 'lastName DESC, firstName DESC', 'condition' => $flag ? 'id IN ' . $str : 'id=null'))); $this->widget('application.components.X2GridView', array('id' => 'contacts-grid', 'baseScriptUrl' => Yii::app()->request->baseUrl . '/themes/' . Yii::app()->theme->name . '/css/gridview', 'template' => '<h2>' . Yii::t('contacts', 'Associated Contacts') . '</h2><div class="title-bar">' . CHtml::link(Yii::t('app', 'Advanced Search'), '#', array('class' => 'search-button')) . ' | ' . CHtml::link(Yii::t('app', 'Clear Filters'), array('index', 'clearFilters' => 1)) . ' | ' . CHtml::link(Yii::t('app', 'Columns'), 'javascript:void(0);', array('class' => 'column-selector-link')) . '{summary}</div>{items}{pager}', 'dataProvider' => $contactDataProvider, 'filter' => $contactModel, 'modelName' => 'Contacts', 'viewName' => 'contacts', 'defaultGvSettings' => array('name' => 234, 'email' => 108, 'leadsource' => 128, 'assignedTo' => 115), 'specialColumns' => array('name' => array('name' => 'name', 'header' => Yii::t('contacts', 'Name'), 'value' => 'CHtml::link($data->name,array("/contacts/".$data->id))', 'type' => 'raw')), 'enableControls' => true)); echo "<br />"; $this->widget('InlineActionForm', array('associationType' => 'sales', 'associationId' => $model->id, 'assignedTo' => Yii::app()->user->getName(), 'users' => $users, 'startHidden' => false)); if (isset($_GET['history'])) {
/** * 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 update($model, $oldAttributes, $api) { $name = $this->modelClass; $temp = $oldAttributes; $changes = $this->calculateChanges($temp, $model->attributes, $model); $model = $this->updateChangelog($model, $changes); if ($model->save()) { if (!$model instanceof Actions) { $fields = Fields::model()->findAllByAttributes(array('modelName' => $name, 'type' => 'link')); foreach ($fields as $field) { $fieldName = $field->fieldName; if (isset($model->{$fieldName}) && $model->{$fieldName} != "") { if (is_null(Relationships::model()->findBySql("SELECT * FROM x2_relationships WHERE \n\t\t\t\t\t\t\t\t(firstType='{$name}' AND firstId='{$model->id}' AND secondType='" . ucfirst($field->linkType) . "' AND secondId='" . $model->{$fieldName} . "') \n\t\t\t\t\t\t\t\tOR (secondType='{$name}' AND secondId='{$model->id}' AND firstType='" . ucfirst($field->linkType) . "' AND firstId='" . $model->{$fieldName} . "')"))) { $rel = new Relationships(); $rel->firstType = $name; $rel->secondType = ucfirst($field->linkType); $rel->firstId = $model->id; $rel->secondId = $model->{$fieldName}; if ($rel->save()) { if ($field->linkType != 'contacts') { $oldRel = CActiveRecord::model(ucfirst($field->linkType))->findByAttributes(array('name' => $oldAttributes[$fieldName])); } else { $pieces = explode(" ", $oldAttributes[$fieldName]); if (count($pieces) > 1) { $oldRel = CActiveRecord::model(ucfirst($field->linkType))->findByAttributes(array('firstName' => $pieces[0], 'lastName' => $pieces[1])); } } if (isset($oldRel)) { $lookup = Relationships::model()->findBySql("SELECT * FROM x2_relationships WHERE \n\t\t\t\t\t\t\t\t\t(firstType='{$name}' AND firstId='{$model->id}' AND secondType='" . ucfirst($field->linkType) . "' AND secondId='" . $oldRel->id . "') \n\t\t\t\t\t\t\t\t\tOR (secondType='{$name}' AND secondId='{$model->id}' AND firstType='" . ucfirst($field->linkType) . "' AND firstId='" . $oldRel->id . "')"); if (isset($lookup)) { $lookup->delete(); } } } } } elseif ($model->{$fieldName} == "") { if ($field->linkType != 'contacts') { $oldRel = CActiveRecord::model(ucfirst($field->linkType))->findByAttributes(array('name' => $oldAttributes[$fieldName])); } else { $pieces = explode(" ", $oldAttributes[$fieldName]); if (count($pieces) > 1) { $oldRel = CActiveRecord::model(ucfirst($field->linkType))->findByAttributes(array('firstName' => $pieces[0], 'lastName' => $pieces[1])); } } if (isset($oldRel)) { $lookup = Relationships::model()->findBySql("SELECT * FROM x2_relationships WHERE \n\t\t\t\t\t\t\t\t\t(firstType='{$name}' AND firstId='{$model->id}' AND secondType='" . ucfirst($field->linkType) . "' AND secondId='" . $oldRel->id . "') \n\t\t\t\t\t\t\t\t\tOR (secondType='{$name}' AND secondId='{$model->id}' AND firstType='" . ucfirst($field->linkType) . "' AND firstId='" . $oldRel->id . "')"); if (isset($lookup)) { $lookup->delete(); } } } } } if ($model instanceof Actions && $api == 0) { if (isset($_GET['redirect']) && $model->associationType != 'none') { // if the action has an association $this->redirect(array('/' . $model->associationType . '/default/view', 'id' => $model->associationId)); } else { // no association $this->redirect(array('/actions/default/view', 'id' => $model->id)); } // view the action } else { if ($api == 0) { $this->redirect(array('view', 'id' => $model->id)); } else { return true; } } } else { return false; } }
?> . </td> <td style="text-align: justify"><?php echo $dependent->name; ?> </td> <td style="text-align: center"><?php echo $dependent->idno; ?> </td> <td style="text-align: center"><?php echo $dependent->mobileno; ?> </td> <td style="text-align: center"><?php echo Relationships::model()->returnRelationship($dependent->relationship); ?> </td> <td style="text-align: center"><?php echo $nominee->percent; ?> </td> <td style="text-align: justify"><?php echo $dependent->postaladdress; ?> </td> </tr> <?php } ?> <?php
<tr> <td style="display:table-cell; text-align:right; width:30px; height: 12px"> <font style="font-family: sans-serif; font-weight: bold" size="11"><?php echo ++$i; ?> .</font> </td> <td style="display:table-cell; text-align:justify; width:320px; height: 12px"> <font style="font-family: sans-serif; font-weight: normal" size="11"><?php echo $sibling->name; ?> </font> </td> <td style="display:table-cell; text-align:center; width:150px; height: 12px"> <font style="font-family: sans-serif; font-weight: normal" size="11"><?php echo Relationships::model()->returnRelationship($sibling->relationship); ?> </font> </td> </tr> <?php } ?> <?php } ?> <tr><td style="display:table-cell; text-align:center; width:500px; height: 10px"> </td></tr> <tr><td style="display:table-cell; text-align:center; width:500px; height: 10px"> </td></tr>
/** * Runs when a model is deleted. * Clears any entries in <tt>x2_phone_numbers</tt>. * Fires onAfterDelete event. */ public function afterDelete() { // Clear out old tags: $class = get_class($this); Tags::model()->deleteAllByAttributes(array('type' => $class, 'itemId' => $this->id)); // Clear out old relationships: Yii::app()->db->createCommand()->delete(Relationships::model()->tableName(), '(`firstType`=:ft AND `firstId`=:fid) OR (`secondType`=:st AND `secondId`=:sid)', array(':ft' => $class, ':fid' => $this->id, ':st' => $class, ':sid' => $this->id)); // Clear out old phone numbers X2Model::model('PhoneNumber')->deleteAllByAttributes(array('modelId' => $this->id, 'modelType' => $class)); RecordAliases::model()->deleteAllByAttributes(array('recordId' => $this->id, 'recordType' => $class)); // Change all references to this record so that they retain the name but // exclude the ID: if ($this->hasAttribute('nameId') && $this->hasAttribute('name')) { $this->_oldAttributes = $this->getAttributes(); $this->nameId = $this->name; $this->updateNameIdRefs(); } // clear out associated actions Actions::model()->deleteAllByAttributes(array('associationType' => strtolower(self::getAssociationType(get_class($this))), 'associationId' => $this->id)); if ($this->hasEventHandler('onAfterDelete')) { $this->onAfterDelete(new CEvent($this)); } }
public function testActionRelationship() { $urlParam = $this->urlParam; $urlParam['{action}'] = 'relationship'; $urlParam['{model}'] = 'Accounts'; // Step 1: Test lookup: $urlParam['{params}'] = '?' . http_build_query(array_merge($this->param, array('firstId' => $this->accounts('testQuote')->id, 'secondType' => 'Contacts', 'secondId' => $this->contacts('testUser')->id)), '', '&'); $ch = $this->getCurlHandle($urlParam); $cr = curl_exec($ch); $cr = json_decode($cr, 1); $this->assertTrue(is_array($cr), 'Request to read relationships failed utterly'); $this->assertArrayNotHasKey('message', $cr, "Unsuccessful API request; unexpected message. json = " . json_encode($cr)); $this->assertEquals(1, count($cr), 'Number of relationships is inconsistent with values expected in fixture data (might want to double-check that)'); foreach (Relationships::model()->attributeNames() as $name) { $this->assertArrayHasKey($name, $cr[0], "Attribute {$name} missing in returned array of relationships"); $this->assertEquals($this->relationships('blackMesaContact')->{$name}, $cr[0][$name], 'API returned relationship record inconsistent with fixture data.'); } // Step 2: Test creation: $urlParam['{params}'] = ''; $postData = array_merge($this->param, array('firstId' => $this->accounts('testQuote')->id, 'secondId' => $this->contacts('testAnyone')->id, 'secondType' => 'Contacts')); $ch = $this->getCurlHandle($urlParam, $postData); $cr = curl_exec($ch); file_put_contents('api_response.html', $cr); $cr = json_decode($cr, 1); $this->assertTrue(is_array($cr), 'Request to put relationships failed utterly'); $this->assertResponseCodeIs(200, $ch, 'Something went wrong.'); $relatedModels = $this->accounts('testQuote')->relatedX2Models; $contactId = $this->contacts('testAnyone')->id; $newRelated = array_filter($relatedModels, function ($m) use($contactId) { return get_class($m) == 'Contacts' && $m->id == $contactId; }); $this->assertEquals(1, count($newRelated), 'Failed asserting that a new relationship was added.'); // Step 3: Test deletion (delete the one that was just created): $urlParam['{params}'] = '?' . http_build_query($postData, '', '&'); $ch = $this->getCurlHandle($urlParam); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE'); $cr = curl_exec($ch); $this->assertResponseCodeIs(200, $ch, "Couldn't delete. Response from server: " . $cr); }
/** * Creates a relationship between two models. * * Before the relationship is created, this function checks that the relationship * does not already exist * @param X2Model $firstType name of the class for the first model in this relationship * @param X2Model $firstId id of the first model in this relationship * @param X2Model $secondType name of the class for the second model in this relationship * @param X2Model $secondId id of the second model in this relationship * @return true if the relationship was created, false if it already exists * */ public static function create($firstType, $firstId, $secondType, $secondId, $firstLabel = '', $secondLabel = '') { $relationship = Relationships::model()->findByAttributes(array('firstType' => $firstType, 'firstId' => $firstId, 'secondType' => $secondType, 'secondId' => $secondId)); if ($relationship) { return false; } $relationship = Relationships::model()->findByAttributes(array('firstType' => $secondType, 'firstId' => $secondId, 'secondType' => $firstType, 'secondId' => $firstId)); if ($relationship) { return false; } $relationship = new Relationships(); $relationship->firstType = $firstType; $relationship->firstId = $firstId; $relationship->firstLabel = $firstLabel; $relationship->secondType = $secondType; $relationship->secondId = $secondId; $relationship->secondLabel = $secondLabel; $relationship->save(); return true; }
/** * Called by the duplicate checker when discarding the new record. */ public function actionDiscardNew() { if (isset($_POST['id'])) { $ref = $_POST['ref']; // Referring action $action = $_POST['action']; $oldId = $_POST['id']; if ($ref == 'create' && is_null($action) || $action == 'null') { echo CHtml::encode($oldId); return; } elseif ($ref == 'create') { $oldRecord = X2Model::model('Contacts')->findByPk($oldId); if (isset($oldRecord)) { $oldRecord->disableBehavior('X2TimestampBehavior'); Relationships::model()->deleteAllByAttributes(array('firstType' => 'Contacts', 'firstId' => $oldRecord->id)); Relationships::model()->deleteAllByAttributes(array('secondType' => 'Contacts', 'secondId' => $oldRecord->id)); if ($action == 'hideThis') { $oldRecord->dupeCheck = 1; $oldRecord->assignedTo = 'Anyone'; $oldRecord->visibility = 0; $oldRecord->doNotCall = 1; $oldRecord->doNotEmail = 1; $oldRecord->save(); $notif = new Notification(); $notif->user = '******'; $notif->createdBy = Yii::app()->user->getName(); $notif->createDate = time(); $notif->type = 'dup_discard'; $notif->modelType = 'Contacts'; $notif->modelId = $oldId; $notif->save(); return; } elseif ($action == 'deleteThis') { $oldRecord->delete(); return; } } } elseif (isset($_POST['newId'])) { $newId = $_POST['newId']; $oldRecord = X2Model::model('Contacts')->findByPk($oldId); $oldRecord->disableBehavior('X2TimestampBehavior'); $newRecord = Contacts::model()->findByPk($newId); $newRecord->disableBehavior('X2TimestampBehavior'); $newRecord->dupeCheck = 1; $newRecord->save(); if ($action === '') { $newRecord->delete(); echo CHtml::encode($oldId); return; } else { if (isset($oldRecord)) { if ($action == 'hideThis') { $oldRecord->dupeCheck = 1; $oldRecord->assignedTo = 'Anyone'; $oldRecord->visibility = 0; $oldRecord->doNotCall = 1; $oldRecord->doNotEmail = 1; $oldRecord->save(); $notif = new Notification(); $notif->user = '******'; $notif->createdBy = Yii::app()->user->getName(); $notif->createDate = time(); $notif->type = 'dup_discard'; $notif->modelType = 'Contacts'; $notif->modelId = $oldId; $notif->save(); } elseif ($action == 'deleteThis') { Relationships::model()->deleteAllByAttributes(array('firstType' => 'Contacts', 'firstId' => $oldRecord->id)); Relationships::model()->deleteAllByAttributes(array('secondType' => 'Contacts', 'secondId' => $oldRecord->id)); Tags::model()->deleteAllByAttributes(array('type' => 'Contacts', 'itemId' => $oldRecord->id)); Actions::model()->deleteAllByAttributes(array('associationType' => 'Contacts', 'associationId' => $oldRecord->id)); $oldRecord->delete(); } } echo CHtml::encode($newId); } } } }
/** * Remove a record with the same ID, save the model attributes in the container, and increment * the count of imported records * @param X2Model $model * @param array $modelContainer Array of validated models attributes * @param array $importedIds Array of ids from imported models */ protected function saveImportedModel(X2Model $model, $modelName, &$modelContainer, &$importedIds) { if (!empty($model->id)) { $lookup = X2Model::model(str_replace(' ', '', $modelName))->findByPk($model->id); if (isset($lookup)) { Relationships::model()->deleteAllByAttributes(array('firstType' => $modelName, 'firstId' => $lookup->id)); Relationships::model()->deleteAllByAttributes(array('secondType' => $modelName, 'secondId' => $lookup->id)); $lookup->delete(); unset($lookup); } } // Save our model & create the import records and // relationships. Passing $validate=false to CActiveRecord.save // because validation has already happened at this point $modelContainer[$modelName][] = $model->attributes; $_SESSION['imported']++; $importedIds[] = $model->id; }
/** * Action for viewing or modifying relationships on a model. * * @param type $_class * @param type $_id * @param type $_relatedId */ public function actionRelationships($_class = null, $_id = null, $_relatedId = null) { $method = Yii::app()->request->requestType; $relationship = null; if ($_relatedId !== null) { $relationship = Relationships::model()->findByPk($_relatedId); if (!$relationship instanceof Relationships) { $this->send(404, "Relationship with id={$_relatedId} not found."); } // Check whether the relationship is actually attached to this model: if ($_class !== null && $_id !== null && $relationship->firstId != $this->model->id && $relationship->secondId != $this->model->id && $relationship->firstType != $_class && $relationship->secondType != $_class) { $this->response->httpHeader['Location'] = $this->createAbsoluteUrl('/api2/relationships', array('_class' => $relationship->firstType, '_id' => $relationship->firstId, '_relatedId' => $relationship->id)); $this->send(303, "Specified relationship does not correspond " . "to {$_class} record {$_id}."); } } switch ($method) { case 'GET': if ($relationship !== null) { // Get an individual relationship record. Also, include the // resource URL of the related model. $which = $relationship->firstId == $_id && $relationship->firstType == $_class ? 'second' : 'first'; $relId = $which . 'Id'; $relType = $which . 'Type'; $this->response->httpHeader['Location'] = $this->createAbsoluteUrl('/api2/model', array('_class' => $relationship->{$relType}, '_id' => $relationship->{$relId})); $this->responseBody = $relationship; } else { // Query relationships on a model. $criteria = null; if (!$relationship instanceof Relationships) { // Both ingoing and outgoing relationships. $from = new CDbCriteria(); $to = new CDbCriteria(); $from->compare('firstType', $_class); $from->compare('firstId', $_id); $to->compare('secondType', $_class); $to->compare('secondId', $_id); $criteria = new CDbCriteria(); $criteria->mergeWith($from, 'OR'); $criteria->mergeWith($to, 'OR'); } $this->responseBody = $this->getDataProvider('Relationships', $criteria)->getData(); } break; case 'PATCH': case 'POST': case 'PUT': if (!$relationship instanceof Relationships) { if ($method !== 'POST') { // Cannot PUT on a nonexistent model $this->send(405, "Method \"POST\" is required to create new relationships."); } $relationship = new Relationships(); } // Scenario kludge that adds special validation rule for the // Relations model class, which dicates that it must point to // an existing record on both ends: $relationship->setScenario('api'); $relationship->setAttributes($this->jpost); // Set missing attributes, if any: if (empty($relationship->firstType)) { $relationship->firstType = $_class; $relationship->firstId = $_id; } elseif (empty($relationship->secondType)) { $relationship->secondType = $_class; $relationship->secondId = $_id; } if (!$relationship->save()) { // Validation errors $this->response['errors'] = $relationship->errors; $this->send(422); } else { $this->responseBody = $relationship; if ($method === 'POST') { // Set location header and respond with "201 Created" $this->response->httpHeader['Location'] = $this->createAbsoluteUrl('/api2/relationships', array('_class' => $_class, '_id' => $_id, '_relatedId' => $_relatedId)); $this->send(201, "Relationship created successfully"); } } break; case 'DELETE': if (!$relationship instanceof Relationships) { $this->send(400, "Cannot delete relationships without specifying which one to delete."); } if ($relationship->delete()) { $this->sendEmpty("Relationship {$_relatedId} deleted successfully."); } else { $this->send(500, "Failed to delete relationship #{$_relatedId}. It may have been deleted already."); } break; } }
public function testAfterDelete() { $contact = $this->contact('testAnyone'); $otherContact = $this->contact('testUser'); $this->assertFalse($contact->relationships->hasRelationship($otherContact)); $contact->relationships->createRelationship($otherContact); $this->assertTrue($contact->relationships->hasRelationship($otherContact)); $rel = $contact->relationships->getRelationship($otherContact); $this->assertNotNull($rel); $contact->delete(); $this->assertFalse($otherContact->relationships->hasRelationship($contact)); $this->assertNull(Relationships::model()->findByPk($rel->id)); }
public function actionQuickDelete($id) { $model = $this->loadModel($id); if ($model) { // delete associated actions Actions::model()->deleteAllByAttributes(array('associationId' => $id, 'associationType' => 'quotes')); // delete product relationships QuoteProduct::model()->deleteAllByAttributes(array('quoteId' => $id)); // delete contact relationships Relationships::model()->deleteAllByAttributes(array('firstType' => 'quotes', 'firstId' => $id, 'secondType' => 'contacts')); $name = $model->name; // generate history $contact = Contacts::model()->findByPk($_GET['contactId']); $action = new Actions(); $action->associationType = 'contacts'; $action->type = 'quotes'; $action->associationId = $contact->id; $action->associationName = $contact->name; $action->assignedTo = Yii::app()->user->getName(); $action->completedBy = Yii::app()->user->getName(); $action->createDate = time(); $action->dueDate = time(); $action->completeDate = time(); $action->visibility = 1; $action->complete = 'Yes'; $action->actionDescription = "Deleted Quote: <span style=\"font-weight:bold;\">{$model->id}</span> {$model->name}"; $action->save(); $this->cleanUpTags($model); $model->delete(); } else { throw new CHttpException(400, Yii::t('app', 'Invalid request. Please do not repeat this request again.')); } if ($_GET['contactId']) { Yii::app()->clientScript->scriptMap['*.js'] = false; $contact = Contacts::model()->findByPk($_GET['contactId']); $this->renderPartial('quoteFormWrapper', array('model' => $contact), false, true); } }
?> </td> <td style="text-align: center"><?php echo $child->idno; ?> </td> <td style="text-align: center"><?php echo $child->dob; ?> </td> <td style="text-align: center"><?php echo $child->alive == 1 ? "Yes" : "No"; ?> </td> <td style="text-align: center"><?php echo Relationships::model()->returnRelationship($child->relationship); ?> </td> </tr> <?php } ?> <?php } ?> </table> <?php } ?> </div>
/** * Add a record to record relationship * * A record can be a contact, opportunity, or account. This function is * called via ajax from the Relationships Widget. * */ public function actionAddRelationship() { //check if relationship already exits if (isset($_POST['ModelName']) && isset($_POST['ModelId']) && isset($_POST['RelationshipModelName']) && isset($_POST['RelationshipModelId'])) { $modelName = $_POST['ModelName']; $modelId = $_POST['ModelId']; $relationshipModelName = $_POST['RelationshipModelName']; $relationshipModelId = $_POST['RelationshipModelId']; $relationship = Relationships::model()->findByAttributes(array('firstType' => $_POST['ModelName'], 'firstId' => $_POST['ModelId'], 'secondType' => $_POST['RelationshipModelName'], 'secondId' => $_POST['RelationshipModelId'])); if ($relationship) { echo "duplicate"; Yii::app()->end(); } $relationship = Relationships::model()->findByAttributes(array('firstType' => $_POST['RelationshipModelName'], 'firstId' => $_POST['RelationshipModelId'], 'secondType' => $_POST['ModelName'], 'secondId' => $_POST['ModelId'])); if ($relationship) { echo "duplicate"; Yii::app()->end(); } if (isset($_POST['mutual']) && $_POST['mutual'] == 'true') { $_POST['secondLabel'] = $_POST['firstLabel']; } $relationship = new Relationships(); $relationship->firstType = $_POST['ModelName']; $relationship->firstId = $_POST['ModelId']; $relationship->firstLabel = $_POST['firstLabel']; $relationship->secondType = $_POST['RelationshipModelName']; $relationship->secondId = $_POST['RelationshipModelId']; $relationship->secondLabel = $_POST['secondLabel']; $relationship->save(); // if($relationshipModelName == "Contacts"){ // $results = Yii::app()->db->createCommand("SELECT * from x2_relationships WHERE (firstType='Contacts' AND firstId=$relationshipModelId AND secondType='Accounts') OR (secondType='Contacts' AND secondId=$relationshipModelId AND firstType='Accounts')")->queryAll(); // if(sizeof($results) == 1){ // $model = Contacts::model()->findByPk($relationshipModelId); // if($model){ // $model->company = $modelId; // $model->update(); // } // } // } echo "success"; Yii::app()->end(); } else { throw new CHttpException(400, Yii::t('app', 'Bad Request')); } }
public static function editContactArray($arr, $model) { $rels = Relationships::model()->findAllByAttributes(array('firstType' => 'Contacts', 'secondType' => 'Opportunity', 'secondId' => $model->id)); $pieces = array(); foreach ($rels as $relationship) { $contact = X2Model::model('Contacts')->findByPk($relationship->firstId); if (isset($contact)) { $pieces[$relationship->firstId] = $contact->name; } } unset($arr[0]); foreach ($pieces as $id => $contact) { if (isset($arr[$id])) { unset($arr[$id]); } } return $arr; }
public function testRelationships() { // Delete a relationship from the fixture data: $this->action = 'relationships_get'; $ch = $this->getCurlHandle('DELETE', array('{_class}' => 'Contacts', '{_id}' => $this->contacts('testFormula')->id, '{_relatedId}' => $this->relationships('blackMesaContact')->id), 'admin'); $oldRelationship = $this->relationships('blackMesaContact')->getAttributes(array('id', 'secondType', 'secondId')); $oldRelationId = $this->relationships('blackMesaContact')->id; $response = curl_exec($ch); $this->assertEmpty($response); $this->assertResponseCodeIs(204, $ch); $this->assertFalse((bool) Relationships::model()->findByPk($oldRelationId)); // Re-create it from fixture data: $this->action = 'relationships'; $ch = $this->getCurlHandle('POST', array('{_class}' => 'Contacts', '{_id}' => $this->contacts('testFormula')->id), 'admin', $oldRelationship); $response = curl_exec($ch); $this->assertResponseCodeIs(201, $ch); // Create it again just to test that validation works (don't set w/same ID) $ch = $this->getCurlHandle('POST', array('{_class}' => 'Contacts', '{_id}' => $this->contacts('testFormula')->id), 'admin', $oldRelationship); $response = json_decode(curl_exec($ch), 1); $this->assertResponseCodeIs(201, $ch); // Create it once more but with a nonexistent ID to test that validation works $oldRelationship['secondId'] = 2424242; $ch = $this->getCurlHandle('POST', array('{_class}' => 'Contacts', '{_id}' => $this->contacts('testFormula')->id), 'admin', $oldRelationship); $response = json_decode(curl_exec($ch), 1); $this->assertResponseCodeIs(422, $ch); }
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. ********************************************************************************/ Yii::app()->clientScript->registerScript('updateWorkflow', "\n\nfunction startWorkflowStage(workflowId,stageNumber) {\n\t\$.ajax({\n\t\turl: '" . CHtml::normalizeUrl(array('workflow/startStage')) . "',\n\t\ttype: 'GET',\n\t\tdata: 'workflowId='+workflowId+'&stageNumber='+stageNumber+'&modelId=" . $model->id . "&type=quotes',\n\t\tsuccess: function(response) {\n\t\t\tif(response!='')\n\t\t\t\t\$('#workflow-diagram').html(response);\n\t\t}\n\t});\n}\n\nfunction completeWorkflowStage(workflowId,stageNumber) {\n\t\$.ajax({\n\t\turl: '" . CHtml::normalizeUrl(array('workflow/completeStage')) . "',\n\t\ttype: 'GET',\n\t\tdata: 'workflowId='+workflowId+'&stageNumber='+stageNumber+'&modelId=" . $model->id . "&type=quotes',\n\t\tsuccess: function(response) {\n\t\t\tif(response!='')\n\t\t\t\t\$('#workflow-diagram').html(response);\n\t\t}\n\t});\n}\n\nfunction revertWorkflowStage(workflowId,stageNumber) {\n\t\$.ajax({\n\t\turl: '" . CHtml::normalizeUrl(array('workflow/revertStage')) . "',\n\t\ttype: 'GET',\n\t\tdata: 'workflowId='+workflowId+'&stageNumber='+stageNumber+'&modelId=" . $model->id . "&type=quotes',\n\t\tsuccess: function(response) {\n\t\t\tif(response!='')\n\t\t\t\t\$('#workflow-diagram').html(response);\n\t\t}\n\t});\n}\n", CClientScript::POS_HEAD); Yii::app()->clientScript->registerScript('detailVewFields', "\nfunction showField(field,focus){\n\t// \$(field).css('background','red');\n\t\$(field).find('.detail-field').hide();\n\t\$(field).find('.detail-form').show();\n\tif(focus)\n\t\t\$(field).find('input').focus();\n\thighlightSave();\n}\nfunction highlightSave() {\n\t\$('#save-changes').css('background','yellow');\n}\n", CClientScript::POS_HEAD); Yii::app()->clientScript->registerScript('stopEdit', ' $(document).ready(function(){ $("td#description a").click(function(e){ e.stopPropagation(); }); }); '); $relationships = Relationships::model()->findAllByAttributes(array('firstType' => 'quotes', 'firstId' => $model->id, 'secondType' => 'contacts')); $associatedContacts = array(); foreach ($relationships as $relationship) { $contact = Contacts::model()->findByPk($relationship->secondId); $associatedContacts[] = CHtml::link($contact->name, array('contacts/view', 'id' => $contact->id)); } $associatedContacts = implode(', ', $associatedContacts); ?> <div class="x2-layout"> <div class="formSection"> <div class="formSectionHeader"> <span class="sectionTitle">Basic Information</span> </div> <div class="tableWrapper">
</td> <td> </td> <td> <?php if ($_REQUEST['rltn1'] == 4) { $model->relationship = $jamaa->gender == 'Male' ? 9 : 4; } $rln1 = $_REQUEST['rltn1'] == 4 && $jamaa->gender == 'Male' ? $_REQUEST['rltn2'] : $_REQUEST['rltn1']; $rln2 = $_REQUEST['rltn1'] == 4 && $jamaa->gender == 'Female' ? $_REQUEST['rltn1'] : $_REQUEST['rltn2']; $cri = new CDbCriteria(); $cri->condition = 'id=:id1 || id=:id2'; $cri->params = array(':id1' => $rln1, ':id2' => $rln2); $cri->order = 'relationship ASC'; $rlns = Relationships::model()->findAll($cri); $rlns = CHtml::listData($rlns, 'id', 'relationship'); ?> <?php echo $form->dropDownList($model, "[{$i}]relationship", $rlns, array()); ?> </td> <td> </td> <td> <?php echo $form->textField($model, "[{$i}]mobileno", array('size' => 10, 'maxlength' => 10, 'placeholder' => $model->getAttributeLabel('mobileno'))); ?> </td> <td>