Prestashop helper form 'file' type - forms

I m working on prestasshop and I created a helper form inside a controller (for back office). My question is how to upload a document by using the type:'file' from the helper form. Here is the code:
public function __construct()
{
$this->context = Context::getContext();
$this->table = 'games';
$this->className = 'Games';
$this->lang = true;
$this->addRowAction('edit');
$this->addRowAction('delete');
$this->bulk_actions = array('delete' => array('text' => $this->l('Delete selected'),
'confirm' => $this->l('Delete selected items?')));
$this->multishop_context = Shop::CONTEXT_ALL;
$this->fieldImageSettings = array(
'name' => 'image',
'dir' => 'games'
);
$this->fields_list = array(
'id_game' => array(
'title' => $this->l('ID'),
'width' => 25
)
);
$this->identifier = 'id_game';
parent::__construct();
}
public function renderForm()
{
if (!($obj = $this->loadObject(true)))
return;
$games_list = Activity::getGamesList();
$this->fields_form = array(
'tinymce' => true,
'legend' => array(
'title' => $this->l('Game'),
'image' => '../img/admin/tab-payment.gif'
),
'input' => array(
array(
'type' => 'select',
'label' => $this->l('Game:'),
'desc' => $this->l('Choose a Game'),
'name' => 'id_games',
'required' => true,
'options' => array(
'query' => $games_list,
'id' => 'id_game',
'name' => 'name'
)
),
array(
'type' => 'text',
'label' => $this->l('Game Title:'),
'name' => 'name',
'size' => 64,
'required' => true,
'lang' => true,
'hint' => $this->l('Invalid characters:').' <>;=#{}'
),
array(
'type' => 'file',
'label' => $this->l('Photo:'),
'name' => 'uploadedfile',
'id' => 'uploadedfile',
'display_image' => false,
'required' => false,
'desc' => $this->l('Upload your document')
)
)
);
$this->fields_form['submit'] = array(
'title' => $this->l(' Save '),
'class' => 'button'
);
return AdminController::renderForm();
}
Now how can I upload the document?
Do I have to create a column in the table of the db (games table) for storing the file or something related?
Thanks in advance

I assume this AdminController for your model. Now a model obviously can't hold a file in table column. What you can do is hold path to the uploaded file. That's what you can save.
You should look in AdminController class (which you extended). When you submit a form, one of two method are executed:
processAdd()
processUpdate()
Now investigate the flow logic in these methods. Other methods are called from within this methods, such as:
$this->beforeAdd($this->object); -> calls $this->_childValidation();
$this->validateRules();
$this->afterUpdate($object);
As you can see, there these are the methods where you can do you custom stuff. If you look up these functions in AdminController class, the're empty. They are purposely added so people can override them and put their custom logic there.
So, using these functions, you can validate your uploaded file fields (even though it isnt in the model itself), if it validates you can then assign path to the object; and then in beforeAdd method you can actually move the uploaded file to the desired location (because both child validation and default validation has passed).
The way I've done it:
protected function _childValidation()
{
// Check upload errors, file type, writing permissions
// Use $this->errors['file'] if there is an error;
protected function beforeAdd($object)
{
// create filename and filepath
// assign these fields to object;
protected function afterAdd($object)
{
// move the file
If you allow the file field to be updated, you'll need to to these steps for Update methods as well.

you can get uploaded file using $_FILES['uploadedfile'] in both the functions processAdd() and processUpdate(), you can check all the conditions there and before calling $this->object->save(); to save the form data you can write the code to upload the file in the desired location like
move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)
since you can't save the file in database you need to save only the name of the file or location on the database
Hope that helps

Related

Prestashop fields_options in AdminMaintenanceController

In my override file AdminMaintenanceController, I try to add an input file to add an image(dynamically) on maintenance.tpl when the maintenance mode in active. The field form appear correctly in my backoffice below maintenance ip and switch but nothing is uploaded.
Do you have tips or informations about this issue ?
I'm on 1.6
My controller:
class AdminMaintenanceController extends AdminMaintenanceControllerCore
{
public function __construct()
{
$this->bootstrap = true;
$this->className = 'Configuration';
$this->table = 'configuration';
parent::__construct();
$this->fields_options = array(
'general' => array(
'title' => $this->l('General'),
'fields' => array(
'PS_SHOP_ENABLE' => array(
'title' => $this->l('Enable Shop'),
'desc' => $this->l('Activate or deactivate your shop (It is a good idea to deactivate your shop while you perform maintenance. Please note that the webservice will not be disabled).'),
'validation' => 'isBool',
'cast' => 'intval',
'type' => 'bool'
),
'PS_MAINTENANCE_IP' => array(
'title' => $this->l('Maintenance IP'),
'hint' => $this->l('IP addresses allowed to access the front office even if the shop is disabled. Please use a comma to separate them (e.g. 42.24.4.2,127.0.0.1,99.98.97.96)'),
'validation' => 'isGenericName',
'type' => 'maintenance_ip',
'default' => ''
),
),
'submit' => array('title' => $this->l('Save'))
),
'image' => array(
'title' => $this->l('Images parameters'),
'fields' => array(
'PS_IMG1' => array(
'title' => $this->l('Left side image'),
'type' => 'file',
'name' => 'PS_IMG1',
'thumb' => _PS_IMG_.'PS_IMG1.jpg',
'hint' => $this->l('Choose the photo for this side'),
),
),
'submit' => array('title' => $this->l('Save'))
),
It seems that you have implemented only a form fields display but not file(image) upload process. You need to instantiate a process of an image uploading after form confirmation

Zend framework 2 form element normalization

I am migrating an application from Zend 1 to Zend 2 and starting to desperate with one issue. The application works with different locales and therefore, I need to store the data in a normalized way in the database. In Zend 1 I used this code:
public function normalizeNumber( $value )
{
// get the locale to change the date format
$this->_locale = Zend_Registry::get('Zend_Locale' );
return Zend_Locale_Format::getNumber($value, array('precision' => 2, 'locale' => $this->_locale));
}
Unfortunately Zend 2 does not has this Zend_Locale_Format::getNumber any more and I was not able to figure out what function did replace it. I have tried with NumberFormat, but I get only localized data not normalized. I need this function to normalize data I receive from a form via POST. Can someone give some advice?
thanks
Just to complete my question. The Form element definition I am using is the following:
namespace Profile\Form;
use Zend\Form\Form;
use Zend\InputFilter\InputFilterProviderInterface;
class Profile Extends Form implements InputFilterProviderInterface
{
protected $model;
public function __construct( $model, $name = 'assignmentprofile')
{
parent::__construct( $name );
$this->setAttribute( 'method', 'post');
$this->model = $model;
...
$this->add( array(
'name' =>'CommutingRate',
'type' =>'Zend\Form\Element\Text',
'options' => array( // list of options to add to the element
'label' => 'Commuting rate to be charged:',
'pattern' => '/[0-9.,]/',
),
'attributes' => array( // Attributes to be passed to the HTML lement
'type' =>'text',
'required' => 'required',
'placeholder' => '',
),
));
}
public function getInputFilterSpecification()
{
return array(
...
'CommutingRate' => array(
'required' => true,
'filters' => array(
array( 'name' => 'StripTags', ),
array( 'name' => 'StringTrim'),
array( 'name' => 'NumberFormat', 'options' => array('locale' => 'en_US', 'style' => 'NumberFormatter::DECIMAL', 'type' => 'NumberFormatter::TYPE_DOUBLE',
))
),
'validators' => array(
array( 'name' => 'Float',
'options' => array( 'messages' => array('notFloat' => 'A valid numeric entry is required')),
),
),),
...
);
}
}
As mentioned before, I am able to localized the data and validate it in the localized manner, but i am failing to convert it back to a normalized manner...

CodeIgniter autoloading form validation rules set not working with parameters

Following CI user_guide, I have created a configuration file named "form_validation.php" with in it the following sets:
$config = array(
'user/create' => array(
array(
'field' => 'id',
'label' => '',
'rules' => ''
),
array(
'field' => 'first_name',
'label' => 'lang:First name',
'rules' => 'required|max_length[30]'
),...
),
'user/update' => array(
array(
'field' => 'id',
'label' => '',
'rules' => ''
),
array(
'field' => 'first_name',
'label' => 'lang:First name',
'rules' => 'required|max_length[30]'
),...
)
);
In my 'user' controller, when I call the 'create' method, hence with the URL http://localhost/my_ci_application/user/create, the statement $this->form_validation->run() automatically runs the first set of rules defined in my configuration file. This is the expected behaviour from what I read in the user guide.
But when I run the following URL http://localhost/my_ci_application/user/update/1 to update the user whose ID is 1, it does not automatically load the 'user/update' rules set. It seems like because of the parameter, CI expects to find a 'user/update/1' rules set, which of course I cannot create because the ID of my users will vary all the time when calling this method.
Am I understanding this right? If yes, then that's a pity as I thought standard CI URL were formed like: controller/method/parameters... so I would expect the form validation class to only consider the first two URI segments?!
FYI, if I write in my user.update method the following, my validation rules work fine:
$this->form_validation->run('user/update')
So my question is really if I understood the autoloading of rules properly or not, and if there is anything we can do to autoload those rules even with methods having some parameters.
thank you very much in advance.
In your form_validation.php file:
$CI =& get_instance();
$config = array(
'user/update/' . $CI->uri->segment(3) => array(
....
)
);
if i understant this question u will need call validation, for example:
$this->lang->load('form_validation', 'portuguese'); //if u have order language
if($this->form_validation->run('user/update') == FALSE)
{
//msg error
}
else{
//save
}
To get the value for the url dowel u need:
$this->uri->segment(3);
i hope this has helped
You can extend the library to achieve this
application/libraries/MY_Form_validation.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Form_validation extends CI_Form_validation {
function run($group = '')
{
if($group == '')
{
$group = '/' . implode('/', array_slice($this->CI->uri->rsegment_array(), 0, 2));
}
return parent::run($group);
}
}

how to set value from database in Zend Framework 1 in add form element

I have a form in Zend Framework 1. when I click on edit button I want to display values from databases in the form. but I don't know how to do it.
This is my form code:
// Add an email element
$this->addElement('text', 'orgname', array(
'required' => true,
'filters' => array('StringTrim'),
'style' => array('width:220px'),
'decorators'=>Array(
'ViewHelper','Errors'
)
));
This is my controller:
public function editclientcompanyAction()
$form = new Application_Form_Companyform();
$form->addform();
$this->view->form = $form;
$request = $this->getRequest();
$editid=$request->getParam('id');
$edit_show = new Application_Model_Clientcompany;
$showdetails = $edit_show->editclient($editid);
$this->view->assign('datas', $showdetails);
How do I display database vlaues in my Zend Form?
There are two cases.
1) Populating form which has fields same like the database table fields : If you have the form which has same fields like the database fields, then you can populate them easily.
First you need to get the data from the database and then call the Zend_Form populate function passing the data as an associative array, where keys will be same like form fields names and values will be values for the form fields, as below in case of your form.
This will be in your controller
$data = array("orgname" => "Value for the field");
$form = new Application_Form_Companyform();
$form->populate($data);
Now send will automatically populate the form field orgname. You dont need to modify your form or set the value field in the addElement.
*2)Setting field value manually: * The second case is to set the value manually. First you will need to modify your form and add a constructor to it. Also in your form class you will need to create a property (if you have multiple fields, then you can create an array property or multiple properties for each field. This will be all up to you.). And then set the value key in the addElement. Your form should look like this
class Application_Form_Companyform extends Zend_Form
{
private $orgname;
public function __contruct($orgname)
{
$this->orgname = $orgname;
//It is required to call the parent contructor, else the form will not work
parent::__contruct();
}
public function init()
{
$this->addElement('text', 'orgname',
array(
'required' => true,
'filters' => array('StringTrim'),
'style' => array('width:220px'),
'decorators'=>Array('ViewHelper','Errors'),
'value'=>$this->orgname
)
));
} //end of init
} //end of form
Now your controller, you will need to instantiate the form object passing the value of the orgname field like below
$form = new Application_Form_Companyform("This is the value for orgname");
And thats it.
I used such methods and it works like a charm. For your requirements, you may need to adjust the above sample code, as i did not checked it, but it will run fine for sure i hope :P
Thank you
Ok in either ZF1 or ZF2 just do this.
// Add an email element
$this->addElement('text', 'orgname',
array(
'required' => true,
'filters' => array('StringTrim'),
'style' => array('width:220px'),
'decorators' => Array('ViewHelper','Errors'),
'value' => $showdetails->orgname
)
));
You might want to test first for null/empty values first though, you could use ternary operators for convenience:
// Add an email element
$this->addElement('text', 'orgname',
array(
'required' => true,
'filters' => array('StringTrim'),
'style' => array('width:220px'),
'decorators' => Array('ViewHelper','Errors'),
'value' => empty($showdetails->orgname)? null : $showdetails->orgname
)
));
Please have a look in my edit function at /var/www/html/zend1app/application/controllers/CountryController.php :
public function editAction() {
$data = $this->getRequest()->getParams();
$id = (int)$data['id'];
$options = array();
$country = $this->getCountryModel()->fetchRow("id=$id");
if(!$country)
{
throw new Exception("Invalid Request Id!");
}
$form = new Application_Form_Country();
$form->addIdElement();
if ($this->getRequest()->isPost()) {
if ($form->isValid($this->getRequest()->getPost())){
$data = new Application_Model_Country();
if($data->save($form->getValues()))
{
$message = array("sucess" => "Country has been updated!");
}
else {
$message = array("danger" => "Country could not be updated!");
}
$this->_helper->FlashMessenger->addMessage($message);
return $this->_helper->redirector('index');
}
}
$options = array (
'id' => $country->id,
'name' => $country->name,
'code' => $country->code
);
$form->populate( $options ); // data binding in the edit form
$this->view->form = $form;
}
and form class at /var/www/html/zend1app/application/forms/Country.php :
class Application_Form_Country extends Zend_Form
{
public function init()
{
// Set the method for the display form to POST
$this->setMethod('post');
// Add an email element
$this->addElement('text', 'name', array(
'label' => 'Enter Country Name:',
'required' => true,
'filters' => array('StringTrim'),
'validators' => array(
array('validator' => 'StringLength', 'options' => array(0, 20))
)
));
// Add the comment element
$this->addElement('text', 'code', array(
'label' => 'Enter Country Code:',
'required' => true,
'validators' => array(
array('validator' => 'StringLength', 'options' => array(0, 20))
)
));
// Add the submit button
$this->addElement('submit', 'submit', array(
'ignore' => true,
'label' => 'Save',
));
// And finally add some CSRF protection
$this->addElement('hash', 'csrf', array(
'ignore' => true,
));
}
public function addIdElement()
{
$this->addElement('hidden', 'id');
}
}
HTH

Module Forms - Store Value of addField to a Variable

I have something like in my custom module:
$fieldset->addField('orderinfo', 'link', array(
'label' => Mage::helper('web')->__('Order Info'),
'style' => "",
'href' => Mage::helper('adminhtml')->getUrl('adminhtml/sales_order/view', array('order_id' => $order_id)),
'value' => 'Magento Blog',
'after_element_html' => '',
));
And as you can see from the code, I am trying to link that field to the Order Tab in the back-end. I'm having trouble getting the ID though. I'm planning to just save the Order ID in the database, and then using the addField I could have the correct url.
But how can I save an addField value to a variable?
I want to store the value in "$order_id".
Is it possible?
I am not sure in which context you are using this fieldset but if it is used for example for creating or editing object you can try something like that:
In controller:
public function editAction()
{
$id = $this->getRequest()->getParam('id');
$model = Mage::getModel('module/model')->load($id);
Mage::register('model_name', $model);
}
and then in the block:
protected function _prepareForm()
{
$model = Mage::registry('model_name');
// add fieldset to form
$fieldset->addField('orderinfo', 'link', array(
'label' => Mage::helper('web')->__('Order Info'),
'style' => "",
'href' => Mage::helper('adminhtml')->getUrl('adminhtml/sales_order/view', array('order_id' => $model->getOrderId())),
'value' => 'Magento Blog',
'after_element_html' => '',
));
//rest of the elements
}
Answering my own post again. (src: https://magento.stackexchange.com/questions/682/module-forms-store-value-of-addfield-to-a-variable)