Opencart 2 product image galleries. How to? - image

I have an issue. I need 2 product image galleries. I added additional code (copied from the main image gallery controller, model, view on admin side). Everything works (sort order, product ID etc) and is successfully stored in the database, except the image link itself.
The problem is probably with the image manager and it only assigns images to the main image gallery and not to the additional one I created.
What am I missing? The functions to INSERT into database are all there. But how do I make the image manager use the other function?
I tried everything I could think of: changed all the strings I could think of, created additional functions and edited the admin view file as well.
Here's the place where I THINK the problem is:
'''
// Images
if (isset($this->request->post['product_image'])) {
$product_images = $this->request->post['product_image'];
} elseif (isset($this->request->get['product_id'])) {
$product_images = $this->model_catalog_product->getProductImages($this->request->get['product_id']);
} else {
$product_images = array();
}
$data['product_images'] = array();
foreach ($product_images as $product_image) {
if (is_file(DIR_IMAGE . $product_image['image'])) {
$image = $product_image['image'];
$thumb = $product_image['image'];
} else {
$image = '';
$thumb = 'no_image.png';
}
$data['product_images'][] = array(
'image' => $image,
'thumb' => $this->model_tool_image->resize($thumb, 100, 100),
'sort_order' => $product_image['sort_order']
);
}
// Energy Class Images
if (isset($this->request->post['energy_product_image'])) {
$energy_product_images = $this->request->post['energy_product_image'];
} elseif (isset($this->request->get['product_id'])) {
$energy_product_images = $this->model_catalog_product->getEnergyProductImages($this->request->get['product_id']);
} else {
$energy_product_images = array();
}
$data['energy_product_images'] = array();
foreach ($energy_product_images as $energy_product_image) {
if (is_file(DIR_IMAGE . $energy_product_image['image'])) {
$energy_image = $energy_product_image['image'];
$energy_thumb = $energy_product_image['image'];
} else {
$energy_image = '';
$energy_thumb = 'no_image.png';
}
$data['energy_product_images'][] = array(
'image' => $energy_image,
'thumb' => $this->model_tool_image->resize($energy_thumb, 100, 100),
'sort_order' => $energy_product_image['sort_order']
);
}
'''

Related

Multiple Image Upload in Laravel tweak to add additional field

I have a need to upload multiple images. This code below works well. This is using Intervention Image plugin. I am trying to customise this code to add another field which is a ForeignKey value to the parent of this image model. $request has the value coming from form. How to save it along with images?
The value is:
$request('vehicle_id')
How can tweak the below method so as save includes this vehicle_id as well?
public function uploadImage(Request $request)
{
$request->validate([
'image' => 'required',
'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
//check if image exist
if ($request->hasFile('image')) {
$images = $request->file('image');
// create new directory for uploading image if doesn't exist
if( ! File::exists('images/'.auth()->user()->id)) {
$org_img = File::makeDirectory('images/'.auth()->user()->id, 0777, true);
}
// loop through each image to save and upload
foreach($images as $key => $image) {
//create new instance of Photo class
$newPhoto = new $this->photo;
//get file name of image and concatenate with 4 random integer for unique
$filename = rand(1111,9999).time().'.'.$image->getClientOriginalExtension();
//path of image for upload
$org_path = 'images/'.auth()->user()->id . $filename;
$newPhoto->image = 'images/'.auth()->user()->id.$filename;
//don't upload file when unable to save name to database
if ( ! $newPhoto->save()) {
return false;
}
// upload image to server
if ($org_img == true) {
Image::make($image)->fit(900, 500, function ($constraint) {
$constraint->upsize();
})->save($org_path);
}
}
}
return redirect('/home')->with('success','Images Uploaded');
}
I found solution
public function uploadImage(Request $request)
{
$request->validate([
'image' => 'required',
'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'vehicle' => 'required'
]);
//check if image exist
if ($request->hasFile('image')) {
$images = $request->file('image');
// create new directory for uploading image if doesn't exist
if( ! File::exists('images/'.auth()->user()->id.'/')) {
$org_img = File::makeDirectory('images/'.auth()->user()->id.'/', 0777, true);
}
// loop through each image to save and upload
foreach($images as $key => $image) {
//create new instance of Photo class
$newPhoto = new $this->photo;
//get file name of image and concatenate with 4 random integer for unique
$filename = rand(1111,9999).time().'.'.$image->getClientOriginalExtension();
//path of image for upload
$org_path = 'images/'.auth()->user()->id.'/' . $filename;
$newPhoto->image = 'images/'.auth()->user()->id.'/' . $filename;
$newPhoto->vehicle = $request->input('vehicle');
//don't upload file when unable to save name to database
if ( ! $newPhoto->save()) {
return false;
}
// upload image to server
Image::make($image)->fit(900, 500, function ($constraint) {
$constraint->upsize();
})->save($org_path);
}
}
return redirect('/home')->with('success','Images Uploaded');

How to upload multiple images in php

I am developing a module of epaper in codeigniter(PyroCMS).
I want to know how can I upload multiple images ar once.
Can anyone guide me in uploading multiple images?
I tried but I only found code for uploading single image which I have already used in news module.
In the view file give this code for image upload:
echo form_label('Multi Images','',$label_attr);
echo form_upload($multi_photo_attr);
where
$multi_photo_attr = array(
'id' => "cat_multi_images",
'class' => "multi",
'name' => "cat_multi_images[]",
'maxlength' => "25",
'multiple' => "multiple"
);
Now you need to create a folder in the root directory where your photos will be uploaded.
After that in the controller's method you need to store the path to that folder in a variable.This variable will be used to upload the images in the folder.
Next,get the names of all the images in a array something like this:
foreach($_FILES["cat_multi_images"] as $key => $value)
{
$i=0;
foreach($value as $key1 => $value1)
{
$multi_photo_array[$i][$key] = $value1;
$i++;
}
After that for every array element,i.e.,for every image run the below code to upload it:
function UploadFile($files,$path)
{
$extensions = array('jpeg','JPEG','gif','GIF','png','PNG','jpg','JPG','pdf','PDF','ZIP','zip','rar','RAR','html','HTML','TXT','txt','doc','docx','DOC','DOCX','ppt','PPT','pptx','PPTX','xlsx','XLSX','xls','XLS','exe','EXE','mp3','MP3','wav','WAV','m4r','M4R','mpeg','MPEG','mpg','MPG','mpe','MPE','mov','MOV','avi','AVI',);
$destination = $path.$files["name"];
//print_r($destination);exit;
// GET FILE PARTS
$fileParts = pathinfo($files['name']);
$file_name = $files['name'];
$file_name_only = $fileParts['filename'];
$file_name_only = preg_replace('/[^a-zA-Z0-9]/','',$file_name_only);
$file_extention = $fileParts['extension'];
$Count = 0;
$destination = $path.$file_name_only.".$file_extention";
$file_name = $file_name_only.".$file_extention";;
// THIS SHOULD KEEP CHECKING UNTIL THE FILE DOESN'T EXISTS
while( file_exists($destination))
{
$Count += 1;
$destination = $path. $file_name_only."-".$Count.".$file_extention";
$file_name = $file_name_only."-".$Count.".$file_extention";
}
$fileextension='';
$filename='';
if(!empty($files))
{
$filename=$files['name'];
$fileextension=substr($filename,strpos($filename,".")+1);
if(in_array($fileextension,$extensions))
{
$uploadstatus=move_uploaded_file($files["tmp_name"],$destination);
if($uploadstatus)
{
return $file_name;
}
else
{
return false;
}
}
else
{
return false;
}
}
}
Just copy the above code.It should work as it is made for a general case by me!You can copy that code in your model file and call it in the controller like this :
$pr_photo_data = $this->admin_model->UploadFile($value,$targetPath_images);
$photo_list[] = $pr_photo_data;
And then store every image in the database
foreach($photo_list as $image)
{
$pro_image["cat_multi_images"] = $image;
$pro_retId = $this->admin_model->add_multipic_cat($pro_image);
}
where
function add_multipic_cat($data)
{
$retId = $this->database->query_insert("photo", $data);
return $retId;
}
Be careful.Take care and do every step accurately
check this one
https://github.com/blueimp/jQuery-File-Upload/wiki/jQuery-File-Upload,---Multi-file-upload-with-CodeIgniter
Struggling To Use PyroCMS Files Library To Upload Multiple Files

adding the uploaded file name to database in blueimp fileupload jquery plugin

I am hoping someone has some experience with the blueimp fileupload jquery plugin at : https://github.com/blueimp/jQuery-File-Upload
How to add the uploaded file name to database ?
In the options array (look for $this->options = array( )
and insert
'database' => 'database_name',
'host' => 'localhost',
'username' => 'user',
'password' => 'password',
Then after
protected function handle_file_upload($uploaded_file, $name, $size, $type, $error,
$index = null, $content_range = null) {
$file = new stdClass();
$file->name = $this->get_file_name($name, $type, $index, $content_range);
$file->size = $this->fix_integer_overflow(intval($size));
$file->type = $type;</code></pre>
Insert this code
//Start added coded
// prepare the image for insertion
$data = addslashes (file_get_contents($uploaded_file));
// get the image info..
$size = getimagesize($uploaded_file);
$file->upload_to_db = $this->add_img($data, $size, $name);
//end added code
and after the function handle_file_upload insert the following code to actually upload the image to the database.
function query($query) {
$database = $this->options['database'];
$host = $this->options['host'];
$username = $this->options['username'];
$password = $this->options['password'];
$link = mysql_connect($host,$username,$password);
if (!$link) {
die(mysql_error());
}
$db_selected = mysql_select_db($database);
if (!$db_selected) {
die(mysql_error());
}
$result = mysql_query($query);
mysql_close($link);
return $result;
}
function add_img($data,$size,$name)
{
$add_to_db = $this->query("INSERT INTO your_database_name
(image_type ,image, image_size, file_name)
VALUES
('{$size['mime']}', '{$data}', '{$size[3]}', '{$name}')") or die(mysql_error());
return $add_to_db;
}
This will store the actual image in the database if you don't want that change the add_img($data,$size,$name) to add_img($size,$name) and just don't pass the $data variable. The $data variable should be stored as a medium or long blob.
You can also comment out the fileupload to directory stuff so you don't get errors if you don't what the images uploaded to a directory. This is in the protected function handle_file_upload
//comment out file upload stuff since storing in database
/*
if ($this->validate($uploaded_file, $file, $error, $index)) {
$this->handle_form_data($file, $index);
$upload_dir = $this->get_upload_path();
if (!is_dir($upload_dir)) {
mkdir($upload_dir, $this->options['mkdir_mode'], true);
}
$file_path = $this->get_upload_path($file->name);
$append_file = $content_range && is_file($file_path) &&
$file->size > $this->get_file_size($file_path);
if ($uploaded_file && is_uploaded_file($uploaded_file)) {
// multipart/formdata uploads (POST method uploads)
if ($append_file) {
file_put_contents(
$file_path,
fopen($uploaded_file, 'r'),
FILE_APPEND
);
} else {
move_uploaded_file($uploaded_file, $file_path);
}
} else {
// Non-multipart uploads (PUT method support)
file_put_contents(
$file_path,
fopen('php://input', 'r'),
$append_file ? FILE_APPEND : 0
);
}
$file_size = $this->get_file_size($file_path, $append_file);
if ($file_size === $file->size) {
$file->url = $this->get_download_url($file->name);
list($img_width, $img_height) = #getimagesize($file_path);
if (is_int($img_width) &&
preg_match($this->options['inline_file_types'], $file->name)) {
$this->handle_image_file($file_path, $file);
}
} else {
$file->size = $file_size;
if (!$content_range && $this->options['discard_aborted_uploads']) {
unlink($file_path);
$file->error = 'abort';
}
}
$this->set_additional_file_properties($file);
}
*/

remove certain state/province from magento checkout

I want to remove certain state/Province from magento 1.12.0.2 checkout (onestepcheckout) page like "American Samoa"
I tried changing the Data.php file in "/app/code/local/Mage/Directory/"
public function getRegionJson()
{
$exclude_regions = array ('AS','FM');
Varien_Profiler::start('TEST: '.__METHOD__);
if (!$this->_regionJson)
{
$cacheKey = 'DIRECTORY_REGIONS_JSON_STORE'.Mage::app()->getStore()->getId();
if (Mage::app()->useCache('config')) {
$json = Mage::app()->loadCache($cacheKey);
}
if (empty($json))
{
$countryIds = array();
foreach ($this->getCountryCollection() as $country)
{
$countryIds[] = $country->getCountryId();
}
$collection = Mage::getModel('directory/region')->getResourceCollection()
->addCountryFilter($countryIds)
->load();
$regions = array();
foreach ($collection as $region) {
$rg = $region->getCode();
//if ($rg!='AL'){
if(!in_array($rg, $exclude_regions)) {
if (!$region->getRegionId()) {
continue;
}
$regions[$region->getCountryId()][$region->getRegionId()] = array(
'code' => $region->getCode(),
//'name' => $region->getName()
'name' => $this->__($region->getName())
);
}
}
$json = Mage::helper('core')->jsonEncode($regions);
if (Mage::app()->useCache('config')) {
Mage::app()->saveCache($json, $cacheKey, array('config'));
}
}
$this->_regionJson = $json;
}
Varien_Profiler::stop('TEST: '.__METHOD__);
return $this->_regionJson;
}
but did not have any luck, any help will be greatly appreciated on how to do this
Thank you in advance
The above code works fine, i just needed to flush the Magento cache storage.

Display multi-option customer attribute within customer management admin grid

Okay so with Customer Attributes I have a multi-option selection that I have added to the Manage Customers Grid.
$prodCode = Mage::getSingleton('eav/config')->getAttribute('customer','prod_codes');
$prodCodeOptions = $prodCode->getSource()->getAllOptions(false);
$prodOptions = array();
foreach($prodCodeOptions as $k)
$prodOptions[$k['value']] = $k['label'];
$this->addColumn('prod_codes', array(
'header' => Mage::helper('customer')->__('Product Code'),
'width' => '100',
'index' => 'prod_codes',
'type' => 'options',
'options' => $prodOptions,
'filter_condition_callback'
=> array($this, '_filterProdOptionsCondition'),
));
I do have my attribute added to the collection at the top of my Grid.php:
->addAttributeToSelect('prod_codes')
Here is my _filterProdOptionsCondition method:
protected function _filterProdOptionsCondition($collection, $column) {
if(!$value = $column->getFilter()->getValue()) {
return;
}
$this->getCollection()->addFieldToFilter('prod_codes', array('finset' => $value));
#print($collection->getSelectSql());
}
Now this work fine and dandy if I only have ONE of the options selected, once I apply more than one option to the customers attribute I will get a blank results within the admin grid, however it IS still searchable.
A close look with the print($collection->getSelectSql()); uncommented I see that the attribute ID values are being returned in an comma delimited list.
Now onto my question with that background laid out, is there a method or "Magento" way to display these multi-options within the admin grid I'm just unaware of? Or do I need to simply get the comma values exploded and call for a new collection to build out the display values? Any help appreciated!
Appears I had to extend the Column renderer to anticipate comma values and simply render them, I'm amazed this isn't built in since the functionality exists to create the multioptions attributes but no grid display option for it.
app/code/local/Mage/Adminhtml/Block/Widget/Grid/Column/Renderer/Options.php
public function render(Varien_Object $row)
{
$options = $this->getColumn()->getOptions();
$showMissingOptionValues = (bool)$this->getColumn()->getShowMissingOptionValues();
if (!empty($options) && is_array($options)) {
$value = $row->getData($this->getColumn()->getIndex());
if (is_array($value)) {
$res = array();
foreach ($value as $item) {
if (isset($options[$item])) {
$res[] = $options[$item];
}
elseif ($showMissingOptionValues) {
$res[] = $item;
}
}
return implode(', ', $res);
}
elseif (isset($options[$value])) {
return $options[$value];
} elseif (is_string($value)) { // <--- MY CHANGES HERE
$values = explode(',', $value);
$returnOptions = "";
foreach($values as $k=>$v) {
$returnOptions .= $options[$v]. ", ";
}
return substr($returnOptions, 0, -2);
}
return '';
}
}

Resources