Yii2 : Upload Image using Kartik/FileInput Plugin - file-upload

I want to upload an image via Kartik widget. After submitting the form, the $_FILE['Product'] has the data about the image but getInstance($model, 'images') returns null. Tried with images[], also null.
This is what I'm trying to var_dump in the controller:
public function actionCreate()
{
$model = new Product();
if ($model->load(Yii::$app->request->post())) {
var_dump(UploadedFile::getInstance($model, 'images[]'));die;
And this is my model Product:
<?php
namespace app\models;
use backend\models\CActiveRecord;
use Yii;
use omgdef\multilingual\MultilingualQuery;
use omgdef\multilingual\MultilingualBehavior;
use yii\web\UploadedFile;
/**
* This is the model class for table "product".
*
* #property int $id
* #property int $category_id
* #property int $quantity
* #property double $price
* #property int $sort
*
* #property Productlang[] $productlangs
*/
class Product extends CActiveRecord
{
public $images;
public static function find()
{
return new MultilingualQuery(get_called_class());
}
public function behaviors()
{
$allLanguages = [];
foreach (Yii::$app->params['languages'] as $title => $language) {
$allLanguages[$title] = $language;
}
return [
'ml' => [
'class' => MultilingualBehavior::className(),
'languages' => $allLanguages,
//'languageField' => 'language',
//'localizedPrefix' => '',
//'requireTranslations' => false',
//'dynamicLangClass' => true',
//'langClassName' => PostLang::className(), // or namespace/for/a/class/PostLang
'defaultLanguage' => Yii::$app->params['languageDefault'],
'langForeignKey' => 'product_id',
'tableName' => "{{%productLang}}",
'attributes' => [
'title',
'description',
'meta_title',
'meta_desc',
'url'
]
],
];
}
/**
* #inheritdoc
*/
public static function tableName()
{
return 'product';
}
/**
* #inheritdoc
*/
public function rules()
{
$string = $this->multilingualFields(['description', 'url']);
$string_59 = $this->multilingualFields(['meta_title']);
$string_255 = $this->multilingualFields(['meta_desc', 'title']);
$string[] = 'description';
$string[] = 'url';
$string_59[] = 'meta_title';
$string_255[] = 'meta_desc';
$string_255[] = 'title';
return [
[['quantity', 'price', 'title', 'meta_title', 'meta_desc'], 'required'],
[['category_id', 'quantity', 'sort'], 'integer'],
[$string, 'string'],
[$string_59, 'string', 'max' => 59],
[$string_255, 'string', 'max' => 255],
[['price'], 'number'],
['images', 'file']
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'category_id' => 'Category ID',
'quantity' => 'Quantity',
'price' => 'Price',
'sort' => 'Sort',
];
}
public function upload()
{
if ($this->validate()) {
foreach ($this->image as $file) {
$file->saveAs(\Yii::getAlias("#images") . "/products/" . $this->id . "_" . $this->image->baseName . '.' . $this->image->extension);
}
return true;
} else {
return false;
}
}
}
Tried with rules ['images', 'safe'] also ['images', 'file'] ( think the second one is not right because the attribute is an array, right ? ). The form is <?php $form = ActiveForm::begin(['options' => ['multipart/form-data']]); ?>.
Finally my input:
<?= $form->field($model, 'images[]')->widget(FileInput::class, [
'showMessage' => true,
]) ?>
Full controller action:
public function actionCreate()
{
$model = new Product();
if ($model->load(Yii::$app->request->post())) {
foreach (Yii::$app->params['languages'] as $language){
if(Yii::$app->params['languageDefault'] != $language){
$title_lang = "title_$language";
$model->$title_lang = Yii::$app->request->post('Product')["title_$language"];
$description_lang = "description_$language";
$model->$description_lang = Yii::$app->request->post('Product')["description_$language"];
$meta_title_lang = "meta_title_$language";
$model->$meta_title_lang = Yii::$app->request->post('Product')["meta_title_$language"];
$meta_desc_lang = "meta_desc_$language";
$model->$meta_desc_lang = Yii::$app->request->post('Product')["meta_desc_$language"];
}
}
if($model->save()){
$model = $this->findModel($model->id, true);
//Make urls
foreach (Yii::$app->params['languages'] as $language) {
if (Yii::$app->params['languageDefault'] != $language) {
$url_lang = "url_$language";
$title_lang = "title_$language";
$model->$url_lang = $model->constructURL(
$model->$title_lang,
$model->id
);
}else{
$model->url = $model->constructURL(
$model->title,
$model->id
);
}
}
//Upload Images
$model->images = UploadedFile::getInstance($model, 'images');
if (!($model->upload())) {
Yii::$app->session->setFlash('error', Yii::t('app', 'Some problem with the image uploading occure!'));
return $this->redirect(['create']);
}
if($model->update() !== false){
return $this->redirect(['view', 'id' => $model->id]);
}else{
Yii::$app->session->setFlash('error', Yii::t('app', 'Something went wrong. Please, try again later!'));
return $this->redirect(['create']);
}
}
}
return $this->render('create', [
'model' => $model,
]);
}

What looks like you are trying to upload a single image you should remove the [] from the input field name from the ActiveForm field declaration, and from models rules.
Single File
<?= $form->field($model, 'images')->widget(FileInput::class, [
'showMessage' => true,
'pluginOptions' => [
'showCaption' => false ,
'showRemove' => false ,
'showUpload' => false ,
'showPreview' => false ,
'browseClass' => 'btn btn-success btn-block' ,
'browseIcon' => '<i class="glyphicon glyphicon-camera"></i> ' ,
'browseLabel' => 'Select Profile Image'
] ,
'options' => ['accept' => 'image/*' ] ,
]) ?>
and from the following line
UploadedFile::getInstance($model, 'images');
Multiple Files
For multiple files you need to add 'options' => ['multiple' => true] for the field and change the attribute name to images[]
<?= $form->field($model, 'images[]')->widget(FileInput::class, [
'showMessage' => true,
'pluginOptions' => [
'showCaption' => false ,
'showRemove' => false ,
'showUpload' => false ,
'showPreview' => false ,
'browseClass' => 'btn btn-success btn-block' ,
'browseIcon' => '<i class="glyphicon glyphicon-camera"></i> ' ,
'browseLabel' => 'Select Profile Image'
] ,
'options' => ['accept' => 'image/*' ,'multiple'=>true] ,
]) ?>
and for receiving the uploaded files you should not specify the attribute as an array just change getInstance to getInstances and then try printing, it will show you all the images use foreach() to save all of them.
UploadedFile::getInstances($model, 'images');
I personally prefer to use a separate model for file uploading rather than using the ActiveRecord model.
Note: When using multiple files upload, you can also specify the 'maxFiles'=>1000 inside you model rules to limit the number of files to be uploaded
EDIT
For troubleshooting your code you should comment out the actionCreate from the controller and replace with the one i added below
public function actionCreate() {
$model = new Product();
if ( $model->load ( Yii::$app->request->post () ) ) {
foreach ( Yii::$app->params['languages'] as $language ) {
if ( Yii::$app->params['languageDefault'] != $language ) {
$title_lang = "title_$language";
$model->$title_lang = Yii::$app->request->post ( 'Product' )["title_$language"];
$description_lang = "description_$language";
$model->$description_lang = Yii::$app->request->post ( 'Product' )["description_$language"];
$meta_title_lang = "meta_title_$language";
$model->$meta_title_lang = Yii::$app->request->post ( 'Product' )["meta_title_$language"];
$meta_desc_lang = "meta_desc_$language";
$model->$meta_desc_lang = Yii::$app->request->post ( 'Product' )["meta_desc_$language"];
}
}
$transaction = Yii::$app->db->beginTransaction ();
try {
if ( !$model->save () ) {
throw new \Exception ( implode ( "<br />" , \yii\helpers\ArrayHelper::getColumn ( $model->errors , 0 , false ) ) );
}
//Make urls
foreach ( Yii::$app->params['languages'] as $language ) {
if ( Yii::$app->params['languageDefault'] != $language ) {
$url_lang = "url_$language";
$title_lang = "title_$language";
$model->$url_lang = $model->constructURL (
$model->$title_lang , $model->id
);
} else {
$model->url = $model->constructURL (
$model->title , $model->id
);
}
}
//save the new urls
if ( !$model->save () ) {
throw new \Exception ( implode ( "<br />" , \yii\helpers\ArrayHelper::getColumn ( $model->errors , 0 , false ) ) );
}
//Upload Images
$model->images = UploadedFile::getInstances ( $model , 'images' );
$model->upload ();
//commit the transatction to save the record in the table
$transaction->commit ();
Yii::$app->session->setFlash ( 'success' , 'The model saved successfully.' );
return $this->redirect ( [ 'view' , 'id' => $model->id ] );
} catch ( \Exception $ex ) {
$transaction->rollBack ();
Yii::$app->session->setFlash ( 'error' , Yii::t ( 'app' , $ex->getMessage () ) );
}
}
return $this->render ( 'create' , [
'model' => $model ,
] );
}
And comment out the upload() function of your model and add below function
public function upload() {
$skipped = [];
foreach ( $this->images as $file ) {
if ( !$file->saveAs ( \Yii::getAlias ( "#images" ) . "/products/" . $this->id . "_" . $this->image->baseName . '.' . $this->image->extension ) ) {
$skipped[] = "File " . $file->baseName . " was not saved.";
}
}
if ( !empty ( $skipped ) ) {
Yii::$app->session->setFlash ( 'error' , implode ( "<br>" , $skipped ) );
}
}
And for the ActiveForm make sure your input matches the following
$form->field($model, 'images[]')->widget(FileInput::class, [
'showMessage' => true,
'pluginOptions' => [
'showCaption' => false ,
'showRemove' => false ,
'showUpload' => false ,
'showPreview' => false ,
'browseClass' => 'btn btn-success btn-block' ,
'browseIcon' => '<i class="glyphicon glyphicon-camera"></i> ' ,
'browseLabel' => 'Select Profile Image'
] ,
'options' => ['accept' => 'image/*','multiple'=>true ] ,
]) ;

Related

Create form in back office by module Prestashop 1.7

I made a module to hook a form in product page in the back office (with hook DisplayAdminProductExtra).
How can I create a form with some inputs by module?
I think it can be done by {helper and .tpl file} or {form_field and .twig file}.
If anyone explains this as a walkthrough I'm sure it's gonna be a good reference for many others too.
this is the code that created by PrestaShop module generator:
<?php
if (!defined('_PS_VERSION_')) {
exit;
}
class Myfirstmodule extends Module
{
protected $config_form = false;
public function __construct()
{
$this->name = 'myfirstmodule';
$this->tab = 'administration';
$this->version = '1.0.0';
$this->author = 'parsa';
$this->need_instance = 0;
/**
* Set $this->bootstrap to true if your module is compliant with bootstrap (PrestaShop 1.6)
*/
$this->bootstrap = true;
parent::__construct();
$this->displayName = $this->l('new module');
$this->description = $this->l('first module');
$this->confirmUninstall = $this->l('Are you sure?');
$this->ps_versions_compliancy = array('min' => '1.7', 'max' => _PS_VERSION_);
}
/**
* Don't forget to create update methods if needed:
* http://doc.prestashop.com/display/PS16/Enabling+the+Auto-Update
*/
public function install()
{
Configuration::updateValue('MYFIRSTMODULE_LIVE_MODE', false);
return parent::install() &&
$this->registerHook('header') &&
$this->registerHook('backOfficeHeader') &&
$this->registerHook('displayAdminProductsExtra');
}
public function uninstall()
{
Configuration::deleteByName('MYFIRSTMODULE_LIVE_MODE');
return parent::uninstall();
}
/**
* Load the configuration form
*/
public function getContent()
{
/**
* If values have been submitted in the form, process.
*/
if (((bool)Tools::isSubmit('submitMyfirstmoduleModule')) == true) {
$this->postProcess();
}
$this->context->smarty->assign('module_dir', $this->_path);
$output = $this->context->smarty->fetch($this->local_path . 'views/templates/admin/configure.tpl');
return $output . $this->renderForm();
}
/**
* Create the form that will be displayed in the configuration of your module.
*/
protected function renderForm()
{
$helper = new HelperForm();
$helper->show_toolbar = false;
$helper->table = $this->table;
$helper->module = $this;
$helper->default_form_language = $this->context->language->id;
$helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG', 0);
$helper->identifier = $this->identifier;
$helper->submit_action = 'submitMyfirstmoduleModule';
$helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false)
. '&configure=' . $this->name . '&tab_module=' . $this->tab . '&module_name=' . $this->name;
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->tpl_vars = array(
'fields_value' => $this->getConfigFormValues(), /* Add values for your inputs */
'languages' => $this->context->controller->getLanguages(),
'id_language' => $this->context->language->id,
);
return $helper->generateForm(array($this->getConfigForm()));
}
/**
* Create the structure of your form.
*/
protected function getConfigForm()
{
return array(
'form' => array(
'legend' => array(
'title' => $this->l('Settings'),
'icon' => 'icon-cogs',
),
'input' => array(
array(
'type' => 'switch',
'label' => $this->l('Live mode'),
'name' => 'MYFIRSTMODULE_LIVE_MODE',
'is_bool' => true,
'desc' => $this->l('Use this module in live mode'),
'values' => array(
array(
'id' => 'active_on',
'value' => true,
'label' => $this->l('Enabled')
),
array(
'id' => 'active_off',
'value' => false,
'label' => $this->l('Disabled')
)
),
),
array(
'col' => 3,
'type' => 'text',
'prefix' => '<i class="icon icon-envelope"></i>',
'desc' => $this->l('Enter a valid email address'),
'name' => 'MYFIRSTMODULE_ACCOUNT_EMAIL',
'label' => $this->l('Email'),
),
array(
'type' => 'password',
'name' => 'MYFIRSTMODULE_ACCOUNT_PASSWORD',
'label' => $this->l('Password'),
),
),
'submit' => array(
'title' => $this->l('Save'),
),
),
);
}
/**
* Set values for the inputs.
*/
protected function getConfigFormValues()
{
return array(
'MYFIRSTMODULE_LIVE_MODE' => Configuration::get('MYFIRSTMODULE_LIVE_MODE', true),
'MYFIRSTMODULE_ACCOUNT_EMAIL' => Configuration::get('MYFIRSTMODULE_ACCOUNT_EMAIL', 'contact#prestashop.com'),
'MYFIRSTMODULE_ACCOUNT_PASSWORD' => Configuration::get('MYFIRSTMODULE_ACCOUNT_PASSWORD', null),
);
}
/**
* Save form data.
*/
protected function postProcess()
{
$form_values = $this->getConfigFormValues();
foreach (array_keys($form_values) as $key) {
Configuration::updateValue($key, Tools::getValue($key));
}
}
/**
* Add the CSS & JavaScript files you want to be loaded in the BO.
*/
public function hookBackOfficeHeader()
{
if (Tools::getValue('module_name') == $this->name) {
$this->context->controller->addJS($this->_path . 'views/js/back.js');
$this->context->controller->addCSS($this->_path . 'views/css/back.css');
}
}
/**
* Add the CSS & JavaScript files you want to be added on the FO.
*/
public function hookHeader()
{
$this->context->controller->addJS($this->_path . '/views/js/front.js');
$this->context->controller->addCSS($this->_path . '/views/css/front.css');
}
public function hookDisplayAdminProductsExtra()
{
/* Place your code here. */
}
}
Welcome on Stack Overflow
using HelperForm on PrestaShop 1.7 product page is not really working at this moment, it is recommended to use HTML markup and get all values of the form from the $_POST using actionProductSave hook

Yii2: show user friendly validation errors when using try catch with transactions

I am using bootstrap ActiveForm. Here is my form:
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use kartik\file\FileInput;
/* #var $this yii\web\View */
/* #var $model common\models\Customer */
/* #var $form yii\widgets\ActiveForm */
?>
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data'],
'id' => 'customer-form',
'enableClientValidation' => true,
'options' => [
'validateOnSubmit' => true,
'class' => 'form'
],
'layout' => 'horizontal',
'fieldConfig' => [
'horizontalCssClasses' => [
'label' => 'col-sm-4',
// 'offset' => 'col-sm-offset-2',
'wrapper' => 'col-sm-8',
],
],
]); ?>
<?= $form->field($model, 'email')->textInput(['maxlength' => true]) ?>
<?php ActiveForm::end(); ?>
Here is my model:
class Customer extends \yii\db\ActiveRecord
{
public $username;
public $password;
public $status;
public $email;
public $uploads;
public function rules()
{
return [
[['user_id', 'created_by', 'updated_by'], 'integer'],
[['created_at','uploads', 'updated_at','legacy_customer_id','fax','phone_two','trn'], 'safe'],
[['company_name','customer_name','username','password', 'tax_id'], 'string', 'max' => 200],
[['customer_name','email','legacy_customer_id','company_name','city'], 'required'],
[['is_deleted','status'], 'boolean'],
[['address_line_1', 'state','phone', 'country'], 'string', 'max' => 450],
[['address_line_2', 'city', 'zip_code'], 'string', 'max' => 45],
[['user_id','legacy_customer_id'], 'unique'],
['email', 'email'],
[['uploads'], 'file', 'maxFiles' => 10],
[['email'], 'unique', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['email' => 'email'], 'message' => 'This email address has already been taken.'],
[['user_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['user_id' => 'id']],
];
}
}
Here is Controller
public function actionCreate() {
$model = new Customer();
if ($model->load(Yii::$app->request->post())) {
$transaction = Yii::$app->db->beginTransaction();
try
{
$user_create = \common\models\User::customeruser($model);
if ($user_create) {
$model->user_id = $user_create->id;
$auth = \Yii::$app->authManager;
$role = $auth->getRole('customer');
$auth->assign($role, $model->user_id);
}
if ($user_create && $model->save()) {
$photo = UploadedFile::getInstances($model, 'uploads');
if ($photo !== null) {
$save_images = \common\models\CustomerDocuments::save_document($model->user_id, $photo);
}
$transaction->commit();
return $this->redirect(['view', 'id' => $model->user_id]);
}
}catch (Exception $e)
{
$transaction->rollBack();
}
}
if (Yii::$app->request->isAjax) {
return $this->renderAjax('create', [
'model' => $model,
]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
Now the required attribute working used in the rules. It does not allow the form to submit until the required field filled with some value, but at the same time the unique attribute using with target class not working and allow the form to submit. After click the submit form the form will not submit but it does not show the error of unique validation. Regard I am using the form in bootstrap modal and I want the form will show the unique submit error before submission like the same as required working. I can do it using jQuery on blur function and send custom AJAX request but I want the default solution of Yii 2.
EDIT
This is where the error is throw due to user not being saved
public static function customeruser( $model ) {
$user = new User();
$user->username = $model->email;
$user->email = $model->email;
$user->setPassword ( $model->legacy_customer_id );
$user->generateAuthKey ();
if ( !$user->save () ) {
var_dump ( $user->getErrors () );
exit ();
} return $user->save () ? $user : null;
}
var_dump() shows the following
'username' => array (size = 1)
0 => string 'This username has already been taken.' (length = 37)
'email' => array (size = 1) 0 => string 'This email address has already been taken.' (length = 42).
As you are using the try catch block along with the transaction you should throw and catch such errors as the exception so that the transaction is rolled back, and the message is displayed to the user too.
You are not consuming or using the beauty of try{}catch(){} block with transactions. You should always throw an Exception in case any of the models are not saved and the catch block will rollback the transaction.
For example, you are saving the user in the function customeruser() by calling
$user_create = \common\models\User::customeruser($model);
and returning the user object or null otherwise and then in the very next line, you are verifying the user was created or not.
if ($user_create) {
You should simply throw an exception from the function customeruser() in case the model was not saved and return the $user object otherwise, you don't have to check $user_create again to verify if user was not saved the exception will be thrown and control will be transferred to the catch block and the lines after $user_create = \common\models\User::customeruser($model); will never be called.
I mostly use the following way when i have multiple models to save and i am using the transaction block.
$transaction = Yii::$app->db->beginTransaction ();
try {
if ( !$modelUser->save () ) {
throw new \Exception ( implode ( "<br />" , \yii\helpers\ArrayHelper::getColumn ( $modelUser->errors , 0 , false ) ) );
}
if ( !$modelProfile->save () ) {
throw new \Exception ( implode ( "<br />" , \yii\helpers\ArrayHelper::getColumn ( $modelProfile->errors , 0 , false ) ) );
}
$transaction->commit();
} catch ( \Exception $ex ) {
$transaction->rollBack();
Yii::$app->session->setFlash ( 'error' , $ex->getMessage () );
}
So you can do the same for your code
public static function customeruser( $model ) {
$user = new User();
$user->username = $model->email;
$user->email = $model->email;
$user->setPassword ( $model->legacy_customer_id );
$user->generateAuthKey ();
if(!$user->save()){
throw new \Exception ( implode ( "<br />" , \yii\helpers\ArrayHelper::getColumn ( $user->errors , 0 , false ) ) );
}
return $user;
}
change your actionCreate to the following
public function actionCreate() {
$model = new Customer();
if ( $model->load ( Yii::$app->request->post () ) ) {
$transaction = Yii::$app->db->beginTransaction ();
try {
$user_create = \common\models\User::customeruser ( $model );
$model->user_id = $user_create->id;
$auth = \Yii::$app->authManager;
$role = $auth->getRole ( 'customer' );
$auth->assign ( $role , $model->user_id );
if ( !$model->save () ) {
throw new \Exception ( implode ( "<br />" , \yii\helpers\ArrayHelper::getColumn ( $model->errors , 0 , false ) ) );
}
$photo = UploadedFile::getInstances ( $model , 'uploads' );
if ( $photo !== null ) {
$save_images = \common\models\CustomerDocuments::save_document ( $model->user_id , $photo );
}
$transaction->commit ();
return $this->redirect ( [ 'view' , 'id' => $model->user_id ] );
} catch ( \Exception $ex ) {
Yii::$app->session->setFlash ( 'error' , $ex->getMessage () );
$transaction->rollBack ();
}
}
if ( Yii::$app->request->isAjax ) {
return $this->renderAjax ( 'create' , [
'model' => $model ,
] );
}
return $this->render ( 'create' , [
'model' => $model ,
] );
}
There are two three thing :
1. You are not accepting email address by user input .
2. It will insert a blank entry if in database your field is taken as NULL
3. In second insertion it will show you the error message if db field is not NUll.
Solution:
1. Make db field Not NUll .
2. Take email as user input .
3. Try to print error
if ($model->validate()) {
// all inputs are valid
} else {
// validation failed: $errors is an array containing error messages
$errors = $model->errors;
}
4. remove 'skipOnError' => true,
Try Above I am sure you will get the solution
Help Full LINK For validation

Prestashop 1.7 - Overriding module class

i try to overriding a module in my custom themes, so I have copy past the original folder (from module folder in my themes > themename > modules folder)
but its not working
I have in my module folder from my theme :
ps_sharebuttons > views
and
ps_sharebuttons > ps_sharebuttons.php
which contains
<?php
if (!defined('_PS_VERSION_')) {
exit;
}
class Ps_SharebuttonsOverride extends Ps_Sharebuttons
{
public function renderWidget($hookName, array $params)
{
var_dump($params);
exit;
$key = 'ps_sharebuttons|' . $params['product']['id_product'];
if (!empty($params['product']['id_product_attribute'])) {
$key .= '|' . $params['product']['id_product_attribute'];
}
if (!$this->isCached($this->templateFile, $this->getCacheId($key))) {
$this->smarty->assign($this->getWidgetVariables($hookName, $params));
}
return $this->fetch($this->templateFile, $this->getCacheId($key));
}
public function getWidgetVariables($hookName, array $params)
{
if (!isset($this->context->controller->php_self) || $this->context->controller->php_self != 'product') {
return;
}
$product = $this->context->controller->getProduct();
if (!Validate::isLoadedObject($product)) {
return;
}
$social_share_links = [];
$sharing_url = addcslashes($this->context->link->getProductLink($product), "'");
$sharing_name = addcslashes($product->name, "'");
$image_cover_id = $product->getCover($product->id);
if (is_array($image_cover_id) && isset($image_cover_id['id_image'])) {
$image_cover_id = (int)$image_cover_id['id_image'];
} else {
$image_cover_id = 0;
}
$sharing_img = addcslashes($this->context->link->getImageLink($product->link_rewrite, $image_cover_id), "'");
if (Configuration::get('PS_SC_FACEBOOK')) {
$social_share_links['facebook'] = array(
'label' => $this->trans('Share', array(), 'Modules.Sharebuttons.Shop'),
'class' => 'facebook',
'url' => 'http://www.facebook.com/sharer.php?u='.$sharing_url,
);
}
if (Configuration::get('PS_SC_TWITTER')) {
$social_share_links['twitter'] = array(
'label' => $this->trans('Tweet', array(), 'Modules.Sharebuttons.Shop'),
'class' => 'twitter',
'url' => 'https://twitter.com/intent/tweet?text='.$sharing_name.' '.$sharing_url,
);
}
if (Configuration::get('PS_SC_GOOGLE')) {
$social_share_links['googleplus'] = array(
'label' => $this->trans('Google+', array(), 'Modules.Sharebuttons.Shop'),
'class' => 'googleplus',
'url' => 'https://plus.google.com/share?url='.$sharing_url,
);
}
if (Configuration::get('PS_SC_PINTEREST')) {
$social_share_links['pinterest'] = array(
'label' => $this->trans('Pinterest', array(), 'Modules.Sharebuttons.Shop'),
'class' => 'pinterest',
'url' => 'http://www.pinterest.com/pin/create/button/?media='.$sharing_img.'&url='.$sharing_url,
);
}
return array(
'social_share_links' => $social_share_links,
);
}
}
But prestashop still use the orignal file module because i get this error :
'Undefined index: product', '/home/xxxxxxxx/www/modules/ps_sharebuttons/ps_sharebuttons.php',
I've already clear cache
Thanks for help
Ok im stupid, the override view goes to theme > module folder but the class should be in override > module folder

how to change a bool value in prestashop 1.6 back end by icon click

I want to change my printing status ,I am able to place the icon to change the status but the change is not occurring when I click the Print status icon shown in the image I have placed the callback as changePrintStatus
the code is reaching initProcess() when the change status icon is clicked,But after that what exactly must happen ??Or do i need to call any other function/override function ? (I want to do the same as in customers list where we change active status of customers ,similarly I want to do here for my custom module)
<?php
require_once(_PS_MODULE_DIR_.'eticketprinting/eticketprinting.php');
require_once(_PS_MODULE_DIR_.'eticketprinting/classes/Eticket.php');
class EticketController extends ModuleAdminController
{
public $module;
public $html;
public $tabName = 'renderForm';
public function __construct()
{
$this->tab = 'eticket';
$this->module = new eticketprinting();
$this->addRowAction('edit');
//$this->addRowAction('edit');
// $this->addRowAction('view'); // to display the view
//$this->addRowAction('delete');
$this->explicitSelect = false;
$this->context = Context::getContext();
$this->id_lang = $this->context->language->id;
$this->lang = false;
$this->ajax = 1;
$this->path = _MODULE_DIR_.'eticketprinting';
$this->default_form_language = $this->context->language->id;
$this->table = _DB_KITS_PREFIX_.'print_eticket';
$this->className = 'Eticket';
$this->identifier = 'id_print_eticket';
$this->allow_export = true;
$this->_select = '
id_print_eticket,
ticket_id,
ticket_no,
product_id,
print_status,
date_add,
date_upd
';
$this->name = 'EticketController';
$this->bootstrap = true;
$this->initTabModuleList();
$this->initToolbar();
$this->initPageHeaderToolbar();
// $this->initFieldList();
//$this->initContent();
parent::__construct();
$this->fields_list =
array(
'id_print_eticket' => array(
'title' => $this->l('E-Ticket Print ID'),
'width' => 25,
'type' => 'text',
),
'ticket_id' => array(
'title' => $this->l('Ticket- ID'),
'width' => 140,
'type' => 'text',
),
'ticket_no' => array(
'title' => $this->l('Ticket No'),
'width' => 140,
'type' => 'text',
),
'product_id' => array(
'title' => $this->l('Product ID'),
'width' => 100,
'type' => 'text',
),
'print_status' => array(
'title' => $this->l('Print Status'),
'align' => 'center',
'type' => 'bool',
'callback' => 'changePrintStatus',
'orderby' => false,
),
'date_add' => array(
'title' => $this->l('Date Add'),
'width' => 140,
'type' => 'text',
),
'date_upd' => array(
'title' => $this->l('Date Update'),
'width' => 140,
'type' => 'text',
),
);
}
public function changePrintStatus($value, $eticket)
{
return '<a class="list-action-enable '.($value ? 'action-enabled' : 'action-disabled').'" href="index.php?'.htmlspecialchars('tab=Eticket&id_print_eticket='
.(int)$eticket['id_print_eticket'].'&changePrintVal&token='.Tools::getAdminTokenLite('Eticket')).'">
'.($value ? '<i class="icon-check"></i>' : '<i class="icon-remove"></i>').
'</a>';
}
public function initProcess()
{
parent::initProcess();
//d($this->id_object);
if (Tools::isSubmit('changePrintVal') && $this->id_object) {
if ($this->tabAccess['edit'] === '1') {
//d("reached here");
$this->action = 'change_print_val';
} else {
$this->errors[] = Tools::displayError('You do not have permission to change this.');
}
}
}
public function postProcess()
{
//When generate pdf button is clicked
if (Tools::isSubmit('submitAddeticket')) {
if (!Validate::isDate(Tools::getValue('date_from'))) {
$this->errors[] = $this->l('Invalid "From" date');
}
if (!Validate::isDate(Tools::getValue('date_to'))) {
$this->errors[] = $this->l('Invalid "To" date');
}
if (!Validate::isInt(Tools::getValue('id_product')) || Tools::getValue('id_product')=='' ) {
$this->errors[] = $this->l('Invalid Product/select a product ');
}
if (!count($this->errors)) {
if (count(Ticket::getByProductNDateInterval(Tools::getValue('id_product'),Tools::getValue('date_from'), Tools::getValue('date_to')))) {
//d($this->context->link->getAdminLink('AdminPdf'));
Tools::redirectAdmin($this->context->link->getAdminLink('AdminPdf').'&submitAction=generateEticketPDF&id_product='.urlencode(Tools::getValue('id_product')).'&date_from='.urlencode(Tools::getValue('date_from')).'&date_to='.urlencode(Tools::getValue('date_to')));
}
$this->errors[] = $this->l('No tickets has been found or Ticket Generated Already for this period for Product ID:'.Tools::getValue('id_product').' (Change the Print Status generate the E-Ticket Again)');
}
} else {
parent::postProcess();
}
}
}
I was missing the process function :
**But note that $this->action = 'change_print_val';
and name f the process must be similar in my case processChangePrintVal
So if action is $this->action = 'change_printStatus_val'; then process name must be processChangePrintStatusVal**
I added Below function
/**
* Toggle the Eticket Print Status flag- Here the update action occurs
*/
public function processChangePrintVal()
{
$eticket = new Eticket($this->id_object);
if (!Validate::isLoadedObject($eticket)) {
$this->errors[] = Tools::displayError('An error occurred while updating Eticket Print Status information.');
}
$eticket->print_status = $eticket->print_status ? 0 : 1;
if (!$eticket->update()) {
$this->errors[] = Tools::displayError('An error occurred while Eticket Print Status customer information.');
}
Tools::redirectAdmin(self::$currentIndex.'&token='.$this->token);
}

Rename nama in upload ZF2 + AWS S3

How can I rename the name of a file before to upload zf2 and Amazon S3?
This is my code:
$files = $request->getFiles();
$bucketname = 'mybucket';
$result = $aws->putObject(array(
'Bucket' => $bucketname,
'Key' => 'user/5/'.$files['image-file']['name'],
'Body' => EntityBody::factory(fopen($files['image-file']['tmp_name'], 'r')),
'ACL' => CannedAcl::PUBLIC_READ,
'ContentType' => 'image/jpeg'
));
I can not use the module https://github.com/aws/aws-sdk-php-zf2
This is a working example t upload the image in zf2,rename it and save to database
namespace Admin\Form;
use Zend\Form\Form;
class SubcategoryimageForm extends Form
{
public function __construct($name = null)
{
parent::__construct('Subcategoryimage');
$this->setAttribute('method', 'post');
$this->setAttribute('enctype','multipart/form-data');
$this->add(array(
'name' => 'id',
'attributes' => array(
'type' => 'hidden',
),
));
$this->add(array(
'name' => 'subcategory_link_id',
'attributes' => array(
'type' => 'hidden',
),
));
$this->add(array(
'name' => 'alt',
'attributes' => array(
'type' => 'text',
),
'options' => array(
'label' => 'Alt Text',
),
));
$this->add(array(
'name' => 'fileupload',
'attributes' => array(
'type' => 'file',
),
'options' => array(
'label' => 'File Upload',
),
));
$this->add ( array (
'name' => 'detail',
'attributes' => array (
'type' => 'textarea'
),
'options' => array (
'label' => 'Detail'
)
) );
$this->add ( array (
'type' => 'Zend\Form\Element\Checkbox',
'name' => 'active',
'tabindex' => 3,
'options' => array (
'label' => 'Active',
'use_hidden_element' => true,
'checked_value' => '1',
'unchecked_value' => '0'
)
) );
$this->add(array(
'type' => 'Zend\Form\Element\Radio',
'name' => 'location',
'options' => array(
'label' => 'Please choose one of the choices',
'value_options' => array(
'1' => 'flag',
'2' => 'landing',
'3' => 'home page',
),
),
'attributes' => array(
'value' => '1' //set checked to '1'
)
));
$this->add ( array (
'name' => 'submit',
'type' => 'Submit',
'tabindex' => 5,
'size' => 20,
'required' => false,
'attributes' => array (
'value' => 'Upload File',
'id' => 'submitbutton'
)
) );
}
}
In your controller
//inculde the imagine modules
use Zend\Validatior\File\Size;
use Imagine\Gd\Imagine;
use Imagine\Image\Box;
use Imagine\Image\Point;
public function imageAction()
{
$id = ( int ) $this->params ()->fromRoute ( 'id', 0 );
if (! $id) {
return $this->redirect ()->toRoute ( 'category' );
}
$form = new SubcategoryimageForm();
$form->get ( 'subcategory_link_id' )->setAttribute ( 'value', $id );
$request = $this->getRequest();
if ($request->isPost()) {
// Make certain to merge the files info!
$image = new Subcategoryimage();
$form->setInputFilter($image->getInputFilter());
$post = array_merge_recursive(
$request->getPost()->toArray(),
$request->getFiles()->toArray()
);
$form->setData($post);
if ($form->isValid()) {
$size = new \Zend\Validator\File\ImageSize(array(
'minWidth' => 30, 'minHeight' => 30,
'maxWidth' => 1024, 'maxHeight' => 920,
)); //minimum bytes filesize
$isImage = new \Zend\Validator\File\IsImage();
$mimeType = new \Zend\Validator\File\MimeType(array('image/gif', 'image/jpg','image/jpeg','image/png','enableHeaderCheck' => true));
$adapter = new \Zend\File\Transfer\Adapter\Http();
$adapter->setValidators(array($size), $post['fileupload']['name']);
$adapter->setValidators(array($isImage), $post['fileupload']['name']);
$adapter->setValidators(array($mimeType), $post['fileupload']['name']);
if (!$adapter->isValid()){
$dataError = $adapter->getMessages();
$error = array();
foreach($dataError as $key=>$row)
{
$error[] = $row;
}
$form->setMessages(array('fileupload'=>$error ));
$messages = $form->getMessages();
return $this->redirect ()->toRoute ( 'category' );
// print_r($messages);die('file errors');
} else {
//$adapter->setDestination(dirname(__DIR__).'imageurltosaveimage/');
$adapter->setDestination('imagepathtosave');
if ($adapter->receive($post['fileupload']['name'])) {
$image->exchangeArray($form->getData());
switch(strtolower($_FILES['fileupload']['type']))
{
case 'image/jpeg':
$filename = imagecreatefromjpeg('imagepath/'.$post['fileupload']['name']);
break;
case 'image/png':
$filename = imagecreatefrompng('imagepath/'.$post['fileupload']['name']);
break;
case 'image/gif':
$filename = imagecreatefromgif('imagepath/'.$post['fileupload']['name']);
break;
default:
exit('Unsupported type: '.$_FILES['fileupload']['type']);
}
ob_start();
imagejpeg($filename);
// large image
$large = base64_encode(ob_get_contents()); // returns output
$mainimgWidth = imagesx($filename);
$mainimgHeight = imagesy($filename);
$thumbWidth = intval($mainimgWidth / 4);
$thumbHeight = intval($mainimgHeight / 4);
$new = imagecreatetruecolor($thumbWidth, $thumbHeight);
$backgroundColor = imagecolorallocate($new, 255, 255, 255);
imagefill($new, 0, 0, $backgroundColor);
imagecopyresampled($new, $filename, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $mainimgWidth, $mainimgHeight);
/** Catch the imagedata */
ob_start();
imagejpeg($new);
$data = ob_get_clean();
// Destroy resources
imagedestroy($filename);
imagedestroy($new);
// Set new content-type and status code
$thumb = base64_encode($data);
// imagine library was intsalled by the composer in the test server by amarjit
ob_end_clean();
$imagine = new Imagine();
//rename files
$filedata = array(
'id' => $post ['id'],
'subcategory_link_id' => $post ['subcategory_link_id'],
'alt' => $post ['alt'],
'detail' => $post ['detail'],
'active' => $post ['active'],
'location' => $post ['location'],
'thumb' => $thumb,
'large' => $large,
'created' => date('Y-m-d H:i:s'),
'createdby' => 1,
);
$id = $this->getImageTable ()->save ( $filedata );
$imagine->open('ipathofimage/'.$post['fileupload']['name'])
->save('pathtosaveimages/newnameofimage-'.$id.'.jpg');
/**
* delete the origional uploaded file;
*/
unlink('pathtoimage/'.$post['fileupload']['name']);
return $this->redirect ()->toRoute ( 'category' );
}
}
}else{
$messages = $form->getMessages();
}
}
return array (
'id' => $id,
'form' => $form,
'entities' => $this->getImageTable ()->getImageContents($id),
);
}
To get the image from database
use below code in your action
public function getlandingimageAction()
{
$id = ( int ) $this->params ()->fromRoute ( 'id', 0 );
if (! $id) {
return $this->redirect ()->toRoute ( 'category' );
}
try {
$thumb = $this->getImageTable ()->getImage ( $id );
} catch ( \Exception $ex ) {
return $this->redirect ()->toRoute ( 'category', array (
'action' => 'index'
) );
}
$image = base64_decode($thumb);
/** check if the image is db */
if($image!=null)
{
$db_img = imagecreatefromstring($image);
Header("Content-type: image/jpeg");
imagejpeg($db_img);
}
else
{
/** check if the image is upload dir */
$url= "path/imagename".$id.'.jpg';
if(file_exists($url))
{
$db_img = imagecreatefromjpeg($url);
Header("Content-type: image/jpeg");
imagejpeg($db_img);
exit;
}
/** handle if the image does not exit */
/**
* This needs to be changed from t
*/
$imgurl= "paaathofimage/";
Header("Content-type: image/gif");
$i=imagecreatefromgif($imgurl."/images/noimg.gif");
imagegif($i);
}
exit;
}