/** * Shows a bug with opportunity as a product relation. The bug is when there is a default customField value * The fix is the use of isReallyModified() to now determine if during save() if the model has really been modified * If it is a new model, then for example 'name' must not be empty, otherwise it is has not really been modified */ public function testEmptyOpportunityGetsCreatedOnProductEdit() { $super = User::getByUsername('super'); Yii::app()->user->userModel = $super; $name = 'Amazing Kid Sample'; $productTemplateName = ProductsDemoDataMaker::getProductTemplateForProduct($name); $productTemplate = ProductTemplateTestHelper::createProductTemplateByName($productTemplateName); $model = new Product(); $name = 'My Simple Product'; $model->name = $name; $model->quantity = 4; $model->stage->value = 'Open'; $model->priceFrequency = $productTemplate->priceFrequency; $model->sellPrice->value = $productTemplate->sellPrice->value; $model->type = $productTemplate->type; $postData = array(); $postData['opportunity'] = array('id' => ''); $model->setAttributes($postData); $model->validate(); $sanitizedOwnerData = array('owner' => array('id' => $super->id)); $model->setAttributes($sanitizedOwnerData); $model->validate(array('owner')); $this->assertTrue($model->opportunity->id < 0); //need to check this to call get first. $this->assertTrue($model->save(false)); $this->assertTrue($model->save(false)); $this->assertTrue($model->opportunity->id < 0); $model->delete(); $productTemplate->delete(); }
/** * This function performs the validation work for complex object models. * * In addition to checking the current object, all related objects will * also be validated. If all pass then <code>true</code> is returned; otherwise * an aggreagated array of ValidationFailed objects will be returned. * * @param array $columns Array of column names to validate. * @return mixed <code>true</code> if all validations pass; array of <code>ValidationFailed</code> objets otherwise. */ protected function doValidate($columns = null) { if (!$this->alreadyInValidation) { $this->alreadyInValidation = true; $retval = null; $failureMap = array(); // We call the validate method on the following object(s) if they // were passed to this object by their coresponding set // method. This object relates to these object(s) by a // foreign key reference. if ($this->aUser !== null) { if (!$this->aUser->validate($columns)) { $failureMap = array_merge($failureMap, $this->aUser->getValidationFailures()); } } if ($this->aProduct !== null) { if (!$this->aProduct->validate($columns)) { $failureMap = array_merge($failureMap, $this->aProduct->getValidationFailures()); } } if (($retval = UserProductPeer::doValidate($this, $columns)) !== true) { $failureMap = array_merge($failureMap, $retval); } $this->alreadyInValidation = false; } return !empty($failureMap) ? $failureMap : true; }
public function post() { $post = Input::all(); $validator = Product::validate($post); $productId = $post['id']; if ($validator->fails()) { return Redirect::to('productos/' . $productId)->withErrors($validator)->withInput(); } else { $product = self::__checkExistence($productId); $isNew = false; if (!$productId) { $product = new Product(); $isNew = true; } $product->name = $post['name']; $product->description = $post['description']; $product->code = $post['code']; $product->minimum_stock = $post['minimum_stock']; $product->cost = str_replace(',', '.', $post['cost']); $product->save(); if ($isNew) { Globals::triggerAlerts(4, array('productId' => $product->id)); } if ($post['status'] == 'inactive') { $product->delete(); } else { if ($product->trashed()) { $product->restore(); } } Session::flash('success', 'Producto guardado correctamente.'); return Redirect::to('productos'); } }
/** * 添加商品 */ public function actionAddProduct() { $this->pageTitle = "添加商品"; $product = new Product(); if (isset($_POST) && isset($_POST['Product'])) { $_POST['Product']['product_user_id'] = Yii::app()->user->getId(); $product->setAttributes($_POST['Product']); if ($product->validate() && $product->save()) { $this->redirect(Yii::app()->createUrl('/wechat/product/changePro/id/' . $product->product_id)); Yii::app()->end(); } } $this->render('product_add', array("product" => $product)); }
public function postProductAddNew($id = "") { if (\Request::ajax()) { if (isset($_POST['options'])) { $options = \DB::table("options_values")->where("title", "like", "%" . $_POST['options'] . "%")->get(); $autoComplete = ""; $autoComplete .= "<ul style='list-style: none; margin: 0'>"; foreach ($options as $option) { $autoComplete .= "<li>{$option->title}</li>"; } $autoComplete .= "</ul>"; echo $autoComplete; exit; } ############ Configuration ############## $thumb_square_size = 200; //Thumbnails will be cropped to 200x200 pixels $max_image_size = 500; //Maximum image size (height and width) $thumb_prefix = "thumb_"; //Normal thumb Prefix if (public_path()) { $destination_folder = public_path() . "/uploads/images/"; //upload directory ends with / (slash) $image_invention_folder = public_path() . "/uploads/images/"; } else { $image_invention_folder = '/home/medicalng/public_html/uploads/images/'; $destination_folder = '/home/medicalng/public_html/uploads/images/'; } //$file = $jpeg_quality = 90; //jpeg quality ########################################## //continue only if $_POST is set and it is a Ajax request if (isset($_POST) && isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') { // check $_FILES['ImageFile'] not empty if (!isset($_FILES['image_file']) || !is_uploaded_file($_FILES['image_file']['tmp_name'])) { die('Image file is Missing!'); // output error when above checks fail. exit; } //uploaded file info we need to proceed $image_name = $_FILES['image_file']['name']; //file name $image_size = $_FILES['image_file']['size']; //file size $image_temp = $_FILES['image_file']['tmp_name']; //file temp $image_size_info = getimagesize($image_temp); //get image size if ($image_size_info) { $image_width = $image_size_info[0]; //image width $image_height = $image_size_info[1]; //image height $image_type = $image_size_info['mime']; //image type } else { die("Make sure image file is valid!"); } //switch statement below checks allowed image type //as well as creates new image from given file switch ($image_type) { case 'image/png': $image_res = imagecreatefrompng($image_temp); break; case 'image/gif': $image_res = imagecreatefromgif($image_temp); break; case 'image/jpeg': case 'image/pjpeg': $image_res = imagecreatefromjpeg($image_temp); break; default: $image_res = false; } if ($image_res) { //Get file extension and name to construct new file name $image_info = pathinfo($image_name); $image_extension = strtolower($image_info["extension"]); //image extension $image_name_only = strtolower($image_info["filename"]); //file name only, no extension //create a random name for new image (Eg: fileName_293749.jpg) ; $mrand = rand(0, 9999999999.0); $new_file_name = $image_name_only . '_' . $mrand . '.' . $image_extension; //folder path to save resized images and thumbnails //$thumb_save_folder = $destination_folder . $thumb_prefix . $new_file_name; $image_save_folder = $destination_folder . $new_file_name; //call normal_resize_image() function to proportionally resize image if (normal_resize_image($image_res, $image_save_folder, $image_type, $max_image_size, $image_width, $image_height, $jpeg_quality)) { $img1 = \Image::make($image_invention_folder . $new_file_name); $img1->resize(262, 311); $imageNewNameten = $image_name_only . '_' . $mrand . "-262x311" . "." . $image_extension; $img1->save($image_invention_folder . "thumbs/" . $imageNewNameten); $img3 = \Image::make($image_invention_folder . $new_file_name); $img3->resize(100, 100); $imageNewNameten = $image_name_only . '_' . $mrand . "-100x100" . "." . $image_extension; $img3->save($image_invention_folder . "thumbs/" . $imageNewNameten); $img3 = \Image::make($image_invention_folder . $new_file_name); $img3->resize(50, 80); $imageNewNameten = $image_name_only . '_' . $mrand . "-50x80" . "." . $image_extension; $img3->save($image_invention_folder . $imageNewNameten); $img2 = \Image::make($image_invention_folder . $new_file_name); $img2->resize(50, 50); $imageNewNameten = $image_name_only . '_' . $mrand . "-50x50" . "." . $image_extension; $img2->save($image_invention_folder . "thumbs/" . $imageNewNameten); /* We have succesfully resized and created thumbnail image We can now output image to user's browser or store information in the database.$destination_folder */ echo '<div align="center">'; echo '<img src="' . url() . '/uploads/images/' . $new_file_name . '" alt="Resized Image">'; echo '</div>@@' . $new_file_name; } imagedestroy($image_res); //freeup memory } } exit; } $validation = \Product::validate(\Input::all()); $input = \Input::all(); //print_r($input); if (isset($input['product_option'])) { $data['product_option'] = $input['product_option']; } if ($validation->fails()) { return \Redirect::back()->withErrors($validation)->withInput(); } else { $parent_name = $input['parent_name']; $categories = $input['cat']; array_forget($input, "parent_name"); array_forget($input, "_token"); array_forget($input, "parent_id"); array_forget($input, "cat"); // $data = $input['product_option']; array_forget($input, "product_option"); $image = $input['image'] == "" ? $input['oldimage'] : $input['image']; array_forget($input, "oldimage"); try { if ($id == "") { $product = new \Product(); foreach ($input as $key => $value) { if ($key != 'product_option') { $product->{$key} = $value; } } if ($product->save()) { $cats = explode(",", $categories); foreach ($cats as $cat) { if ($cat != "") { $cid = \DB::table('categories')->where('title', $cat)->pluck('id'); \DB::table('categories_products')->insert(['category_id' => $cid, 'product_id' => $product->id]); } } if (!empty($data['product_option']) && isset($data['product_option'])) { $x = 0; foreach ($data['product_option'] as $product_option) { // if ($product_option['product_option_value'][$x]['type'] == 'volume' || $product_option['product_option_value'][$x]['type'] == 'size' || $product_option['product_option_value'][$x]['type'] == 'select' || $product_option['product_option_value'][$x]['type'] == 'radio' || $product_option['product_option_value'][$x]['type'] == 'checkbox' || $product_option['product_option_value'][$x]['type'] == 'image') { if (isset($product_option['product_option_value']) && count($product_option['product_option_value']) > 0) { foreach ($product_option['product_option_value'] as $product_option_value) { $option_value_id = (int) $product_option_value['option_value_id']; $quantity = (int) $product_option_value['quantity']; $price = $product_option_value['price']; $weight = $product_option_value['weight']; $weight_prefix = $product_option_value['weight_prefix']; $points_prefix = $product_option_value['points_prefix']; $price_prefix = $product_option_value['price_prefix']; $option_type = $product_option_value['option_type']; $points = $product_option_value['points']; $product_option_value_id = $product_option_value['product_option_value_id']; $objOptionValue = \Optionvalue::find($option_value_id); $option_value = $objOptionValue->optvalue; $option_id = $objOptionValue->option_id; \DB::table('products_options')->insert(['product_id' => $product->id, 'option_type' => $option_type, 'option_value_id' => $option_value_id, 'option_value' => $option_value, 'option_id' => $option_id, 'quantity' => $quantity, 'price' => $price, 'price_prefix' => $price_prefix, 'weight' => $weight, 'weight_prefix' => $weight_prefix, 'points' => $points, 'points_prefix' => $points_prefix]); } } else { //DB::table('products_options')->where('product_option_value_id', '=',$product_option_value_id)->delete(); // $this->db->query("DELETE FROM " . DB_PREFIX . "product_option WHERE product_option_id = '".$product_option_id."'"); } //} $x++; } } \Session::put("success_message", "Record Saved"); return \Redirect::back(); } else { \Session::put("error_message", "Sorry, Unexpected Error! Record Could Not Be Saved"); return \Redirect::back(); } } else { $product = \Product::find($id); array_forget($input, "_token"); foreach ($input as $key => $value) { $product->{$key} = $value; } $product->image = $image; if ($product->update()) { if (!empty($data['product_option'])) { $opt = \Productoptions::where("product_id", $product->id)->get(); if ($opt) { \DB::table('products_options')->where('product_id', '=', $product->id)->delete(); } $x = 0; foreach ($data['product_option'] as $product_option) { // if ($product_option['product_option_value'][$x]['type'] == 'volume' || $product_option['product_option_value'][$x]['type'] == 'size' || $product_option['product_option_value'][$x]['type'] == 'select' || $product_option['product_option_value'][$x]['type'] == 'radio' || $product_option['product_option_value'][$x]['type'] == 'checkbox' || $product_option['product_option_value'][$x]['type'] == 'image') { if (isset($product_option['product_option_value']) && count($product_option['product_option_value']) > 0) { foreach ($product_option['product_option_value'] as $product_option_value) { $option_value_id = (int) $product_option_value['option_value_id']; $quantity = (int) $product_option_value['quantity']; $price = $product_option_value['price']; $weight = $product_option_value['weight']; $option_type = $product_option_value['option_type']; $weight_prefix = $product_option_value['weight_prefix']; $points_prefix = $product_option_value['points_prefix']; $price_prefix = $product_option_value['price_prefix']; $points = $product_option_value['points']; $product_option_value_id = $product_option_value['product_option_value_id']; $objOptionValue = \Optionvalue::find($option_value_id); $option_value = $objOptionValue->optvalue; $option_id = $objOptionValue->option_id; \DB::table('products_options')->insert(['product_id' => $product->id, 'option_type' => $option_type, 'option_value_id' => $option_value_id, 'option_value' => $option_value, 'option_id' => $option_id, 'quantity' => $quantity, 'price' => $price, 'price_prefix' => $price_prefix, 'weight' => $weight, 'weight_prefix' => $weight_prefix, 'points' => $points, 'points_prefix' => $points_prefix]); } } else { $opt = \Productoptions::where("product_id", $product->id)->get(); if ($opt) { \DB::table('products_options')->where('product_id', '=', $product->id)->delete(); } } //} $x++; } } \Session::put("success_message", "Record Updated"); return \Redirect::back(); } else { \Session::put("error_message", "Sorry, Unexpected Error! Record Could Not Be Saved"); return \Redirect::back(); } } } catch (ValidationException $e) { \Session::put("error_message", $e->getMessage()); return \Redirect::back()->withInput()->withErrors($e->getErrors()); } catch (\Illuminate\Database\QueryException $e) { \Session::put("error_message", $e->getMessage()); return \Redirect::back(); exit; } catch (\PDOException $e) { \Session::put("error_message", $e->getMessage()); return \Redirect::back(); //exit; } catch (\Exception $e) { \Session::put("error_message", $e->getMessage()); return \Redirect::back(); //exit; } } }
public function actionImport() { $total_records = 0; $inserted_records = 0; $msg = ""; $model = new Product(); $model->setScenario('importFile'); $file = CUploadedFile::getInstance($model, 'csv_file'); if (isset($_POST['Product'])) { // echo $_POST['Product']['import_option']; die(); if (!empty($_FILES['Product']['tmp_name']['import_file'])) { $file = CUploadedFile::getInstance($model, 'import_file'); $fp = fopen($file->tempName, 'r'); $row = 1; if ($fp) { $line = fgetcsv($fp, 1000, ","); $first_time = true; $c = 1; if ($_POST['Product']['import_option'] == "Insert") { do { //var_dump($line); die(); if ($first_time == true) { $first_time = false; $headerLine = $line; continue; } //$data = explode(",",$line); //$data = $line[0]; //$data = explode(';',$line); $fData = array_combine($headerLine, $line); //echo '<pre>'; var_dump($fData); echo '</pre>'; die(); $email_id = $fData["business_email_id1"]; //echo '<pre>'; var_dump($modelObj); echo '</pre>'; die(); $modelObj = new Product(); $modelObj->setIsNewRecord(true); $modelObj->attributes = $fData; $modelObj->logo_photo_name = $fData['logo_photo_name']; $modelObj->cover_photo_name = $fData['cover_photo_name']; // echo '<pre>'; var_dump($modelObj); echo '</pre>'; die(); if ($modelObj->validate()) { $modelObj->save(); var_dump($model->getErrors()); } else { die(CVarDumper::dump($modelObj->errors, 10, true)); } $modelObj->product_id; $inserted_records = $inserted_records + 1; $total_records = $total_records + 1; } while (($line = fgetcsv($fp, 1000, ",")) != FALSE); $msg = $inserted_records . " records are inserted" . " out of " . $total_records; $this->render('import', array('model' => $model, 'total_records' => $total_records, 'inserted_records' => $inserted_records, 'msg' => $msg)); } if ($_POST['Product']['import_option'] == "Update") { do { if ($first_time == true) { $first_time = false; $headerLine = $line; continue; } //$data = explode(",",$line); //$data = $line[0]; //$data = explode(',',$data); //echo '<pre>'; var_dump($data); echo '</pre>'; die(); $fData = array_combine($headerLine, $line); $email_id = $fData['business_email_id1']; $modelObj = Product::model()->find('business_email_id1=:business_email_id1', array(':business_email_id1' => $email_id)); //echo '<pre>'; var_dump($modelObj); echo '</pre>'; die(); // echo var_dump($modelObj); if ($modelObj) { $modelObj->attributes = $fData; $modelObj->logo_photo_name = $fData['logo_photo_name']; $modelObj->cover_photo_name = $fData['cover_photo_name']; // echo '<pre>'; var_dump($modelObj); echo '</pre>'; die(); $modelObj->save(); $modelObj->product_id; $inserted_records = $inserted_records + 1; } $total_records = $total_records + 1; } while (($line = fgetcsv($fp, 1000, ",")) != FALSE); // echo "count:".$inserted_records.'---'.$total_records; die(); $msg = $inserted_records . " records are updated" . " out of " . $total_records; $this->render('import', array('model' => $model, 'total_records' => $total_records, 'inserted_records' => $inserted_records, 'msg' => $msg)); //$this->redirect('././view'); } } else { $msg = "Please select insert or update option for import file."; $this->render('import', array('model' => $model, 'total_records' => $total_records, 'inserted_records' => $inserted_records, 'msg' => $msg)); } } else { $msg = "Please upload file."; $this->render('import', array('model' => $model, 'total_records' => $total_records, 'inserted_records' => $inserted_records, 'msg' => $msg)); } } else { $this->render('import', array('model' => $model, 'total_records' => $total_records, 'inserted_records' => $inserted_records, 'msg' => $msg)); } }
function productImport($array) { if ($array['id'] || $array['artno']) { $log = array('error' => 0, 'warning' => '', 'note' => ''); if ($array['id']) { $product = $this->loadModel($array['id']); } else { $product = Product::model()->findByAttributes(array('artno' => $array['artno'])); } if ($product) { $value = $product->value; $log['new'] = 0; } else { $log['new'] = 1; $product = new Product(); $value = new ProductValue(); } foreach ($array as $f => $v) { if (array_key_exists($f, $product->attributes)) { if (in_array($f, array('id', 'photo_id', 'price', 'store', 'type', 'status'))) { if ($f != 'photo_id' && $f != 'id') { $product->setAttribute($f, (int) $v); } } else { $product->setAttribute($f, $v); } } elseif (array_key_exists($f, $value->attributes)) { $value->setAttribute($f, $v); } } if ($product->validate() && $value->validate()) { if ($log['new']) { $product->save(); $value->pr_id = $product->id; } if (isset($array['catalogs'])) { $catalogs = explode('|', $array['catalogs']); foreach ($catalogs as $branch) { $parent_id = 0; foreach (explode('=>', $branch) as $cat_name) { $catalog = Catalog::model()->findByAttributes(array('name' => $cat_name, 'pid' => $parent_id)); if ($catalog) { $carRel = new CatalogRelation(); $carRel->cid = $parent_id = $catalog->id; $carRel->pr_id = $product->id; $carRel->save(); } else { $log['note'] = CartModule::t('Not found catalog "{catalog}" in branch "{branch}".', 'import', array('{branch}' => $branch, '{catalog}' => $cat_name)); } } } } if ($array['photo']) { $photos = explode('|', $array['photo']); foreach ($photos as $photo) { $path = Yii::app()->getModule('cart')->importPathPhotos . '/' . $photo; $newPhoto = new Photo(); if ($newPhoto->addByFile($path, $product->id)) { if (!$product->photo_id && $newPhoto->id) { $product->photo_id = $newPhoto->id; $product->save(); } } else { $log['warning'] = CartModule::t('Failed to add photo: {photo}', 'import', array('{photo}' => $photo)); } } } $value->save(); $product->save(); if ($log['new']) { $log['message'] = CartModule::t('Addded product name (artno)', 'import', $array); } else { $log['message'] = CartModule::t('Changed product name (artno)', 'import', $array); } } else { $log['error'] = 1; if (!$product->validate()) { $log['message'] = CartModule::t('Product validation error', 'import') . ' (' . CHtml::errorSummary($product) . ')<br/>'; } if (!$value->validate()) { $log['message'] = CartModule::t('Product fields validation error', 'import') . ' (' . CHtml::errorSummary($value) . ')'; } } return $log; } else { return array('message' => CartModule::t('Not found the ID and Product Marking', 'import')); } }