public function testClone() { $text = EavField::getNewInstance('User', EavField::DATATYPE_TEXT, EavField::TYPE_TEXT_SIMPLE); $text->save(); $singleSel = EavField::getNewInstance('User', EavField::DATATYPE_NUMBERS, EavField::TYPE_NUMBERS_SELECTOR); $singleSel->handle->set('single.sel'); $singleSel->setValueByLang('name', 'en', 'Select one value'); $singleSel->save(); $value1 = EavValue::getNewInstance($singleSel); $value1->setValueByLang('value', 'en', $firstValue = '20'); $value1->save(); $value2 = EavValue::getNewInstance($singleSel); $value2->setValueByLang('value', 'en', $secValue = '30'); $value2->save(); $user = User::getNewInstance('*****@*****.**'); $user->save(); $spec = $user->getSpecification(); $spec->setAttributeValueByLang($text, 'en', 'text'); $spec->setAttributeValue($singleSel, $value1); $user->save(); $cloned = clone $user; $cloned->email->set('*****@*****.**'); $cloned->save(); $this->assertNotSame($cloned->getSpecification(), $user->getSpecification()); $this->assertEquals($cloned->getSpecification()->getAttribute($text)->getValueByLang('value', 'en'), 'text'); ActiveRecordModel::clearPool(); $reloaded = ActiveRecordModel::getInstanceByID('User', $cloned->getID(), true); $this->assertEquals($reloaded->getSpecification()->getAttribute($text)->getValueByLang('value', 'en'), 'text'); $this->assertEquals($reloaded->getSpecification()->getAttribute($singleSel)->getValue()->get()->getID(), $value1->getID()); }
public function save() { $validator = $this->createValidator(); if (!$validator->isValid()) { return new JSONResponse(array('errors' => $validator->getErrorList(), 'failure')); } if ($id = $this->request->get('id')) { $newsletter = ActiveRecordModel::getInstanceByID('NewsletterMessage', $id); } else { $newsletter = ActiveRecordModel::getNewInstance('NewsletterMessage'); } $format = $this->request->get('newsletter_' . $id . '_format'); if ($format == self::FORMAT_TEXT) { $this->request->set('html', ''); } else { if ($format == self::FORMAT_HTML) { $this->request->set('text', ''); } } $newsletter->loadRequestData($this->request); $newsletter->save(); if ($this->request->get('sendFlag')) { return $this->send($newsletter); } return new JSONResponse($newsletter->toArray()); }
protected function getInstance($record, CsvImportProfile $profile) { $fields = $profile->getSortedFields(); if (isset($fields['ProductReview']['ID'])) { $instance = ActiveRecordModel::getInstanceByID('ProductReview', $record[$fields['ProductReview']['ID']], true); } else { if (isset($fields['Product']['ID'])) { $parent = ActiveRecordModel::getInstanceByID('Product', $record[$fields['Product']['ID']], true); } else { if (isset($fields['Product']['sku'])) { $parent = Product::getInstanceBySku($record[$fields['Product']['sku']]); } else { return; } } } if (empty($instance) && empty($parent)) { return; } if (empty($instance)) { $instance = ProductReview::getNewInstance($parent, User::getNewInstance('')); $instance->isEnabled->set(true); } return $instance; }
/** * @role update */ public function edit() { $form = $this->buildForm(); $type = ActiveRecordModel::getInstanceByID('ProductRatingType', $this->request->get('id'), ProductRatingType::LOAD_DATA); $form->loadData($type->toArray()); return new ActionResponse('form', $form); }
public function destroy($id) { try { $inst = ActiveRecordModel::getInstanceByID('SessionData', $id, true); $inst->delete(); return true; } catch (Exception $e) { return false; } }
/** * @role update */ public function sort() { $target = $this->request->get('target'); preg_match('/_(\\d+)$/', $target, $match); // Get group. $productID = $match[1]; foreach ($this->request->get($this->request->get('target'), array()) as $position => $id) { $item = ActiveRecordModel::getInstanceByID('ProductBundle', array('productID' => $productID, 'relatedProductID' => $id), ActiveRecord::LOAD_DATA); $item->position->set($position); $item->save(); } return new JSONResponse(false, 'success'); }
/** * @role update */ public function sort() { $target = $this->request->get('target'); preg_match('/_(\\d+)$/', $target, $match); // Get group. foreach ($this->request->get($this->request->get('target'), array()) as $position => $id) { $item = ActiveRecordModel::getInstanceByID('ProductListItem', $id); $item->position->set($position); if (isset($match[1])) { $item->productList->set(ActiveRecordModel::getInstanceById('ProductList', $match[1])); } $item->save(); } return new JSONResponse(false, 'success'); }
protected function getInstance($record, CsvImportProfile $profile) { $fields = $profile->getSortedFields(); if (isset($fields['NewsPost']['ID'])) { try { $instance = ActiveRecordModel::getInstanceByID('NewsPost', $record[$fields['NewsPost']['ID']], true); } catch (ARNotFoundException $e) { } } if (empty($instance)) { $instance = ActiveRecordModel::getNewInstance('NewsPost'); } //$this->setLastImportedRecordName($instance->getID()); return $instance; }
protected function getInstance($record, CsvImportProfile $profile) { pp('User address import get instance'); $fields = $profile->getSortedFields(); if (isset($fields['UserAddress']['ID'])) { $instance = ActiveRecordModel::getInstanceByID('UserAddress', $record[$fields['UserAddress']['ID']], true); } else { if (isset($fields['AddressUser']['ID'])) { $owner = User::getInstanceByID($record[$fields['AddressUser']['ID']], true); } else { if (isset($fields['AddressUser']['email'])) { $owner = User::getInstanceByEmail($record[$fields['AddressUser']['email']]); } } } if (isset($owner)) { if ($profile->isColumnSet('AddressUser.isShipping')) { $type = $this->evalBool(strtolower($record[$profile->getColumnIndex('AddressUser.isShipping')])) ? 'ShippingAddress' : 'BillingAddress'; } else { $type = 'BillingAddress'; } $owner->loadAddresses(); } if (empty($instance)) { if (empty($owner)) { return; } $isDefault = $profile->isColumnSet('AddressUser.isDefault') && $this->evalBool(strtolower($record[$profile->getColumnIndex('AddressUser.isDefault')])); if ($isDefault) { $field = 'default' . $type; $addressType = $owner->{$field}->get(); $instance = $addressType->userAddress->get(); } if (empty($addressType)) { $instance = UserAddress::getNewInstance(); $addressType = call_user_func_array(array($type, 'getNewInstance'), array($owner, $instance)); if ($isDefault) { $owner->{$field}->set($addressType); } } $addressType->userAddress->set($instance); $instance->addressType = $addressType; } return $instance; }
protected function getInstance($record, CsvImportProfile $profile) { $fields = $profile->getSortedFields(); if (isset($fields['NewsletterSubscriber']['ID'])) { $instance = ActiveRecordModel::getInstanceByID('NewsletterSubscriber', $record[$fields['NewsletterSubscriber']['ID']], true); } else { if (isset($fields['NewsletterSubscriber']['email'])) { $instance = NewsletterSubscriber::getInstanceByEmail($record[$fields['NewsletterSubscriber']['email']]); } else { return; } } if (empty($instance)) { $instance = NewsletterSubscriber::getNewInstanceByEmail($record[$fields['NewsletterSubscriber']['email']]); } $this->setLastImportedRecordName($instance->email->get()); return $instance; }
function testCloning() { $user = User::getNewInstance('*****@*****.**'); $user->firstName->set('Rinalds'); $user->lastName->set('Uzkalns'); $user->save(); $state = ActiveRecordModel::getInstanceByID('State', 2, ActiveRecordModel::LOAD_DATA); $address = UserAddress::getNewInstance(); $address->city->set('Vilnius'); $address->state->set($state); $address->save(); $newAddress = clone $address; // simple value $this->assertEqual($address->city->get(), $newAddress->city->get()); // foreign key $this->assertEqual($address->state->get(), $newAddress->state->get()); $newAddress->save(); // primary key (autoincrement) $this->assertNotEquals($address->getID(), $newAddress->getID()); }
public static function getRealTimeRates(ShippingRateCalculator $handler, Shipment $shipment) { $rates = new ShippingRateSet(); $handler->setWeight($shipment->getChargeableWeight()); $order = $shipment->order->get(); // TODO: fix issue when address has zip and country data, but are missing city, user and record id! // (now workround - get address id, if $address has no id, load address by id) if ($order->isMultiAddress->get()) { $address = $shipment->shippingAddress->get(); $arr = $shipment->toArray(); } else { $address = $order->shippingAddress->get(); $arr = $order->toArray(); } if (!$address->getID() && array_key_exists('shippingAddressID', $arr)) { $address = ActiveRecordModel::getInstanceByID('UserAddress', $arr['shippingAddressID'], true); } if (!$address) { return $rates; } $handler->setDestCountry($address->countryID->get()); $handler->setDestState($address->state->get() ? $address->state->get()->code->get() : $address->stateName->get()); $handler->setDestZip($address->postalCode->get()); $handler->setDestCity($address->city->get()); $config = $shipment->getApplication()->getConfig(); $handler->setSourceCountry($config->get('STORE_COUNTRY')); $handler->setSourceZip($config->get('STORE_ZIP')); $handler->setSourceState($config->get('STORE_STATE')); foreach ($handler->getAllRates() as $k => $rate) { $newRate = new ShipmentDeliveryRate(); $newRate->setApplication($shipment->getApplication()); $newRate->setCost($rate->getCostAmount(), $rate->getCostCurrency()); $newRate->setServiceName($rate->getServiceName()); $newRate->setClassName($rate->getClassName()); $newRate->setProviderName($rate->getProviderName()); $newRate->setServiceId($rate->getClassName() . '_' . $k); $rates->add($newRate); } return $rates; }
public function testSettingValues() { $field = EavField::getNewInstance('User', EavField::DATATYPE_TEXT, EavField::TYPE_TEXT_SIMPLE); $field->save(); $user = User::getNewInstance('*****@*****.**'); $user->save(); $spec = $user->getSpecification(); $this->assertIsA($spec, 'EavSpecificationManager'); $testValue = 'something'; $spec = $user->getSpecification(); $this->assertSame($spec, $user->getSpecification()); $spec->setAttributeValueByLang($field, 'en', $testValue); $attr = $spec->getAttribute($field); $this->assertEqual($testValue, $attr->getValueByLang('value', 'en')); $spec->save(); $id = $user->getID(); unset($user); ActiveRecordModel::clearPool(); $user = ActiveRecordModel::getInstanceByID('User', $id, ActiveRecordModel::LOAD_DATA); $spec = $user->getSpecification(); $attr = $spec->getAttribute($field); $this->assertEqual($testValue, $attr->getValueByLang('value', 'en')); }
/** * Remove a product from shopping cart */ public function delete() { $item = ActiveRecordModel::getInstanceByID('OrderedItem', $this->request->get('id'), ActiveRecordModel::LOAD_DATA, array('Product')); $this->setMessage($this->makeText('_removed_from_cart', array($item->getProduct()->getName($this->getRequestLanguage())))); $this->order->removeItem($item); SessionOrder::save($this->order); return new ActionRedirectResponse('order', 'index', array('query' => 'return=' . $this->request->get('return'))); }
public function testLoadAllReferencesIncludingAutoLoad() { $child = ActiveRecordModel::getNewInstance('LoadReferenceChild'); $child->name->set('child'); $child->setID(4); $child->save(); $parent = ActiveRecordModel::getNewInstance('LoadReferenceParent'); $parent->setID(4); $parent->name->set('parent'); $parent->reference->set($child); $parent->save(); $super = ActiveRecordModel::getNewInstance('LoadReferenceSuper'); $super->setID(1); $super->name->set('super'); $super->reference->set($parent); $super->save(); $schema = ActiveRecordModel::getSchemaInstance('LoadReferenceParent'); $schema->registerAutoReference('referenceID'); ActiveRecordModel::clearPool(); $newSuper = ActiveRecordModel::getInstanceByID('LoadReferenceSuper', 1, ActiveRecordModel::LOAD_DATA, true); $this->assertNotSame($child, $newSuper->reference->get()->reference->get()); $this->assertNotSame($newSuper->reference->get(), $newSuper->reference->get()->reference->get()); $this->assertEqual('child', $newSuper->reference->get()->reference->get()->name->get()); }
/** * Save image order * @return RawResponse */ public function saveOrder($order = null) { $ownerId = $this->request->get('ownerId'); if ($order === null) { $varName = array_shift(explode('_', $this->request->get('draggedID'))); $order = array_filter($this->request->get($varName . '_' . $ownerId), array($this, 'filterOrder')); $order = array_values($order); } foreach ($order as $key => $value) { $update = new ARUpdateFilter(); $update->setCondition(new EqualsCond(new ARFieldHandle($this->getModelClass(), 'ID'), $value)); $update->addModifier('position', $key); ActiveRecord::updateRecordSet($this->getModelClass(), $update); } // set owners main image if (isset($order[0])) { $owner = ActiveRecordModel::getInstanceByID($this->getOwnerClass(), $ownerId); $owner->defaultImage->set(ActiveRecordModel::getInstanceByID($this->getModelClass(), $order[0])); $owner->save(); } $resp = new RawResponse(); $resp->setContent($this->request->get('draggedId')); return $resp; }
private function saveAddresses(User $user = null) { $user->loadAddresses(); foreach (array('defaultBillingAddress' => 'billingAddress', 'defaultShippingAddress' => 'shippingAddress') as $field => $prefix) { $address = $user->{$field}->get() ? $user->{$field}->get()->userAddress->get() : UserAddress::getNewInstance(); $address->loadRequestData($this->request, $prefix . '_'); // get address state if ($stateID = $this->request->get($prefix . '_stateID')) { $address->state->set(ActiveRecordModel::getInstanceByID('State', $stateID, ActiveRecordModel::LOAD_DATA)); $address->stateName->setNull(); } else { $address->stateName->set($this->request->get($prefix . '_stateName')); $address->state->setNull(); } $modified = false; foreach (ActiveRecordModel::getSchemaInstance('UserAddress')->getFieldList() as $f) { if ($address->getFieldValue($f->getName())) { $modified = true; } } if ($modified) { $address->save(); if (!$user->{$field}->get()) { $addressType = call_user_func_array(array($prefix, 'getNewInstance'), array($user, $address)); $addressType->save(); } } } if ($this->request->get('sameAddresses') && $user->defaultBillingAddress->get()) { $shippingAddress = ShippingAddress::getNewInstance($user, clone $user->defaultBillingAddress->get()->userAddress->get()); $shippingAddress->save(); } }
public function updateActionField() { list($fieldName, $id) = explode('_', $this->request->get('field')); $value = $this->request->get('value'); $action = ActiveRecordModel::getInstanceByID('DiscountAction', $id, DiscountAction::LOAD_DATA, array('DiscountCondition', 'DiscountCondition_ActionCondition')); if ('type' == $fieldName) { switch ($value) { case DiscountAction::TYPE_ORDER_DISCOUNT: $action->type->set(DiscountAction::TYPE_ORDER_DISCOUNT); $action->actionCondition->set(null); break; case DiscountAction::TYPE_ITEM_DISCOUNT: $action->type->set(DiscountAction::TYPE_ITEM_DISCOUNT); $action->actionCondition->set($action->condition->get()); break; case DiscountAction::TYPE_CUSTOM_DISCOUNT: $newCondition = DiscountCondition::getNewInstance(); $newCondition->isEnabled->set(true); $newCondition->isActionCondition->set(true); $newCondition->isAnyRecord->set(true); $newCondition->save(); $action->actionCondition->set($newCondition); $action->type->set(DiscountAction::TYPE_ITEM_DISCOUNT); $action->save(); return new JSONResponse(array('field' => $fieldName, 'condition' => $newCondition->toArray())); break; } } else { if ($this->request->get('isParam') != 'false') { $action->setParamValue($fieldName, $value); $fieldName .= '_' . $action->getID(); } else { $action->{$fieldName}->set($value); } } $action->save(); return new JSONResponse($fieldName); }
private function getStore() { return ActiveRecordModel::getInstanceByID('ClonedStore', $this->request->get('id'), true); }
public function changeRecurringProductPeriod() { $request = $this->getRequest(); $orderedItemID = $request->get('id'); $billingPlandropdownName = $request->get('recurringBillingPlan'); $recurringID = $request->get($billingPlandropdownName); $orderedItem = ActiveRecordModel::getInstanceByID('OrderedItem', $orderedItemID, true); $recurringItem = RecurringItem::getInstanceByOrderedItem($orderedItem); if ($recurringItem) { $recurringItem->setRecurringProductPeriod(RecurringProductPeriod::getInstanceByID($recurringID)); $recurringItem->save(); $orderedItem->updateBasePriceToCalculatedPrice(); } $this->order->loadItemData(); $this->order->mergeItems(); $this->order->save(); return new ActionRedirectResponse('order', 'index', array('query' => 'return=' . $this->request->get('return'))); }
public function __clone() { parent::__clone(); $original = $this->originalRecord; $original->loadSpecification(); $this->specificationInstance = clone $original->getSpecification(); $this->specificationInstance->setOwner($this); $original->loadPricing(); $this->pricingHandlerInstance = clone $original->pricingHandlerInstance; $this->pricingHandlerInstance->setProduct($this); $this->save(); // images if ($original->defaultImage->get()) { foreach ($original->getRelatedRecordSet('ProductImage', $original->getImageFilter()) as $image) { $image->_clone($this); } } // options foreach (ProductOption::getProductOptions($original) as $option) { $clonedOpt = clone $option; $clonedOpt->product->set($this); $clonedOpt->save(); } // variations $variations = $original->getRelatedRecordSet('Product'); if ($variations->size()) { $idMap = array(); foreach ($original->getRelatedRecordSet('ProductVariationType') as $type) { $newType = clone $type; $newType->product->set($this); $newType->save(); foreach ($type->getRelatedRecordSet('ProductVariation') as $var) { $newVar = clone $var; $newVar->type->set($newType); $newVar->save(); $idMap[$var->getID()] = $newVar->getID(); } } foreach ($variations as $variation) { $newVariation = clone $variation; $newVariation->parent->set($this); $newVariation->save(); foreach ($variation->getRelatedRecordSet('ProductVariationValue') as $value) { $newValue = clone $value; $newValue->product->set($newVariation); $newValue->variation->set(ActiveRecordModel::getInstanceByID('ProductVariation', $idMap[$value->variation->get()->getID()], true)); $newValue->save(); } } } // additional categories foreach ($original->getRelatedRecordSet('ProductCategory') as $additionalCat) { $newCat = clone $additionalCat; $newCat->product->set($this); $newCat->save(); } // related products $groups[] = array(); foreach ($original->getRelationships() as $relationship) { $group = $relationship->productRelationshipGroup->get(); $id = $group ? $group->getID() : null; if ($id) { $groups[$id] = clone $group; $groups[$id]->product->set($this); $groups[$id]->save(); } $cloned = ProductRelationship::getNewInstance($this, $relationship->relatedProduct->get(), $id ? $groups[$id] : null); $cloned->save(); } }
public static function getOwnerInstance($className, $id) { return ActiveRecordModel::getInstanceByID($className, $id, ActiveRecordModel::LOAD_DATA); }
protected function getGroupInstanceByID($id, $loadData = true) { return ActiveRecordModel::getInstanceByID($this->getGroupClassName(), $id, $loadData); }
protected function getStoreFile() { $store = ActiveRecordModel::getInstanceByID('ClonedStore', $this->request->get('id'), true); if ($this->request->get('password') != md5($store->apiKey->get())) { return new RawResponse('Wrong password'); } return $store->getFileDir() . '/' . $this->request->get('file'); }
/** * @return Form */ public function createUserAddressForm($addressArray = array(), ActionResponse $response) { $form = new Form($this->createUserAddressFormValidator()); if (!empty($addressArray)) { if (isset($addressArray['State']['ID'])) { $addressArray['stateID'] = $addressArray['State']['ID']; } $form->setData($addressArray); } $address = !empty($addressArray['ID']) ? ActiveRecordModel::getInstanceByID('UserAddress', $addressArray['ID'], true) : UserAddress::getNewInstance(); $address->getSpecification()->setFormResponse($response, $form); return $form; }
public function save() { ActiveRecordModel::beginTransaction(); $parent = Product::getInstanceByID($this->request->get('id'), true); $items = json_decode($this->request->get('items'), true); $types = json_decode($this->request->get('types'), true); $variations = json_decode($this->request->get('variations'), true); $existingTypes = $existingVariations = $existingItems = array(); $currency = $this->application->getDefaultCurrencyCode(); // deleted types foreach ($types as $id) { if (is_numeric($id)) { $existingTypes[] = $id; } } $parent->deleteRelatedRecordSet('ProductVariationType', new ARDeleteFilter(new NotINCond(new ARFieldHandle('ProductVariationType', 'ID'), $existingTypes))); // deleted variations foreach ($variations as $type => $typeVars) { foreach ($typeVars as $id) { if (is_numeric($id)) { $existingVariations[] = $id; } } } $f = new ARDeleteFilter(new INCond(new ARFieldHandle('ProductVariation', 'typeID'), $existingTypes)); $f->mergeCondition(new NotINCond(new ARFieldHandle('ProductVariation', 'ID'), $existingVariations)); ActiveRecordModel::deleteRecordSet('ProductVariation', $f); // deleted items foreach ($items as $id) { if (is_numeric($id)) { $existingItems[] = $id; } } $parent->deleteRelatedRecordSet('Product', new ARDeleteFilter(new NotINCond(new ARFieldHandle('Product', 'ID'), $existingItems))); // load existing records foreach (array('Types' => 'ProductVariationType', 'Variations' => 'ProductVariation', 'Items' => 'Product') as $arr => $class) { $var = 'existing' . $arr; $array = ${$var}; if ($array) { ActiveRecordModel::getRecordSet($class, new ARSelectFilter(new INCond(new ARFieldHandle($class, 'ID'), $array))); } } $idMap = array(); // save types $request = $this->request->toArray(); foreach ($types as $index => $id) { if (!is_numeric($id)) { $type = ProductVariationType::getNewInstance($parent); $idMap[$id] = $type; } else { $type = ActiveRecordModel::getInstanceByID('ProductVariationType', $id); } $type->setValueByLang('name', null, $request['variationType'][$index]); $type->position->set($index); if (!empty($request['typeLang_' . $id])) { foreach ($request['typeLang_' . $id] as $field => $value) { list($field, $lang) = explode('_', $field, 2); $type->setValueByLang($field, $lang, $value); } } $type->save(); } // save variations $tree = array(); $typeIndex = -1; foreach ($variations as $typeID => $typeVars) { $type = is_numeric($typeID) ? ActiveRecordModel::getInstanceByID('ProductVariationType', $typeID) : $idMap[$typeID]; $typeIndex++; foreach ($typeVars as $index => $id) { if (!is_numeric($id)) { $variation = ProductVariation::getNewInstance($type); $idMap[$id] = $variation; } else { $variation = ActiveRecordModel::getInstanceByID('ProductVariation', $id); } $variation->position->set($index); $variation->setValueByLang('name', null, $request['variation'][$id]); if (!empty($request['variationLang_' . $id])) { foreach ($request['variationLang_' . $id] as $field => $value) { list($field, $lang) = explode('_', $field, 2); $variation->setValueByLang($field, $lang, $value); } } $variation->save(); $tree[$typeIndex][] = $variation; } } $images = array(); // save items foreach ($items as $index => $id) { if (!is_numeric($id)) { $item = $parent->createChildProduct(); $idMap[$id] = $item; } else { $item = ActiveRecordModel::getInstanceByID('Product', $id); } $item->isEnabled->set(!empty($request['isEnabled'][$id])); if (!$request['sku'][$index]) { $request['sku'][$index] = $item->sku->get(); } foreach (array('sku', 'stockCount', 'shippingWeight') as $field) { if ($item->{$field}->get() || $request[$field][$index]) { $item->{$field}->set($request[$field][$index]); } } $item->setChildSetting('weight', $request['shippingWeightType'][$index]); $item->setChildSetting('price', $request['priceType'][$index]); if (!strlen($request['priceType'][$index])) { $request['price'][$index] = ''; } $item->setPrice($currency, $request['price'][$index]); $item->save(); // assign variations $currentVariationValues = $currentVariations = array(); foreach ($item->getRelatedRecordSet('ProductVariationValue') as $variationValue) { $currentVariations[$variationValue->variation->get()->getID()] = $variationValue->variation->get(); $currentVariationValues[$variationValue->variation->get()->getID()] = $variationValue; } foreach ($this->getItemVariations($tree, $index) as $variation) { if (!isset($currentVariations[$variation->getID()])) { ProductVariationValue::getNewInstance($item, $variation)->save(); } unset($currentVariations[$variation->getID()]); } foreach ($currentVariations as $deletedVariation) { $currentVariationValues[$deletedVariation->getID()]->delete(); } // set image if ($_FILES['image']['tmp_name'][$index]) { if ($item->defaultImage->get()) { $item->defaultImage->get()->load(); $image = $item->defaultImage->get(); } else { $image = ProductImage::getNewInstance($item); } $image->save(); $image->setFile($_FILES['image']['tmp_name'][$index]); $image->save(); $images[$item->getID()] = $image->toArray(); unset($images[$item->getID()]['Product']); } } ActiveRecordModel::commit(); // pass ID's for newly created records $ids = array(); foreach ($idMap as $id => $instance) { $ids[$id] = $instance->getID(); } $response = new ActionResponse('ids', $ids); $response->set('parent', $parent->getID()); $response->set('images', $images); $response->set('variationCount', $parent->getRelatedRecordCount('Product', new ARSelectFilter(new EqualsCond(new ARFieldHandle('Product', 'isEnabled'), true)))); return $response; }
/** * Gets an existing record instance (persisted on a database). * * @param mixed $recordID * @param bool $loadRecordData * @param bool $loadReferencedRecords * @param array $data Record data array (may include referenced record data) * * @return User */ public static function getInstanceByID($recordID, $loadRecordData = false, $loadReferencedRecords = array('UserGroup'), $data = array()) { return parent::getInstanceByID(__CLASS__, $recordID, $loadRecordData, $loadReferencedRecords, $data); }
private function save(Product $product) { ClassLoader::import('application.model.presentation.CategoryPresentation'); $validator = $this->buildValidator($product); if ($validator->isValid()) { $product->loadRequestData($this->request); foreach (array('ShippingClass' => 'shippingClassID', 'TaxClass' => 'taxClassID') as $class => $field) { $value = $this->request->get($field, null); $instance = $value ? ActiveRecordModel::getInstanceByID($class, $value) : null; $product->setFieldValue($field, $instance); } $product->save(); // presentation $instance = CategoryPresentation::getInstance($product); $instance->loadRequestData($this->request); $instance->save(); // save pricing $product->loadSpecification(); $product->loadPricing(); if ($quantities = $this->request->get('quantityPricing')) { foreach ($product->getRelatedRecordSet('ProductPrice', new ARSelectFilter()) as $price) { $id = $price->currency->get()->getID(); $prices = array(); if (!empty($quantities[$id])) { $values = json_decode($quantities[$id], true); $prices = array(); // no group selected - set all customers if ('' == $values['group'][0]) { $values['group'][0] = 0; } $quantCount = count($values['quant']); foreach ($values['group'] as $groupIndex => $group) { foreach ($values['quant'] as $quantIndex => $quant) { $pr = $values['price'][$groupIndex * $quantCount + $quantIndex]; if (strlen($pr) != 0) { $prices[$quant][$group] = (double) $pr; } } } } ksort($prices); $price->serializedRules->set(serialize($prices)); $price->save(); } } // $product->loadRequestData($this->request); // $product->save(); if ($this->isQuickEdit == false) { BackendToolbarItem::registerLastViewedProduct($product); } $response = $this->productForm($product); $response->setHeader('Cache-Control', 'no-cache, must-revalidate'); $response->setHeader('Expires', 'Mon, 26 Jul 1997 05:00:00 GMT'); $response->setHeader('Content-type', 'text/javascript'); return $response; } else { // reset validator data (as we won't need to restore the form) $validator->restore(); return new JSONResponse(array('errors' => $validator->getErrorList(), 'failure', $this->translate('_could_not_save_product_information'))); } }
private function createAddress($prefix) { // get address state if ($this->request->get($prefix . 'state_select')) { try { $state = ActiveRecordModel::getInstanceByID('State', $this->request->get($prefix . 'state_select'), ActiveRecordModel::LOAD_DATA); } catch (Exception $e) { throw new ApplicationException('State not found'); } $country = $state->countryID->get(); } else { $country = $this->request->get($prefix . 'country'); } $address = UserAddress::getNewInstance(); $address->loadRequestData($this->request, $prefix); if (isset($state)) { $address->state->set($state); } else { $address->stateName->set($this->request->get($prefix . 'state_text')); } $address->countryID->set($country); $address->save(); return $address; }
protected function importAttributes(ActiveRecordModel $instance, $record, $fields, $attrIdentifier = 'eavField') { if (isset($fields[$attrIdentifier])) { $impReq = new Request(); $fieldClass = ucfirst($attrIdentifier); $valueClass = 'eavField' == $attrIdentifier ? 'EavValue' : $fieldClass . 'Value'; foreach ($fields[$attrIdentifier] as $specFieldID => $csvIndex) { if (empty($record[$csvIndex])) { continue; } $attr = ActiveRecordModel::getInstanceByID($fieldClass, $specFieldID, ActiveRecord::LOAD_DATA); if ($attr->isSimpleNumbers()) { $impReq->set($attr->getFormFieldName(), (double) $record[$csvIndex]); } else { if ($attr->isSelector()) { if ($attr->isMultiValue->get()) { $values = explode(',', $record[$csvIndex]); } else { $values = array($record[$csvIndex]); } foreach ($values as $fieldValue) { $fieldValue = trim($fieldValue); $f = new ARSelectFilter(new LikeCond(MultilingualObject::getLangSearchHandle(new ARFieldHandle($valueClass, 'value'), $this->application->getDefaultLanguageCode()), $fieldValue . '%')); $f->setLimit(1); if (!($value = $attr->getRelatedRecordSet($valueClass, $f)->shift())) { $value = call_user_func_array(array($valueClass, 'getNewInstance'), array($attr)); if ($attr->type->get() == EavFieldCommon::TYPE_NUMBERS_SELECTOR) { $value->value->set($fieldValue); } else { $value->setValueByLang('value', $this->application->getDefaultLanguageCode(), $fieldValue); } $value->save(); } if (!$attr->isMultiValue->get()) { $impReq->set($attr->getFormFieldName(), $value->getID()); } else { $impReq->set($value->getFormFieldName(), true); } } } else { $impReq->set($attr->getFormFieldName(), $record[$csvIndex]); } } } $instance->loadRequestData($impReq); $instance->save(); } }