Here i can only able preview the images on update the model. I want to load the images properly so user can remove one r more file and update will work accordingly Here is my controller
public function actionUpdate($id)
{
$model = $this->findModel($id);
$session_data = \common\models\Customer::find()->where(['user_id' => $model->customer_user_id])->one();
$towing = \common\models\TowingRequest::find()->where(['id' => $model->towing_request_id])->one();
$images_old = \common\models\Images::find()->where(['=', 'vehicle_id', $model->id])->all();
$images = \common\models\Images::find()->where(['=', 'vehicle_id', $model->id])->one();
if (!$images) {
$images = new \common\models\Images();
}
if ($images_old) {
foreach ($images_old as $image) {
$baseurl = \Yii::$app->request->BaseUrl;
$image_url = $baseurl . '../backend/uploads/' . $image->thumbnail;
$all_images[] = Html::img("$image_url", ['class' => 'file-preview-image']);
}
} else {
$all_images = '';
}
$vehiclefeatures = new \common\models\VehicleFeatures();
$vehiclecondition = new \common\models\VehicleCondition();
$featuredata = \common\models\VehicleFeatures::find()->where(['=', 'vehicle_id', $model->id])->all();
$conditiondata = \common\models\VehicleCondition::find()->where(['=', 'vehicle_id', $model->id])->all();
$features = \common\models\Features::find()->all();
// $vf = Yii::$app->db->createCommand('SELECT * FROM features f left join vehicle_features vf on vf.features_id=f.id;')->queryAll();
$condition = \common\models\Condition::find()->all();
if ($model->load(Yii::$app->request->post()) && $towing->load(Yii::$app->request->post()) && $vehiclefeatures->load(Yii::$app->request->post()) && $vehiclecondition->load(Yii::$app->request->post()) && $images->load(Yii::$app->request->post())) {
$towing->save();
if (!$model->save()) {
$result = [];
// The code below comes from ActiveForm::validate(). We do not need to validate the model
// again, as it was already validated by save(). Just collect the messages.
foreach ($model->getErrors() as $attribute => $errors) {
$result[Html::getInputId($model, $attribute)] = $errors;
}
return $this->asJson(['validation' => $result]);
// Yii::$app->response->statusCode = 422;
}
//delet vehicle features and add new features
$command = Yii::$app->db->createCommand()
->delete('vehicle_features', 'vehicle_id = ' . $model->id)
->execute();
if ($vehiclefeatures->value) {
$vehicle_feature = \common\models\VehicleFeatures::inert_vehicle_feature($model, $vehiclefeatures->value);
}
//delete vehicle condition and add new features
$command = Yii::$app->db->createCommand()
->delete('vehicle_condition', 'vehicle_id = ' . $model->id)
->execute();
if ($vehiclecondition->value) {
$vehicle_condition = \common\models\VehicleCondition::inert_vehicle_condition($model, $vehiclecondition->value);
}
$photo = UploadedFile::getInstances($images, 'name');
if ($photo) {
$command = Yii::$app->db->createCommand()
->delete('images', 'vehicle_id = ' . $model->id)
->execute();
$save_images = \common\models\Images::save_container_images($model->id, $photo);
}
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('update', [
'model' => $model,
'towing' => $towing,
'images' => $images,
'features' => $features,
'condition' => $condition,
'vehiclefeatures' => $vehiclefeatures,
'vehiclecondition' => $vehiclecondition,
'all_images' => $all_images,
'featuredata' => $featuredata,
'conditiondata' => $conditiondata,
'session_data' => $session_data,
]);
}
And here is my form where I have an issue on update the images. I know here I am just previewing the image by adding it in $all_images[] in the controller and initialPreview => $all_images in form to just show it on upload. Now I want exactly is to load the images properly so I can remove any image and can able to add more images. I just want here is how to load all the images properly in the upload widget on update After uploading it properly on update i can process it on the controller that i will delete and unlink all images and uploading the updating files
Here is my form with model images
<?=
$form->field($images, 'name[]')->widget(FileInput::classname(), [
'options' => ['accept' => 'image/*', 'multiple' => true],
'pluginOptions' => [
'previewFileType' => 'image',
'allowedFileExtensions' => ['jpg', 'gif', 'png', 'bmp','jpeg'],
'showUpload' => true,
'initialPreview' => $all_images,
'overwriteInitial' => true,
],
]);
?>
Yii2 Fileinput Upload Multiple Images, AJAX based Images Previews and Delete Images.
Please Refer For Multiple Images : https://stackoverflow.com/a/53832224/2218492
Table : products_images
id (Primary)
product_id (FK)
image
Table : product
id (Primary)
Name
ect
Here View Forms...
<?php
use yii\helpers\Html;
use yii\helpers\Url;
use kartik\widgets\FileInput;
?>
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<?php echo '<label class="control-label">Choose an Image file(.png, .jpg)</label>'; ?>
<?php
//For Update Form : Fetch Uploaded Images and create Array to preview
$imagesList = array();
$imagesListId = array();
foreach ($model->productsImages as $img) {
$imagesList[] = Url::base(TRUE) . '/' . $img->image;
$imagesListId[]['key'] = $img->id;
}
?>
<?php
$empty_image = Url::base(TRUE) . "/uploads/image-upload-empty.png";
echo FileInput::widget([
'model' => $model,
'attribute' => 'products_image[]',
'name' => 'products_image[]',
'options' => ['multiple' => true, 'accept' => 'image/*', 'id' => 'products_image_id'],
'pluginOptions' => [
'initialPreview' => $imagesList,
'initialPreviewConfig' => $imagesListId,
'deleteUrl' => Url::to(['products/delete-image']),
'showCaption' => false,
'showRemove' => false,
'showUpload' => false,
'browseClass' => 'btn btn-primary col-lg-6 col-md-8 col-sm-8 col-xs-6',
'browseIcon' => '<i class="glyphicon glyphicon-plus-sign"></i> ',
'browseLabel' => 'Upload Image',
'allowedFileExtensions' => ['jpg', 'png'],
'previewFileType' => ['jpg', 'png'],
'initialPreviewAsData' => true,
'overwriteInitial' => false,
"uploadUrl" => Url::to(['products/upload']),
'uploadExtraData' => ['products_id' => $model->id, 'is_post' => $model->isNewRecord ? 'new' : 'update'],
'msgUploadBegin' => Yii::t('app', 'Please wait, system is uploading the files'),
//'msgUploadThreshold' => Yii::t('app', 'Please wait, system is uploading the files'),
//'msgUploadEnd' => Yii::t('app', 'Done'),
'msgFilesTooMany' => 'Maximum 15 products Images are allowed to be uploaded.',
'dropZoneClickTitle' => '',
"uploadAsync" => true,
"browseOnZoneClick" => true,
"dropZoneTitle" => '<img src=' . $empty_image . ' />',
'fileActionSettings' => [
'showZoom' => true,
'showRemove' => true,
'showUpload' => false,
],
'validateInitialCount' => true,
'maxFileCount' => 15,
'maxFileSize' => 5120, //5mb
'msgPlaceholder' => 'Select attachments',
],
'pluginEvents' => [
'filebatchselected' => 'function(event, files) {
$(this).fileinput("upload");
}',
/* 'uploadExtraData' => 'function() {
var out = {}, key, i = 0;
$(".kv-input:visible").each(function() {
$el = $(this);
key = $el.hasClass("kv-new") ? "new_" + i : "init_" + i;
out[key] = $el.val();
i++;
});
return out;
}', */
'filepredelete' => 'function(event, files) {
//var abort = true;
var index = uploaded_images.indexOf(files);
if (index !== -1) uploaded_images.splice(index, 1);
console.log(uploaded_images);
$("#productsmaster-images_array").val(uploaded_images);
//return abort;
}',
'fileuploaded' => 'function(event, data, previewId, index){
//alert( data.response.initialPreviewConfig[0].key);
uploaded_images.push(data.response.initialPreviewConfig[0].key);
console.log(uploaded_images);
$("#productsmaster-images_array").val(uploaded_images);
}',
/* 'filepreupload' => 'function(event, data, previewId, index){
var form = data.form, files = data.files, extra = data.extra,
response = data.response, reader = data.reader;
console.log(data.jqXHR);
console.log("File pre upload triggered");
}', */
],
]);
?>
<?= $form->field($model, 'images_array')->hiddenInput()->label(false) ?>
<?php echo '<br>' ?>
<?= Html::submitButton('<i class="glyphicon glyphicon-save-file"></i> UPLOAD FILE', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary'], ['students/create']) ?>
<?php ActiveForm::end(); ?>
<?php
$script = <<< JS
// initialize array
var uploaded_images = [];
JS;
$this->registerJs($script);
?>
Here Controller file:
<?php
/*
* Post products Images Upload Action Via FileInput Yii2 Extention.
*/
public function actionUpload() {
$files = array();
$allwoedFiles = ['jpg', 'png'];
if ($_POST['is_post'] == 'update') {
$products_id = $_POST['products_id'];
if ($_FILES) {
$tmpname = $_FILES['ProductsMaster']['tmp_name']['products_image'][0];
$fname = $_FILES['ProductsMaster']['name']['products_image'][0];
//Get the temp file path
$tmpFilePath = $tmpname;
//Make sure we have a filepath
if ($tmpFilePath != "") {
//save the filename
$shortname = $fname;
$size = $_FILES['ProductsMaster']['size']['products_image'][0];
$ext = substr(strrchr($shortname, '.'), 1);
if (in_array($ext, $allwoedFiles)) {
//save the url and the file
$newFileName = Yii::$app->security->generateRandomString(40) . "." . $ext;
//Upload the file into the temp dir
if (move_uploaded_file($tmpFilePath, 'uploads/products/' . $newFileName)) {
$productsImages = new productsImages();
$productsImages->products_id = $products_id;
$productsImages->image_for = 'products';
$productsImages->image = 'uploads/products/' . $newFileName;
$productsImages->created_at = time();
$productsImages->save();
$files['initialPreview'] = Url::base(TRUE) . '/uploads/products/' . $newFileName;
$files['initialPreviewAsData'] = true;
$files['initialPreviewConfig'][]['key'] = $productsImages->id;
return json_encode($files);
}
}
}
} /* else {
return json_encode(['error' => 'No files found for pload.']);
} */
return json_encode($files);
} else {
if (isset($_POST)) {
if ($_FILES) {
$files = ProductsMaster::SaveTempAttachments($_FILES);
return json_encode($files);
$result = ['files' => $files];
Yii::$app->response->format = trim(Response::FORMAT_JSON);
return $result;
} /* else {
echo json_encode(['error' => 'No files found for pload.']);
} */
}
}
}
/**
* Uploaded Images Delete Action on Update Forms Action
* #return boolean
*/
public function actionDeleteImage() {
$key = $_POST['key'];
if (is_numeric($key)) {
$products_image = ProductsImages::find()->where(['id' => $key])->one();
unlink(Yii::getAlias('#webroot') . '/' . $products_image->image);
$products_image->delete();
return true;
} else {
unlink(Yii::getAlias('#webroot') . '/uploads/products/temp/' . $key);
return true;
}
}
/**
** Create Products
**/
public function actionCreate() {
//Products Images
// temp store image moved and save to database.. with generated forms..
if (count($model->images_array) > 0) {
$images_array = explode(',', $model->images_array);
if (!empty($images_array) && $model->images_array != '') {
foreach ($images_array as $image) {
$file = Yii::$app->basePath . '/uploads/products/temp/' . $image;
$rename_file = Yii::$app->basePath . '/uploads/products/' . $image;
rename($file, $rename_file);
$productsImages = new productsImages();
$productsImages->products_id = $model->id;
$productsImages->image_for = 'products';
$productsImages->image = 'uploads/products/' . $image;
$productsImages->created_at = time();
$productsImages->save();
}
}
}
}
?>
Here Model
I added a load function to the attachment model.
<?php
/*
* Save Temp Images
*/
public static function SaveTempAttachments($attachments) {
$files = "";
$allwoedFiles = ['jpg', 'png'];
if ($_FILES) {
$tmpname = $_FILES['ProductsMaster']['tmp_name']['products_image'];
$fname = $_FILES['ProductsMaster']['name']['products_image'];
if (!empty($attachments)) {
if (count($fname) > 0) {
//Loop through each file
for ($i = 0; $i < count($fname); $i++) {
//Get the temp file path
$tmpFilePath = $tmpname[$i];
//Make sure we have a filepath
if ($tmpFilePath != "") {
//save the filename
$shortname = $fname[$i];
$size = $attachments['ProductsMaster']['size']['products_image'][$i];
$ext = substr(strrchr($shortname, '.'), 1);
if (in_array($ext, $allwoedFiles)) {
//save the url and the file
$newFileName = Yii::$app->security->generateRandomString(40) . "." . $ext;
//Upload the file into the temp dir
if (move_uploaded_file($tmpFilePath, 'uploads/products/temp/' . $newFileName)) {
$files['initialPreview'] = Url::base(TRUE) . '/uploads/products/temp/' . $newFileName;
$files['initialPreviewAsData'] = true;
// $files['uploadExtraData'][]['is_post'] = 'new';
$files['initialPreviewConfig'][]['key'] = $newFileName;
}
}
}
}
}
}
}
return $files;
}
?>
Related
I am trying upload file and filter by extension for save name in database by file type and I have a problem: enter image description here
My code example:
public function makepost(Request $req)
{
$req->validate([
'post' => 'required'
]);
$postbyid = Auth::user()->id;
$postby = Auth::user()->name . ' ' . Auth::user()->surname;
if ($req->hasFile('file')) {
$filename = 'WORLDREMO_' . date('YmdHis') . rand(0, 9999999) . '.' . $req->file->extension();
$req->file->move(public_path('files'), $filename);
$post = $req->post;
if ($req->file->extension() == 'mp4') {
$data = array('postbyid' => $postbyid, 'postby' => $postby, 'video' => $filename, 'post' => $post);
Posts::insert($data);
} else {
$data = array('postbyid' => $postbyid, 'postby' => $postby, 'image' => $filename, 'post' => $post);
Posts::insert($data);
}
} else {
$post = $req->post;
$data = array('postbyid' => $postbyid, 'postby' => $postby, 'post' => $post);
Posts::insert($data);
}
}
I am trying to insert images in mysql database with other data but its shows error.
its shows the $msg of not saved & repeat data of view file maybe due to $error which i set.
PS: I set 'image' datatype varchar in database.
here is my view file:
<input type="file" class="form-control-file" name="image" id="exampleInputFile" >
this is my controller:
public function save()
{
$this->load->model('Partner_model');
$feature = $this->input->post('feature');
$config['upload_path'] = './uploads/files';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('image'))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('partner_profile', $error);
}
else
{
$user_data= array(
'pname' => $this->input->post('pname'),
'type' => $this->input->post('type'),
'address' => $this->input->post('address'),
'about' => $this->input->post('about'),
'city' => $this->input->post('city'),
'code' => $this->input->post('code'),
'state'=>$this->input->post('state'),
// 'image'=>$this->upload->do_upload('image')
'feature'=>implode(",",$feature),
'image' => $this->upload->data()
);
}
if($this->Partner_model->save($user_data))
{
$msg = "save sucesss" ;
}
else
{
$msg = "not save";
}
$this->session->set_flashdata('msg', $msg);
$this->load->view('partner_profile');
}
}
& this is my model:
public function save($data)
{
return $this->db->insert('property', $data);
}
Your form must have the multipart attribute in HTML file like below :
If you're using form helper, then it should be
<?php echo form_open_multipart('/save');?>
Else your form should have the enctype attribute like below
<form enctype="multipart/form-data">
Then the uploaded data result $this->upload->data() will come in array. So you can't store your array in mysql column. So you need to get the filename from $this->upload->data() and store it in a variable like below.
Your Controller should be
public function save(){
$this->load->model('Partner_model');
$feature = $this->input->post('feature');
$config['upload_path'] = './uploads/files';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('image')){
$error = array('error' => $this->upload->display_errors());
$this->load->view('partner_profile', $error);
}else{
$imageArray = $this->upload->data();
$image = $imageArray['file_name'];
$user_data= array(
'pname' => $this->input->post('pname'),
'type' => $this->input->post('type'),
'address' => $this->input->post('address'),
'about' => $this->input->post('about'),
'city' => $this->input->post('city'),
'code' => $this->input->post('code'),
'state'=>$this->input->post('state'),
'feature'=>implode(",",$feature),
'image' => $image
);
}
if($this->Partner_model->save($user_data)) {
$msg = "save sucesss" ;
}else {
$msg = "not save";
}
$this->session->set_flashdata('msg', $msg);
$this->load->view('partner_profile');
}
I am still on the process of learning Yii 2 framework. I was able to create a form that uploads excel file then save to database using phpexcel. I want to enhance it in a way that the data from the uploaded excel will be displayed on a table in view so the user can check the data if they are the same with the excel file. After checking, the user will have two options whether CANCEL or CONTINUE.
Here is my controller method to read file and save:
public function importExcel($model, $readFile, $dir)
{
try {
$readFileType = \PHPExcel_IOFactory::identify($readFile);
$objReader = \PHPExcel_IOFactory::createReader($readFileType);
$objPHPExcel = $objReader->load($readFile);
}
catch(Exception $e) {
die('Error reading data from excel file.');
}
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestCol = $sheet->getHighestColumn();
for($row = 9; $row <= $highestRow; $row++) {
$rowData = $sheet->rangeToArray('A'. $row . ':' . $highestCol . $row, NULL, TRUE, FALSE);
$objPHPExcel->getActiveSheet()
->getStyle('A'. $row . ':' . $highestCol . $row)
->getNumberFormat()->setFormatCode('0000');
// ->setFormatCode( \PHPExcel_Style_NumberFormat::FORMAT_TEXT );
if($row == 9) {
continue;
}
$document = new Document();
$document->type_id = ($rowData[0][0] == 'Ordinance' ? 1 : 2);
$document->no = $rowData[0][1];
$document->series = $rowData[0][2];
$document->title = $rowData[0][3];
$document->author = $rowData[0][5];
$document->date_approved = date('Y-m-d', strtotime($rowData[0][8].' '.$rowData[0][9].' '.$rowData[0][10]));
$document->region_c = $model->region_c;
$document->province_c = $model->province_c;
$document->citymun_c = $model->citymun_c;
$document->catParent = 1;
$document->category_id = 1;
$document->file_url = $dir . '/unzip/' . $rowData[0][13];
$document->save();
}
}
I did this and it worked.
try {
$readFileType = \PHPExcel_IOFactory::identify($readFile);
$objReader = \PHPExcel_IOFactory::createReader($readFileType);
$objPHPExcel = $objReader->load($readFile);
}
catch(Exception $e) {
die('Error reading data from excel file.');
}
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestCol = $sheet->getHighestColumn();
for($row = 9; $row <= $highestRow; $row++) {
$rowData = $sheet->rangeToArray('A'. $row . ':' . $highestCol . $row, NULL, TRUE, FALSE);
$objPHPExcel->getActiveSheet()
->getStyle('A'. $row . ':' . $highestCol . $row)
->getNumberFormat()->setFormatCode('0000');
if($row == 9) {
continue;
}
$data[] = array(
'type' => $rowData[0][0],
'no' => $rowData[0][1],
'series' => $rowData[0][2],
'title' => $rowData[0][3],
'author' => $rowData[0][5],
'dateapproved' => date('Y-m-d', strtotime($rowData[0][8].' '.$rowData[0][9].' '.$rowData[0][10])),
'file' => $rowData[0][13]
);
}
$dataProvider = new ArrayDataProvider([
'allModels' => $data,
'pagination' => [
'pageSize' => 10,
],
]);
return $this->render('display', [
'dataProvider' => $dataProvider,
]);
}
If your rowData contain the data and is an array of the row read form excel you can do this
$provider = new ArrayDataProvider([
'allModels' => $rowData,
'pagination' => [
'pageSize' => 10,
],
]);
return $this->render('your:view', [
'provider' => $provider,
]);
and in your grdiView
<?= GridView::widget([
'dataProvider' => $provider,
......
Here my problem is i have a form . In that i have dependent dropdown.
for example if i select company name it automatically selects the dependent company email and company phone number. This is working perfectly while creating. but the problem is while am updating the same form, the dependent value getting reset. so that makes me to select the company name for every time but i don't to be like that. once if i select the value while creating the value shouldn't change while updating also.
_form.php
<?= $form->field($model, 'employee_id')->widget(Select2::classname(), [
'data' => ArrayHelper::map(Employeedetails::find()->all(),'id','employeecode'),
'language' => 'en',
'options' => [
'placeholder' => 'Select a employeecode ...',
'onchange' => '
$.post( "index.php?r=employeedetails/lists2&id='.'"+$(this).val().split("-")[0], function( data ) {
$( "select#claimprocess-claim_for" ).html( data );
}),
$.post( "index.php?r=employeedetails/lists3&id='.'"+$(this).val().split("-")[0], function( data ) {
$( "select#claimprocess-email" ).html( data );
}),
$.post( "index.php?r=employeedetails/lists1&id='.'"+$(this).val(), function( data ) {
$( "select#claimprocess-employee_name" ).html( data );
});',
],
'pluginOptions' => [
'allowClear' => true
],
]); ?>
This is Controller code
controller.php
public function actionLists($id)
{
$countEmployeedetails = Employeedetails::find()
->where(['company_id' => $id])
->count();
$employeedetails = Employeedetails::find()
->where(['company_id' => $id])
->all();
if($countEmployeedetails>0){
foreach($employeedetails as $employee){
echo "<option value='".$employee->id."'>".$employee->employeecode."</option>";
}
}
else{
echo "<option>-</option>";
}
}
public function actionLists1($id)
{
$countEmployeedetails = Employeedetails::find()
->where(['id' => $id])
->count();
$employeedetails = Employeedetails::find()
->where(['id' => $id])
->all();
if($countEmployeedetails >= 0)
{
foreach($employeedetails as $employee)
{
echo "<option value='".$employee->id."'>".$employee->name."</option>";
}
}
else{
echo "<option>-</option>";
}
}
public function actionLists2($id)
{
$countEmployeedetails = Employeedetails::find()
->where(['id' => $id])
->count();
$employeedetails = Employeedetails::find()
->where(['id' => $id])
->all();
if($countEmployeedetails >= 0)
{
foreach($employeedetails as $employee)
{
// $arr["id"] . '-' . $arr['designation']
echo "<option value='".$employee->id. '-' .$employee->name. "'>".$employee->RelationName."</option>";
}
}
else{
echo "<option>-</option>";
}
}
Finally i found answer, actually mistake was mine, because here am using getting records based on company_id but here i have used approvaldetails table id so that is the mistake, after i changed it to company_id, now its working good
public function actionLists2($id)
{
$countEmployeedetails = Employeedetails::find()
->where(['company_id' => $id])
->count();
$employeedetails = Employeedetails::find()
->where(['company_id' => $id])
->all();
if($countEmployeedetails >= 0)
{
foreach($employeedetails as $employee)
{
// $arr["id"] . '-' . $arr['designation']
echo "<option value='".$employee->id. '-' .$employee->name. "'>".$employee->RelationName."</option>";
}
}
else{
echo "<option>-</option>";
}
}
I am trying to display thumbnail image on EDIT form in Admin custom module.
I am getting check box to delete image.
I am getting a square box where image supposed to display.
But it's not displaying image.
Please suggest me solution
my save() action in controller is
public function saveAction()
{
if ($data = $this->getRequest()->getPost())
{
if(isset($_FILES['shop_image']['name']) && $_FILES['shop_image']['name'] != '')
{
try {
/* Starting upload */
$uploader = new Varien_File_Uploader('shop_image');
// Any extention would work
$uploader->setAllowedExtensions(array('jpg','jpeg','gif','png'));
$uploader->setAllowRenameFiles(false);
$uploader->setFilesDispersion(false);
echo $path = Mage::getBaseDir('media').DS.'ud'.DS;
$uploader->save($path, $_FILES['shop_image']['name'] );
} catch (Exception $e) {
}
// echo $path;exit;
//this way the name is saved in DB
$data['shop_image'] = $path.$_FILES['shop_image']['name'];
}
else if((isset($data['shop_image']['delete']) && $data['shop_image']['delete'] == 1)){
.'ud'.DS.$data['shop_image']['value'];
unlink($data['shop_image']['value']);
//set path to null and save to database
$data['shop_image'] = '';
}
$model = Mage::getModel('shop/shop');
$id = $this->getRequest()->getParam('id');
if ($id) {
$model->load($id);
}
$model->setData($data);
Mage::getSingleton('adminhtml/session')->setFormData($data);
try {
if ($id) {
$model->setId($id);
}
$model->save();
if (!$model->getId()) {
Mage::throwException(Mage::helper('shop')->__('Error saving shop'));
}
Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('shop')->__('Shop was successfully saved.'));
Mage::getSingleton('adminhtml/session')->setFormData(false);
// The following line decides if it is a "save" or "save and continue"
if ($this->getRequest()->getParam('back')) {
$this->_redirect('*/*/edit', array('id' => $model->getId()));
} else {
$this->_redirect('*/*/');
}
} catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
if ($model && $model->getId()) {
$this->_redirect('*/*/edit', array('id' => $model->getId()));
} else {
$this->_redirect('*/*/');
}
}
return;
}
Mage::getSingleton('adminhtml/session')->addError(Mage::helper('shop')->__('No data found to save'));
$this->_redirect('*/*/');
}
my form.php is
<?php
class Sample_Shop_Block_Adminhtml_Shop_Edit_Form extends Mage_Adminhtml_Block_Widget_Form
{
protected function _prepareForm()
{
if (Mage::getSingleton('adminhtml/session')->getExampleData())
{
$data = Mage::getSingleton('adminhtml/session')->getExamplelData();
Mage::getSingleton('adminhtml/session')->getExampleData(null);
}
elseif (Mage::registry('example_data'))
{
$data = Mage::registry('example_data')->getData();
}
else
{
$data = array();
}
$form = new Varien_Data_Form(array(
'id' => 'edit_form',
'action' => $this->getUrl('*/*/save', array('id' => $this->getRequest()->getParam('id'))),
'method' => 'post',
'enctype' => 'multipart/form-data',
));
$form->setUseContainer(true);
$this->setForm($form);
$fieldset = $form->addFieldset('example_form', array(
'legend' =>Mage::helper('shop')->__('Shop Information')
));
$fieldset->addField('shopname', 'text', array(
'label' => Mage::helper('shop')->__('Shop Name'),
'class' => 'required-entry',
'required' => true,
'name' => 'shopname',
'note' => Mage::helper('shop')->__('The name of the shop.'),
));
$fieldset->addField('logo', 'text', array(
'label' => Mage::helper('shop')->__('Logo'),
'class' => 'required-entry',
'required' => true,
'name' => 'logo',
));
$fieldset->addField('productimage', 'text', array(
'label' => Mage::helper('shop')->__('Product Image'),
'class' => 'required-entry',
'required' => true,
'name' => 'productimage',
));
$fieldset->addField('state', 'text', array(
'label' => Mage::helper('shop')->__('State'),
'class' => 'required-entry',
'required' => true,
'name' => 'state',
));
$fieldset->addField('shop_image','image', array(
'label' => Mage::helper('shop')->__('Shop Image'),
'required' => false,
'name' => 'shop_image',
));
$form->setValues($data);
return parent::_prepareForm();
}
}
Find the below easy steps to display the thumbnail image.
Add this below code in your edit ->tab->form file
ex: Package_Campaign_Block_Adminhtml_Campaign_Edit_Tab_Form
$fieldset->addType('image','Package_Campaign_Block_Adminhtml_Campaign_Helper_Image');
Create the below helper class file to display the thumbnail image.
class Package_Campaign_Block_Adminhtml_Campaign_Edit_Tab_Form extends Varien_Data_Form_Element_Abstract{
public function __construct($data) {
parent::__construct($data);
$this->setType('file');
}
public function getElementHtml() {
$html = '';
if ($this->getValue()) {
$media = Mage::getBaseUrl('media').'campaign/';
$html = '<a onclick="imagePreview(\''.$this->getHtmlId().'_image\'); return false;" href="'.$this->getValue().'"><img id="'.$this->getHtmlId().'_image" style="border: 1px solid #d6d6d6;" title="'.$this->getValue().'" src="'.$media.$this->getValue().'" alt="'.$this->getValue().'" width="30"></a> ';
}
$this->setClass('input-file');
$html.= parent::getElementHtml();
return $html;
}
}