yii\base\ErrorException Use of undefined constant logo - assumed 'logo' (this will throw an Error in a future version of PHP) - yii2

I installed web apps for Library Management, when I try to upload logo for the library, it give me error like this
Unknown Property – yii\base\UnknownPropertyException
Use of undefined constant logo - assumed 'logo' (this will throw an Error in a future version of PHP)
This is my stack trace:
1. in /otka/app/src/web/backend/modules/setting/umum/controllers/DataPerpustakaanController.php at line 44
// $model->NamaLokasiPerpustakaan = Yii::$app->config->get('NamaLokasiPerpustakaan');
$model->JenisPerpustakaan = Yii::$app->config->get('JenisPerpustakaan');
$model->IsUseKop = Yii::$app->config->get('IsUseKop');
if ($model->load(Yii::$app->request->post())) {
$model->logo = UploadedFile::getInstance($model, 'logo');
$temp_logo = ($model->logo != "" ? logo : kop);
$model->image = UploadedFile::getInstance($model, $temp_logo);
if($model->image!='')
{
$files_uploaded = '../uploaded_files/aplikasi/' . "temp_image" . '.' . "png";
$model->image->saveAs($files_uploaded,false);
$mimetype=DirectoryHelpers::mimeType($files_uploaded);
if ($mimetype){
unlink($files_uploaded);
2. in /otka/app/src/web/backend/modules/setting/umum/controllers/DataPerpustakaanController.php at line 44– yii\base\ErrorHandler::handleError(2, 'Use of undefined constant logo -...', '/otka/app/src/web/backend/module...', 44, ...)
3. backend\modules\setting\umum\controllers\DataPerpustakaanController::actionIndex()
4. in /otka/app/src/web/vendor/yiisoft/yii2/base/InlineAction.php at line 55- call_user_func_array([backend\modules\setting\umum\controllers\DataPerpustakaanController, 'actionIndex'], [])
5. in /otka/app/src/web/vendor/yiisoft/yii2/base/Controller.php at line 154– yii\base\InlineAction::runWithParams([])
6. in /otka/app/src/web/vendor/yiisoft/yii2/base/Module.php at line 454– yii\base\Controller::runAction('index', [])
7. in /otka/app/src/web/vendor/yiisoft/yii2/web/Application.php at line 84– yii\base\Module::runAction('setting/umum/data-perpustakaan/i...', [])
8. in /otka/app/src/web/vendor/yiisoft/yii2/base/Application.php at line 375– yii\web\Application::handleRequest(yii\web\Request)
This is the function line in DataPerpustakaanController.php
<?php
namespace backend\modules\setting\umum\controllers;
use Yii;
use yii\base\DynamicModel;
use yii\web\UploadedFile;
use common\components\DirectoryHelpers;
class DataPerpustakaanController extends \yii\web\Controller
{
public function actionIndex()
{
$model = new DynamicModel([
'NamaPerpustakaan',
//'NamaLokasiPerpustakaan',
'JenisPerpustakaan',
'IsUseKop',
'logo',
'kop',
'image',
]);
$model->addRule([
'NamaPerpustakaan',
//'NamaLokasiPerpustakaan',
'JenisPerpustakaan', 'IsUseKop',], 'required'
);
$model->NamaPerpustakaan = Yii::$app->config->get('NamaPerpustakaan');
// $model->NamaLokasiPerpustakaan = Yii::$app->config->get('NamaLokasiPerpustakaan');
$model->JenisPerpustakaan = Yii::$app->config->get('JenisPerpustakaan');
$model->IsUseKop = Yii::$app->config->get('IsUseKop');
if ($model->load(Yii::$app->request->post())) {
$model->logo = UploadedFile::getInstance($model, 'logo');
$temp_logo = ($model->logo != "" ? logo : kop); //**This is line 44**
$model->image = UploadedFile::getInstance($model, $temp_logo);
if($model->image!='')
{
$files_uploaded = '../uploaded_files/aplikasi/' . "temp_image" . '.' . "png";
$model->image->saveAs($files_uploaded,false);
$mimetype=DirectoryHelpers::mimeType($files_uploaded);
if ($mimetype){
unlink($files_uploaded);
if ($model->logo != "") {
$model->image->saveAs('../uploaded_files/aplikasi/' . "logo_perpusnas_2015" . '.' . "png");
} else{
$model->image->saveAs('../uploaded_files/aplikasi/' . "kop" . '.' . "png");
}
}
else {
Yii::$app->getSession()->setFlash('error', [
'type' => 'error',
'duration' => 500,
'icon' => 'fa fa-info-circle',
'message' => Yii::t('app', 'Failed Save'),
'title' => 'Info',
'positonY' => Yii::$app->params['flashMessagePositionY'],
'positonX' => Yii::$app->params['flashMessagePositionX']
]);
}
}
if ($model->validate()) {
Yii::$app->config->set('NamaPerpustakaan', Yii::$app->request->post('DynamicModel')['NamaPerpustakaan']);
//Yii::$app->config->set('NamaLokasiPerpustakaan', Yii::$app->request->post('DynamicModel')['NamaLokasiPerpustakaan']);
Yii::$app->config->set('JenisPerpustakaan', Yii::$app->request->post('DynamicModel')['JenisPerpustakaan']);
Yii::$app->config->set('IsUseKop', Yii::$app->request->post('DynamicModel')['IsUseKop']);
Yii::$app->getSession()->setFlash('success', [
'type' => 'info',
'duration' => 500,
'icon' => 'fa fa-info-circle',
'message' => Yii::t('app', 'Success Save'),
'title' => 'Info',
'positonY' => Yii::$app->params['flashMessagePositionY'],
'positonX' => Yii::$app->params['flashMessagePositionX']
]);
}
else {
Yii::$app->getSession()->setFlash('error', [
'type' => 'error',
'duration' => 500,
'icon' => 'fa fa-info-circle',
'message' => Yii::t('app', 'Failed Save'),
'title' => 'Info',
'positonY' => Yii::$app->params['flashMessagePositionY'],
'positonX' => Yii::$app->params['flashMessagePositionX']
]);
}
return $this->redirect(['index']);
} else {
return $this->render('index', [
'model' => $model,]);
}
}
}
How to fix this problem?

I solve this problem, so in line 44 there is code
$temp_logo = ($model->logo != "" ? logo : kop);
change it like this
$temp_logo = ($model->logo != "" ? 'logo' : 'kop');

Related

yii2-formwizard change model after select2 selection

I'm trying to implement a multiple models form using the form-wizard widget, with Profile as main model and few others as linked ones. When I select the entity type field for the main model, I would like to change the linked model for the next step, basing on the value of entity type field.
I have tried with this code:
Create Form Code
$modelUrlReletedModelsCreate = Profile::urlRelatedModelCreate();
$urlLinkedProfile = Url::to(['create']);
echo FormWizard::widget([
'formOptions'=>[
'id'=>'profile_form',
'enableClientValidation'=>true,
'enableAjaxValidation'=>true,
'validationUrl' => Url::to(['profile-models-validation'])
],
'theme' => FormWizard::THEME_MATERIAL_V,
'steps' => [
//step 1
[
'model' => $model,
'title' => \Yii::t('app', 'Profile'),
'fieldConfig' => [
'only' => ['entity_type_id', 'profile_type_id'],
'entity_type_id' => [
'widget' => Select2::class,
'options' => [
'data' => EntityType::arrayNamesList(),
'options' => ['placeholder' => \Yii::t('app','Select an element')],
'pluginEvents' => ['select2:select'=>'function(e){;'
. 'var type = $("#pr-ty-sel").val();'
. 'var profile= "'.($model->profile_id ? : "no").'";'
. '$.ajax({ method: "GET",'
. 'url:"'.$urlLinkedProfile.'",'
. 'data:{ entity_text : e.params.data.text,'
. 'entity_id : e.params.data.id,'
. 'profile_type_id : type,'
. 'profile_id : profile},'
. 'success: function(data){'
. '$("#profile_form").html(data);'
. '}'
. '});}'],
],
],
'profile_type_id' =>[
'widget' => Select2::class,
'options' => [
'data' => \app\models\ProfileType::arrayNamesList(),
'options' => ['placeholder' => \Yii::t('app','Select an element'),'id'=>'pr-ty-sel'],
],
]
],
'description' => \Yii::t('app', 'Add Profile Type Data'),
'formInfoText' => \Yii::t('app', 'Fill all fields'),
],
//step 2 I want ot change here $linkedModel
[
'model' => [$model,$linkedModel],
'title' => \Yii::t('app', 'Personal Data'),
'description' => \Yii::t('app', 'Insert Personal Data'),
],
]
]);
Controller Action Create Code
public function actionCreate($profileId = NULL)
{
if($profileId AND $profileId !== 'no'){
$model = $this->findModel($profileId);
}else{
$model = new Profile();
}
$profileLinkedModel = new ProfilePrivate();
$renderMethod = 'render';
if (Yii::$app->request->isAjax) {
$entityText = \Yii::$app->request->get('entity_text');
$entity_id = \Yii::$app->request->get('entity_id');
$profileTypeId = \Yii::$app->request->get('profile_type_id');
$profileId = \Yii::$app->request->get('profile_id');
//Utility function to clean the entity text (remove number and special characters)
$entityTextCleaned = \app\components\Utility::cleanString($entityText);
if ($entityTextCleaned == 'private') {
$profileLinkedModel = new ProfilePrivate();
} elseif ($entityText == 'company') {
$profileLinkedModel = new ProfileCompany();
} else {
//#TODO
return FALSE;
}
$model->entity_type_id = $entity_id;
$model->profile_type_id = $profileTypeId;
$profileLinkedModel->profile_id = $model->profile_id;
Yii::$app->response->format = Response::FORMAT_JSON;
$renderMethod = 'renderAjax';
}
//extra table field used to enable custom rule in model
$model->createFullProfile = TRUE;
if ($model->load(Yii::$app->request->post())) {
return $this->redirect(['view', 'id' => $model->profile_id]);
}
return $this->$renderMethod('create', [
'model' => $model,
'profileLinkedModel' => $profileLinkedModel,
]);
}
When I select a field for entity type field, the server runs the ajax request on select event, but when it ends the other form field is not more selectable. So, in other words, after the ajax request I'm unable to select the profile type field. If I try to select the profile type field before the entity type field I can go to next step, but load always the default model.

Yii2 Dynamic form update fail on kartik-Select2

I am using wbraganca dynamic form widget. It works fine for the Create action.
Let me thanks for those guys making great tutorial video on youtube!!!
I am working on the Update action now. I work it on a purchase order function.
the controller of update action :
public function actionUpdate($id)
{
$model = $this->findModel($id);
$modelsItem = $model->purchaseitems;
if ($model->load(Yii::$app->request->post()) ) {
$oldIDs = ArrayHelper::map($modelsItem, 'purchaseitem_id', 'purchaseitem_id');
$modelsItem = Model::createMultiple(Purchaseitem::classname(), $modelsItem);
Model::loadMultiple($modelsItem, Yii::$app->request->post());
$deletedIDs = array_diff($oldIDs, array_filter(ArrayHelper::map($modelsItem, 'purchaseitem_id', 'purchaseitem_id')));
$valid = $model->validate();
$valid = Model::validateMultiple($modelsItem) && $valid;
if ($valid) {
$transaction = \Yii::$app->db->beginTransaction();
try {
if ($flag = $model->save(false)) {
if (! empty($deletedIDs)) {
Purchaseitem::deleteAll(['purchaseitem_id' => $deletedIDs]);
}
foreach ($modelsItem as $modelItem) {
$modelItem->purchaseitem_purchaseorder_id = $model->purchaseorder_id;
$modelItem->purchaseitem_description = Inventory::findOne($modelItem->purchaseitem_inventory_id)->inventory_partno;
if (! ($flag = $modelItem->save(false))) {
$transaction->rollBack();
break;
}
}
}
if ($flag) {
$transaction->commit();
return $this->redirect(['view', 'id' => $model->purchaseorder_id]);
}
} catch (Exception $e) {
$transaction->rollBack();
}
}
//return $this->redirect(['view', 'id' => $model->purchaseorder_id]);
} else {
return $this->render('update', [
'model' => $model,
'modelsItem' => (empty($modelsItem)) ? [new Purchaseitem] : $modelsItem
]);
}
}
But I think the problem may happen on the view file, as the Select2 field can show the value, which is the 'id' of the product rather than the product code.
view:
<div class="panel panel-default">
<div class="panel-body">
<?php DynamicFormWidget::begin([
'widgetContainer' => 'dynamicform_wrapper',
'widgetBody' => '.container-items',
'widgetItem' => '.item',
'limit' => 50,
'min' => 1,
'insertButton' => '.add-item',
'deleteButton' => '.remove-item',
'model' => $modelsItem[0],
'formId' => 'dynamic-form',
'formFields' => [
'purchaseitem_inventory_id',
'purchaseitem_qty',
'purchaseitem_cost_usd',
'purchaseitem_deliverydate',
],
]); ?>
<?php foreach ($modelsItem as $i => $modelItem): ?>
<div class="item">
<?php
// necessary for update action.
if (! $modelItem->isNewRecord) {
echo Html::activeHiddenInput($modelItem, "[{$i}]purchaseitem_id");
}
?>
<div class="row">
<?= $form->field($modelItem, "[{$i}]purchaseitem_inventory_id")->widget(
Select2::classname(), [
'pluginOptions' => [
'allowClear' => true,
'minimumInputLength' => 2,
'language' => [
'errorLoading' => new JsExpression("function () { return 'Error on finding results...'; }"),
],
'ajax' => [
'url' => Url::toRoute('inventory/inventorylist'),
'dataType' => 'json',
'data' => new JsExpression('function(params) { return {q:params.term}; }')
],
'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
'templateResult' => new JsExpression('function(purchaseitem_inventory_id) { return purchaseitem_inventory_id.text; }'),
'templateSelection' => new JsExpression('function (purchaseitem_inventory_id) { return purchaseitem_inventory_id.text; }'),
],
])->label(false) ?>
<?= $form->field($modelItem, "[{$i}]purchaseitem_qty")->textInput(['maxlength' => true])->label(false) ?>
<?= $form->field($modelItem, "[{$i}]purchaseitem_cost_usd")->textInput(['maxlength' => true])->label(false) ?>
<?= $form->field($modelItem, "[{$i}]purchaseitem_deliverydate")->widget(
DatePicker::className(), [
'options' => [
['placeholder' => 'Please enter delivery date'],
],
'removeButton' => false,
'pluginOptions' => [
'autoclose'=>true,
'format' => 'yyyy-mm-dd',
'todayHighlight' => true,
]
]
)->label(false) ?>
</div>
</div>
<?php endforeach; ?>
</div>
</div>
I have a thought that the problem maybe related to that few lines of JsExpression function.
'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
'templateResult' => new JsExpression('function(purchaseitem_inventory_id) { return purchaseitem_inventory_id.text; }'),
'templateSelection' => new JsExpression('function (purchaseitem_inventory_id) { return purchaseitem_inventory_id.text; }'),
For the Select2 query URL method is here:
public function actionInventorylist($q = null, $id = null) {
Yii::$app->response->format = yii\web\Response::FORMAT_JSON;
$out = ['results' => ['id' => '', 'text' => '']];
if (!is_null($q)) {
$query = new Query;
$query->select('inventory_id AS id, inventory_partno AS text')
->from('inventory')
->where(['like', 'inventory_partno', $q])
->limit(10);
$command = $query->createCommand();
$data = $command->queryAll();
$out['results'] = array_values($data);
}
elseif ($id > 0) {
$out['results'] = ['id' => $id, 'text' => Inventory::find($id)->inventory_partno];
}
return $out;
}
I can load the record, when I click in the update view. Most of the data are feed in right place of the form, except the 'partno' field. I use Select2 to let user select partno by text and store the 'id' in table. It works on the Create view.
but in the update view, it only show the 'id' instead of the 'partno'.
if I make input to the field, I can select 'other' partno only, let me explain here:
if there are 2 code, "ABC" with 'id' is 1, "XYZ" with 'id' 2.
the record original is "ABC", the field show "1".
If I input "XYZ", it will show "XYZ" as normal effect of widget. But, if I change back to "ABC", it will show "1" instead of "ABC".
And the form also cannot submit for update. the button click with no effect.
I am new to Yii2 framework, and quite stuck on this issue, does anyone knows how can I solve this?
THANKS!!!!
I just solve the problem, a few issue happened actually.
To solve the Select2 widget cannot display the partno instead of the ID, I find the partno by the ID and feed it with initValueText in Select2. For my case:
$partno = empty($modelItem->purchaseitem_inventory_id) ? '':Inventory::findOne($modelItem->purchaseitem_inventory_id)->inventory_partno;
$form->field($modelItem, "[{$i}]purchaseitem_inventory_id")->widget(Select2::classname(), ['initValueText' => $partno, ...
About the update POST fail issue, I got error of Getting unknown property: backend\models\Purchaseitem::id, and I found it happened on the Dynamic-form widgets Model.php line 25. That lines is $keys = array_keys(ArrayHelper::map($multipleModels, 'id', 'id'));
If I change the 'id' to my ID field name, i.e 'purchaseitem_id', it will work, but this model will only work for this Id field name afterward. So I get the model's primaryKey and make it work for my other model.
add this line $primaryKey = $model->tableSchema->primaryKey; and modify above line $keys = array_keys(ArrayHelper::map($multipleModels, $primaryKey, $primaryKey));

Yii2 Validation: Image may not be empty

I use ActiveRecord and I want to upload an image. But Yii always says that the fileInput is empty.
My model has an extra attribute called "image" and the rules are
[['image'], 'required', 'on' => 'new'],
[['image'], 'image', 'extensions' => 'png, jpg'],
And I use this Code in the controller
$model = new Picture();
$model->scenario = 'new';
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$model->image = UploadedFile::getInstance($model, 'image');
$model->image->saveAs($model->savePath($this->plugin).'/'.$model->id.'.jpg');
}
What am I doing wrong?
Below code is working for me, hope it will help you,
[['logo'], 'required', 'on' => 'create'],
[['logo'], 'file', 'skipOnError' => true,'extensions' => 'png, jpg, gif'],
$model = new Company();
$model->scenario = 'create';
if ($model->load(Yii::$app->request->post())) {
$logo = UploadedFile::getInstance($model, 'logo');
if (!is_null($logo)) {
$model->logo = $logo->name;
if($model->validate()) {
$dirpath = dirname(getcwd());
$logo->saveAs($dirpath . '/admin/uploads/' . $logo->baseName . '.' . $logo->extension);
$model->save();
return $this->redirect(['view', 'id' => $model->Id]);
}
}
}

PHP - Yii 2.0 Multiple images are save in folder but not saved in database

I have used use kartik\file\FileInput; (extension) for saving multiple images from single form submit.
The images are save locally but are not saving in the database.
Here is my Model Code media.php
namespace app\models;
use yii\web\UploadedFile;
class Media extends \yii\db\ActiveRecord
{
public function rules(){
return [
[['title'], 'file', 'skipOnEmpty' => false, 'extensions' => ['gif', 'jpg', 'png', 'jpeg', 'JPG', 'JPEG', 'PNG', 'GIF'], 'checkExtensionByMimeType' => false ,'maxFiles' => 4, 'maxSize' => 1024 * 1024 * 1024],
[['extension'], 'string', 'max' => 6],
];
}
Controller code:
if ($mediamodel->load ( Yii::$app->request->post () )) {
$title = UploadedFile::getInstances ( $mediamodel, 'title' );
foreach ($title as $key => $file) {
$file->saveAs(Yii::$app->basePath . '/web/images/hotel/'. $file->baseName . '.' . $file->extension);}
foreach ($title as $key => $file){
echo $mediamodel->title."*********";
$mediamodel->title = $file->baseName . '.' . $file->extension;
echo " \Title: ".$mediamodel->title;
$mediamodel->save ();
}
}
My view code:
use kartik\file\FileInput;
$form = ActiveForm::begin([ 'layout' => 'horizontal', {label}\n{beginWrapper}\n{input}\n{hint}\n{error}\n{endWrapper}",
'fieldConfig' => ['horizontalCssClasses' => ['label' => 'col-md-3','offset' => 'col-md-offset-2','wrapper' => 'col-md-4', 'error' => '','hint' => '',],],'
options' => [ 'class' => 'form-horizontal', 'enctype' => 'multipart/form-data', ], ]);?>
<?php echo $form->field($mediamodel, 'title[]')->widget(FileInput::classname(), ['options'=>['multiple' => true]]);
Html::submitButton($model->isNewRecord ? 'Add' : 'Update');
use
$mediamodel->save (false);
instead of
$mediamodel->save ();
// You should handle errors like this.
if(!$mediamodel->save()){
// handle the errors of model.
var_dump($mediamodel->getErrors());
}

magento 1.9 Edit form is not displaying thumbnail image

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;
}
}