/** * Creates a new or modifies an exisitng specification field (according to a passed parameters) * * @return JSONResponse Returns success status or failure status with array of erros */ private function save(ProductOption $productOption) { $this->getProductOptionConfig(); $errors = $this->validate($this->request->getValueArray(array('values', 'name', 'type', 'parentID', 'ID')), $this->productOptionConfig['languageCodes']); if (!$errors) { $productOption->loadRequestData($this->request); $productOption->save(); // create a default choice for non-select options if (!$productOption->isSelect()) { if (!$productOption->defaultChoice->get()) { $defChoice = ProductOptionChoice::getNewInstance($productOption); } else { $defChoice = $productOption->defaultChoice->get(); $defChoice->load(); } $defChoice->loadRequestData($this->request); $defChoice->save(); if (!$productOption->defaultChoice->get()) { $productOption->defaultChoice->set($defChoice); $productOption->save(); } } $parentID = (int) $this->request->get('parentID'); $values = $this->request->get('values'); // save specification field values in database $newIDs = array(); if ($productOption->isSelect() && is_array($values)) { $position = 1; $countValues = count($values); $i = 0; $prices = $this->request->get('prices'); foreach ($values as $key => $value) { $i++; // If last new is empty miss it if ($countValues == $i && preg_match('/new/', $key) && empty($value[$this->productOptionConfig['languageCodes'][0]])) { continue; } if (preg_match('/^new/', $key)) { $productOptionValues = ProductOptionChoice::getNewInstance($productOption); } else { $productOptionValues = ProductOptionChoice::getInstanceByID((int) $key); } $productOptionValues->setLanguageField('name', $value, $this->productOptionConfig['languageCodes']); $productOptionValues->priceDiff->set($prices[$key]); $productOptionValues->position->set($position++); $productOptionValues->save(); if (preg_match('/^new/', $key)) { $newIDs[$productOptionValues->getID()] = $key; } } } return new JSONResponse(array('id' => $productOption->getID(), 'newIDs' => $newIDs), 'success'); } else { return new JSONResponse(array('errors' => $this->translateArray($errors))); } }