I am attempting to create a custom image field within Magento CMS pages.
This is the steps I have taken,
Created an additional column with cms_page within the database called 'banner' - this is a varchar (255).
Amended "app/code/core/Mage/Adminhtml/controllers/Cms/PageController.php" with the uploader code (see at bottom).
Amended "app/code/core/Mage/Adminhtml/Block/Cms/Page/Edit/Tab/Content.php" to add the new field called 'banner' of which is a field type of 'image'.
Deleted everything within "var/cache/" and "var/session/"
It's just simply not uploading/saving the filename within the database. To try and diagnose what's going on I added print_r($_FILES) just below saveAction() and it returned an empty array.
Am I missing a crucial step?
Here is the relevant code,
app/code/core/Mage/Adminhtml/controllers/Cms/PageController.php -
public function saveAction()
{
if ($data = $this->getRequest()->getPost()) {
$data = $this->_filterPostData($data);
//init model and set data
$model = Mage::getModel('cms/page');
if(isset($data['banner']['delete']) && $data['banner']['delete']=='1'){
if(!empty($data['banner']['value'])){
$path = Mage::getBaseDir('media') . DS;
if(#unlink($path.$data['banner']['value'])){
$data['banner']='';
}
}
}
if(isset($_FILES['banner']['name']) && !empty($_FILES['banner']['name'])) {
try {
$uploader = new Varien_File_Uploader('banner');
$uploader->setAllowedExtensions(array('jpg','jpeg','gif','png')); // or pdf or anything
$uploader->setAllowRenameFiles(true);
// setAllowRenameFiles(true) -> move your file in a folder the magento way
// setAllowRenameFiles(false) -> move your file directly in the $path folder
$uploader->setFilesDispersion(true);
$path = Mage::getBaseDir('media') . DS;
//$uploader->saveresized($path, $_FILES['nfile']['name'],100,72);
//$_tmp_nfilethumb = $uploader->getUploadedFileName();
$uploader->save($path, $_FILES['banner']['name']);
$_tmp_nfile = $uploader->getUploadedFileName();
//$data['nfilethumb'] = $_tmp_nfilethumb;
$data['banner'] = $_tmp_nfile;
}catch(Exception $e) {
}
}elseif(isset($data['banner']['value']) && !empty($data['banner']['value'])){
$data['banner']=$data['banner']['value'];
}
if ($id = $this->getRequest()->getParam('page_id')) {
$model->load($id);
}
$model->setData($data);
Mage::dispatchEvent('cms_page_prepare_save', array('page' => $model, 'request' => $this->getRequest()));
//validating
if (!$this->_validatePostData($data)) {
$this->_redirect('*/*/edit', array('page_id' => $model->getId(), '_current' => true));
return;
}
// try to save it
try {
// save the data
$model->save();
// display success message
Mage::getSingleton('adminhtml/session')->addSuccess(
Mage::helper('cms')->__('The page has been saved.'));
// clear previously saved data from session
Mage::getSingleton('adminhtml/session')->setFormData(false);
// check if 'Save and Continue'
if ($this->getRequest()->getParam('back')) {
$this->_redirect('*/*/edit', array('page_id' => $model->getId(), '_current'=>true));
return;
}
// go to grid
$this->_redirect('*/*/');
return;
} catch (Mage_Core_Exception $e) {
$this->_getSession()->addError($e->getMessage());
}
catch (Exception $e) {
$this->_getSession()->addException($e,
Mage::helper('cms')->__('An error occurred while saving the page.'));
}
$this->_getSession()->setFormData($data);
$this->_redirect('*/*/edit', array('page_id' => $this->getRequest()->getParam('page_id')));
return;
}
$this->_redirect('*/*/');
}
app/code/core/Mage/Adminhtml/Block/Cms/Page/Edit/Tab/Content.php -
protected function _prepareForm()
{
$model = Mage::registry('cms_page');
/*
* Checking if user have permissions to save information
*/
if ($this->_isAllowedAction('save')) {
$isElementDisabled = false;
} else {
$isElementDisabled = true;
}
$form = new Varien_Data_Form();
$form->setHtmlIdPrefix('page_');
$fieldset = $form->addFieldset('content_fieldset', array('legend'=>Mage::helper('cms')->__('Content'),'class'=>'fieldset-wide'));
$wysiwygConfig = Mage::getSingleton('cms/wysiwyg_config')->getConfig(
array('tab_id' => $this->getTabId())
);
$fieldset->addField('content_heading', 'text', array(
'name' => 'content_heading',
'label' => Mage::helper('cms')->__('Content Heading'),
'title' => Mage::helper('cms')->__('Content Heading'),
'disabled' => false,
));
$content999Field = $fieldset->addField('banner', 'image', array(
'name' => 'banner',
'label' => Mage::helper('cms')->__('Banner'),
'title' => Mage::helper('cms')->__('Banner'),
));
$contentField = $fieldset->addField('content', 'editor', array(
'name' => 'content',
'label' => Mage::helper('cms')->__('Layout 1'),
'title' => Mage::helper('cms')->__('Layout 1'),
'style' => 'height:36em;',
//'required' => true,
'disabled' => $isElementDisabled,
'config' => $wysiwygConfig
));
$content2Field = $fieldset->addField('content2', 'editor', array(
'name' => 'content2',
'label' => Mage::helper('cms')->__('Layout 2'),
'title' => Mage::helper('cms')->__('Layout 2'),
'style' => 'height:36em;',
//'required' => true,
'disabled' => $isElementDisabled,
'config' => $wysiwygConfig
));
$content3Field = $fieldset->addField('content3', 'editor', array(
'name' => 'content3',
'label' => Mage::helper('cms')->__('Content'),
'title' => Mage::helper('cms')->__('Content'),
'style' => 'height:36em;',
//'required' => true,
'disabled' => $isElementDisabled,
'config' => $wysiwygConfig
));
// Setting custom renderer for content field to remove label column
//$renderer = $this->getLayout()->createBlock('adminhtml/widget_form_renderer_fieldset_element')
// ->setTemplate('cms/page/edit/form/renderer/content.phtml');
// $contentField->setRenderer($renderer);
$form->setValues($model->getData());
$this->setForm($form);
Mage::dispatchEvent('adminhtml_cms_page_edit_tab_content_prepare_form', array('form' => $form));
return parent::_prepareForm();
}
Try to add this line below $form->setValues($model->getData());:
$form->setEnctype(Zend_Form::ENCTYPE_MULTIPART);
I added,
'enctype' => 'multipart/form-data' within the Form.php and it fixed it.
class Mage_Adminhtml_Block_Cms_Page_Edit_Form extends Mage_Adminhtml_Block_Widget_Form
{
protected function _prepareForm()
{
$form = new Varien_Data_Form(array('id' => 'edit_form', 'action' => $this->getData('action'), 'method' => 'post', 'enctype' => 'multipart/form-data'));
$form->setUseContainer(true);
$this->setForm($form);
return parent::_prepareForm();
}
}
Related
Now I'm a bit more into this ZF3 stuff. I could (with some help) implement nearly everything I wanted. To dive in the, for me new version, I developed a test project.
Some questions are still unanswered and I didn't find usable explanations.
My new issue is InputFilterAwareInterface. I tried the examples for strings from the tutorial, so far everything ok. But like always for the easy topics you find everything, if you go further it ends abruptly.
I need an Inputfilter for xls and xlsx files. I googled of course, read tutorials, searched in the zend tutorial, because I had the idea there must somewhere exist some complete reference, but I couldn't find any.
So I tried this one:
$inputFilter->add([
'type' => 'Zend\InputFilter\FileInput',
'name' => 'DCL_Path',
'required' => true,
'validators' => [
['name' => 'FileUploadFile'],
[
'name' => 'FileMimeType',
'options' => [
'mimeType' => ['text/xls', 'text/xlsx']
]
],
[
'name' => 'Filesize',
'options' => [
'max' => 4096
]
],
],
// 'filters' => [
// [
// 'name' => 'FileRenameUpload',
// 'options' => [
// 'target'=>'./data/upload',
// 'useUploadName'=>true,
// 'useUploadExtension'=>true,
// 'overwrite'=>true,
// 'randomize'=>false
// ]
// ]
// ],
]);
As you an see I'm still fighting the validator part. What would be the right syntax to validate xls and xlsx files with a maximum size of let's say 4 MB?
And after that, what about the filterarea, I did the following in my controller action just because I'm used to
if ($form->isValid()) {
$data = $form->getData();
// Upload path
$location = "public/files/";
// A bit validation of uploaded file
$allowedExtension = array('xls', 'xlsx');
$extension = explode('.', $data['DCL_Path']['name']);
$extension = end($extension);
//$import['DCL_Path']=$data['DCL_Path']['name'];
//$fileName = time() . '.' . $extension;
$fileName = $data['DCL_Path']['name'];
// Check if everything is OK!
//echo $fileName;
if (0 === $data['DCL_Path']['error'] && in_array($extension, $allowedExtension)) {
move_uploaded_file($data['DCL_Path']['tmp_name'], $location . $fileName);
} else {
echo 'Something went wrong!';
}
Is the move_uploaded_file($data['DCL_Path']['tmp_name'], $location . $fileName); obsolet with the filterstuff in the interface? And again how would be the syntax in this case?
And one of my biggest wish, does somebody know kind of a tutorial which explains plainly the different possibilities and keys of both options (validator and filter)? Sometimes I can't believe that you need so much time to find only the right keys.
EDIT 1: Show Form, filterstuff and changed controller
here is part my Form class:
<?php
namespace Import\Form;
use Zend\Form\Form;
class ImportForm extends Form
{
public function __construct($name = null)
{
// We will ignore the name provided to the constructor
parent::__construct('import');
$this->add([
'name' => 'DCLID',
'type' => 'hidden',
]);
$this->add([
'name' => 'UnitID',
'type' => 'text',
'options' => [
'label' => 'equipment',
],
]);
$this->add([
'name' => 'DCL_Path',
'type' => 'File',
//'required' => true,
'options' => [
'label' => 'path to file',
],
// 'name' => 'FileRenameUpload',
// 'filters' => [
// 'target'=>'./public/files',
// 'useUploadName'=>true,
// 'useUploadExtension'=>true,
// 'overwrite'=>true,
// 'randomize'=>false
// ],
// 'validators' => [ // Validators.
// // Put validator info here.
// ]
]);
here part of the class extended InputFilterAwareInterface
<?php
namespace Import\Model;
use DomainException;
use Zend\Filter\StringTrim;
use Zend\Filter\StripTags;
use Zend\Filter\ToInt;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;
use Zend\Validator\StringLength;
class Import implements InputFilterAwareInterface
{
public $DCLID;
public $DCL_Path;
public $Unitname;
public $UnitID;
public $Importdate;
public $Importuser;
public $Importok;
public $DCL_Type;
public $Changed_per_User;
public $Description_Changes;
private $inputFilter;
public function exchangeArray(array $data)
{
$this->DCLID= !empty($data['DCLID']) ? $data['DCLID'] : null;
$this->UnitID= !empty($data['UnitID']) ? $data['UnitID'] : null;
$this->DCL_Path= !empty($data['DCL_Path']) ? $data['DCL_Path'] : null;
$this->Importdate= !empty($data['Importdate']) ? $data['Importdate'] : null;
$this->Importuser= !empty($data['Importuser']) ? $data['Importuser'] : null;
$this->Importok= !empty($data['Importok']) ? $data['Importok'] : null;
$this->DCL_Type= !empty($data['DCL_Type']) ? $data['DCL_Type'] : null;
$this->Changed_per_User= !empty($data['Changed_per_User']) ? $data['Changed_per_User'] : null;
$this->Description_Changes= !empty($data['Description_Changes']) ? $data['Description_Changes'] : null;
}
public function getArrayCopy()
{
// echo var_dump(get_object_vars($this)
// );
return get_object_vars($this);
}
public function setInputFilter(InputFilterInterface $inputFilter)
{
throw new DomainException(sprintf(
'%s does not allow injection of an alternate input filter',
__CLASS__
));
}
public function getInputFilter()
{
if ($this->inputFilter) {
return $this->inputFilter;
}
$inputFilter = new InputFilter();
// $inputFilter->add([
// 'name' => 'DCLID',
// 'required' => false,
// 'filters' => [
// ['name' => ToInt::class],
// ],
// ]);
// Validator für das Upload Element
$inputFilter->add([
'type' => 'Zend\InputFilter\FileInput',
'name' => 'DCL_Path', // Element's name.
'required' => true, // Whether the field is required.
'filters' => [ // Filters.
[
'name' => \Zend\Filter\File\RenameUpload::class,
'options' => [
'use_upload_extension' => true,
'randomize' => false,
'overwrite' => true,
'target' => 'public/files',
],
],
],
'validators' => [ // Validators.
[
'name' => \Zend\Validator\File\Extension::class,
'options' => [
'extension' => 'xls, xlsx',
'message' => 'File extension not match',
],
],
[
'name' => \Zend\Validator\File\MimeType::class,
'options' => [
'mimeType' => 'text/xls', 'text/xlsx',
'message' => 'File type not match',
],
],
[
'name' => \Zend\Validator\File\Size::class,
'options' => [
'min' => '1kB', // minimum of 1kB
'max' => '4MB',
'message' => 'File too large',
],
],
]
]);
and my part of my controlleraction, I think inhere might be the problem, something is probably not logic:
$form = new ImportForm();
$form->get('submit')->setValue('Add'); //Änderung des LAbels des Submit Buttons, um das Form wiederverwenden zu können
//echo "hier";
$request = $this->getRequest();
if (! $request->isPost()) { //wurden Daten über POST geschickt?
return ['form' => $form]; //Keine Daten, nur Form anzeigen, nicht verarbeiten
}
else {
//Es wurden Daten gesendet
//echo "Daten";
$import = new Import(); //Neue Instanz von Import
$form->setInputFilter($import->getInputFilter()); //Filter an Form binden
$form->setData($request->getPost()); //Daten abholen
//echo $form->isValid();
if (! $form->isValid()) {
return ['form' => $form]; //Wenn die Daten nicht valide sind
}
else{ //aus Tableadapter
$import->exchangeArray($form->getData());
$data = array_merge_recursive(
$this->getRequest()->getPost()->toArray(),
$this->getRequest()->getFiles()->toArray()
);
$form->setData($data);
if ($form->isValid()) {
$data = $form->getData();
// Upload path
// $location = "public/files/";
// $allowedExtension = array('xls', 'xlsx');
// $extension = explode('.', $data['DCL_Path']['name']);
// $extension = end($extension);
$fileName = $data['DCL_Path']['name'];
// // Check if everything is OK!
// //echo $fileName;
// if (0 === $data['DCL_Path']['error'] && in_array($extension, $allowedExtension)) {
// move_uploaded_file($data['DCL_Path']['tmp_name'], $location . $fileName);
// } else {
// echo 'Something went wrong!';
// }
//-----------------------------------------------------------------
// t_dcl befüllen
//-----------------------------------------------------------------
//$namen = explode(",", $import ); //Konvertierung des Strings in ein Array
//echo "<pre>"; var_dump($namen); echo "</pre>"; //Formartierte Ausgabe des Arrays
$this->table->saveImport($import);
EDIT2: Post part of controlleraction to discuss order of some statements:
controlleraction
$form = new ImportForm();
$form->get('submit')->setValue('Add');
$request = $this->getRequest();
if (! $request->isPost()) {
return ['form' => $form];
}
else {
$import = new Import(); //Neue Instanz von Import
$form->setInputFilter($import->getInputFilter());
$form->setData($request->getPost());
$data = array_merge_recursive(
$this->getRequest()->getPost()->toArray(),
$this->getRequest()->getFiles()->toArray()
);
$form->setData($data);
if (! $form->isValid()) {
return ['form' => $form];
}
else{
$import->exchangeArray($form->getData());
$data = $form->getData();
$fileName = $data['DCL_Path']['name'];
Is the position of $form->setInputFilter($import->getInputFilter()); correct? Or when do I have to bind the Inputfilter to form?
There is a small issue left: I now have a message:
File type not match
I tried to upload a .xlsx file
Please try this for InputFilter
$inputFilter->add([
'type' => 'Zend\InputFilter\FileInput',
'name' => 'DCL_Path', // Element's name.
'required' => true, // Whether the field is required.
'filters' => [ // Filters.
[
'name' => \Zend\Filter\File\RenameUpload::class,
'options' => [
'use_upload_extension' => true,
'randomize' => false,
'overwrite' => true,
'target' => 'public/files',
],
],
],
'validators' => [ // Validators.
[
'name' => \Zend\Validator\File\Extension::class,
'options' => [
'extension' => 'xls, xlsx',
'message' => 'File extension not match',
],
],
[
'name' => \Zend\Validator\File\MimeType::class,
'options' => [
'mimeType' => 'text/xls', 'text/xlsx',
'message' => 'File type not match',
],
],
[
'name' => \Zend\Validator\File\Size::class,
'options' => [
'max' => '4MB',
'message' => 'File too large',
],
],
]
]);
And here for controller
if($this->getRequest()->isPost()) {
// merge post and files
$request = $this->getRequest();
$data = array_merge_recursive(
$request->getPost()->toArray(),
$request->getFiles()->toArray()
);
// passing data
$form->setData($data);
// execute validator
if($form->isValid()) {
// execute file filters.
$data = $form->getData();
}
}
By using \Zend\Validator\File\Extension, \Zend\Validator\File\MimeType and \Zend\Validator\File\FileSize you don't need to check manually in your contoller using this code.
if (0 === $data['DCL_Path']['error'] && in_array($extension, $allowedExtension)) {}
Because validation will be executed when we call $form->isValid().
And by using \Zend\Filter\File\RenameUpload, you don't need to use move_uploaded_file() anymore. Because this filter will move the uploaded file to destination foder we defined in 'target' => 'public/files' option.
Filtering is executed when we call $form->getData();
And about explanation for Validator and Filter, I suggest you to create another post. By using a separate question, it will be easy to search in search engine and will help another to find it.
I have a warehouse grid in my module. My warehouse contains a lot of products, so when i am going to edit the warehouse, i added a products grid in warehouse edit tab. But, i confused about how to save the entire products grid to database. Really need help.
Here is my Grid
public function __construct() {
parent::__construct();
$this->setId('UnicornInventoryGrid');
$this->setDefaultSort('id_warehouse');
$this->setDefaultDir('ASC');
$this->setSaveParametersInSession(true);
$this->setUseAjax(true);
}
protected function _prepareCollection() {
$collection = Mage::getModel('inventory/warehouse')->getCollection();
$this->setCollection($collection);
return parent::_prepareCollection();
}
protected function _prepareColumns() {
$this->addColumn('id_warehouse', array(
'header' => Mage::helper('inventory')->__('id_warehouse'),
'filter_index' => 'main_table.id_warehouse',
'index' => 'id_warehouse',
'width' => '5px',
));
$this->addColumn('warehouse_name', array(
'header' => Mage::helper('inventory')->__('Warehouse Name'),
'filter_index' => 'main_table.warehouse_name',
'index' => 'warehouse_name',
'editable' => 'TRUE',
'width' => '5px',
));
$this->addColumn('created_by', array(
'header' => Mage::helper('inventory')->__('Created By'),
'filter_index' => 'main_table.created_by',
'index' => 'created_by',
'width' => '5px',
'editable' => 'TRUE',
));
$this->addColumn('manager_email', array(
'header' => Mage::helper('inventory')->__('Manager\'s Email'),
'filter_index' => 'main_table.manager_email',
'index' => 'manager_email',
'width' => '5px',
'editable' => 'TRUE',
));
$this->addColumn('phone', array(
'header' => Mage::helper('inventory')->__('Phone'),
'filter_index' => "main_table.phone",
'index' => "phone",
'editable' => 'TRUE',
));
$this->addColumn('street', array(
'header' => Mage::helper('inventory')->__('Street'),
'filter_index' => "ce3.street",
'index' => "street",
'editable' => 'TRUE',
));
$this->addColumn('city', array(
'header' => Mage::helper('inventory')->__('City'),
'filter_index' => 'main_table.city',
'index' => 'city',
'editable' => 'TRUE',
));
$this->addColumn('country', array(
'header' => Mage::helper('inventory')->__('Country'),
'filter_index' => 'main_table.country',
'index' => 'country',
'type' => 'options',
'editable' => 'TRUE',
'options' => array("" => "All Countries" , "Indonesia" => "Indonesia", "US" => "US")
));
$this->addColumn('status', array(
'header' => Mage::helper('inventory')->__('Status'),
'filter_index' => 'main_table.status',
'index' => 'phone',
));
// $this->addColumn('action',
// array(
// 'header' => Mage::helper('inventory')->__('Action'),
// 'width' => '100',
// 'type' => 'action',
// 'getter' => 'getId',
// 'actions' => array(
// array(
// 'caption' => Mage::helper('inventory')->__('Edit'),
// 'url' => array('base'=> '*/*/edit'),
// 'field' => 'id'
// )
// ),
// 'filter' => false,
// 'sortable' => false,
// 'index' => 'stores',
// 'is_system' => true,
// ));
$this->addExportType('*/*/exportCsv', Mage::helper('inventory')->__('CSV'));
$this->addExportType('*/*/exportXml', Mage::helper('inventory')->__('XML'));
return parent::_prepareColumns();
}
protected function _prepareMassaction() {
$this->setMassactionIdField('id');
$this->getMassactionBlock()->setFormFieldName('inventory_warehouse_mass_action');
$this->getMassactionBlock()->addItem('save', array(
'label' => Mage::helper('inventory')->__('Save'),
'url' => $this->getUrl('*/*/massSaveProduct'),
'confirm' => Mage::helper('inventory')->__('Are you sure?')
));
return $this;
}
public function getRowUrl($row) {
return $this->getUrl('*/*/edit', array('id' => $row->getIdWarehouse()));
}
and here is my controller
public function indexAction(){
$this->loadLayout();
$this->renderLayout();
// die("sadfsaf");
}
public function newAction() {
$id = $this->getRequest()->getParam('id');
if(empty($id)) $this->_title($this->__('Admin'))->_title($this->__('Add Warehouse'));
else $this->_title($this->__('Admin'))->_title($this->__('Edit Warehouse'));
$model = Mage::getModel('inventory/warehouse')->load($id);
if ($model->getId() || empty($id)) {
$data = Mage::getSingleton('adminhtml/session')->getFormData(true);
if (!empty($data))
$model->setData($data);
Mage::register('warehouse_warehouse_data', $model);
$this->loadLayout();
$this->_setActiveMenu('unicorn_inventory');
$this->getLayout()->getBlock('head')->setCanLoadExtJs(true);
$this->_addContent($this->getLayout()->createBlock('inventory/adminhtml_warehouse_edit'))
->_addLeft($this->getLayout()->createBlock('inventory/adminhtml_warehouse_edit_tabs'));
$this->renderLayout();
} else {
Mage::getSingleton('adminhtml/session')->addError(Mage::helper('inventory')->__('Warehouse does not exist.'));
$this->_redirect('*/*/');
}
}
public function editAction() {
$id = $this->getRequest()->getParam('id');
if(empty($id)) $this->_title($this->__('Admin'))->_title($this->__('Add Warehouse'));
else $this->_title($this->__('Admin'))->_title($this->__('Edit Warehouse'));
$model = Mage::getModel('inventory/warehouse')->load($id);
if ($model->getId() || empty($id)) {
$data = Mage::getSingleton('adminhtml/session')->getFormData(true);
if (!empty($data))
$model->setData($data);
Mage::register('inventory_warehouse_data', $model);
$this->loadLayout();
$this->_setActiveMenu('unicorn_warehouse');
$this->getLayout()->getBlock('head')->setCanLoadExtJs(true);
$this->_addContent($this->getLayout()->createBlock('inventory/adminhtml_warehouse_edit'))
->_addLeft($this->getLayout()->createBlock('inventory/adminhtml_warehouse_edit_tabs'));
$this->renderLayout();
} else {
Mage::getSingleton('adminhtml/session')->addError(Mage::helper('inventory')->__('Warehouse does not exist.'));
$this->_redirect('*/*/');
}
}
public function saveAction() {
if ($data = $this->getRequest()->getPost()) {
$model = Mage::getModel('inventory/warehouse');
$model->setData($data)
->setData('id_warehouse' , $this->getRequest()->getParam('id'));
try {
$collection = Mage::getModel('inventory/warehouse')->getCollection();
foreach($collection as $item){
if(($item->getIdWarehouse() == $model->getIdWarehouse()) && ($model->isObjectNew())){
Mage::getSingleton('adminhtml/session')->addError(Mage::helper('inventory')->__("Id '" . $model->getIdWarehouse(). "' already assigned."));
Mage::getSingleton('adminhtml/session')->setFormData($data);
$this->_redirect('*/*/new');
return;
}
}
// echo "<pre>";
// var_dump($data);
// echo "</pre>";
// die();
$model->save();
Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('inventory')->__('Warehouse telah disimpan'));
Mage::getSingleton('adminhtml/session')->setFormData(false);
if ($this->getRequest()->getParam('back')) {
$this->_redirect('*/*/edit', array('id' => $model->getId()));
return;
}
if ($this->getRequest()->getParam('backandnew')) {
$this->_redirect('*/*/new');
return;
}
$this->_redirect('*/*/');
return;
} catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
Mage::getSingleton('adminhtml/session')->setFormData($data);
$this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
return;
}
}
Mage::getSingleton('adminhtml/session')->addError(Mage::helper('inventory')->__('Unable to find warehouse to save.'));
$this->_redirect('*/*/');
}
/**
* mass save item(s) action
*/
public function massSaveProductAction() {
$dataIds = $this->getRequest()->getParam('inventory_warehouse_mass_action');
if (!is_array($dataIds)) {
Mage::getSingleton('adminhtml/session')->addError(Mage::helper('inventory')->__('Please select item(s)'));
} else {
try {
foreach ($dataIds as $dataId) {
// $model = Mage::getModel('inventory/wareproduct')->load($dataId);
$model = Mage::getModel('inventory/wareproduct');
$model->delete();
}
Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('supplier')->__('Total of %d record(s) were successfully deleted.', count($dataIds)));
} catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
}
}
$this->_redirect('*/*/index');
}
/**
* export grid item to CSV type
*/
public function exportCsvAction() {
$fileName = 'Unicorn_Inventory.csv';
$content = $this->getLayout()->createBlock('warehouse/adminhtml_warehouse_grid')->getCsv();
$this->_prepareDownloadResponse($fileName, $content);
}
/**
* export grid item to XML type
*/
public function exportXmlAction() {
$fileName = 'warehouse_warehouse.xml';
$content = $this->getLayout()->createBlock('warehouse/adminhtml_warehouse_grid')->getXml();
$this->_prepareDownloadResponse($fileName, $content);
}
public function gridAction()
{
$this->loadLayout();
$this->getResponse()->setBody(
$this->getLayout()->createBlock('inventory/adminhtml_warehouse_edit_tab_product')->toHtml()
);
}
So, what should we do, so every row in the grid can submitted and saved to database. Thx a lot for your attention.
In
massSaveProductAction
exchange the lines
$model = Mage::getModel('inventory/wareproduct');
$model->delete();
with
$model = Mage::getModel('inventory/wareproduct');
$model->setData('your_attribute_code',"YOUR_VALUE");
$model->save();
Answer for second question:
Get a collection of whatever entity type you have...
$collection->addFieldToFilter('YOUR_GRID_ID_FIELD', array('in'=>array($gridIds)))
and you have the collection. Iterate over the collection and do whatever is needed...
All I have created magento 1.8 custom module for admin.
It has grid and the add item option. In database table it has 2 fields ID [Auto increment] and NAME.
Everything working fine but when I click on save button it shows the success message but the name field data not saving to the database. only ID is incrementing and shown in the grid
protected function _prepareForm()
{
$form = new Varien_Data_Form();
$this->setForm($form);
$fieldset = $form->addFieldset('fondation_form', array('legend'=>Mage::helper('fondation')->__('Item information')));
$fieldset->addField('Name', 'text', array(
'label' => Mage::helper('fondation')->__('Name'),
'class' => 'required-entry',
'required' => true,
'name' => 'title',
));
if (Mage::getSingleton('adminhtml/session')->getFondationData()) {
$form->setValues(Mage::getSingleton('adminhtml/session')->getFondationData());
Mage::getSingleton('adminhtml/session')->setFondationData(null);
} elseif (Mage::registry('fondation_data')) {
$form->setValues(Mage::registry('fondation_data')->getData());
}
return parent::_prepareForm();
}
my saveAction function
public function saveAction()
{
if ($data = $this->getRequest()->getPost()) {
$model = Mage::getModel('fondation/fondation');
$model->setData($data)->setId($this->getRequest()->getParam('id'));
try {
$model->save();
Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('fondation')->__('Item was successfully saved'));
Mage::getSingleton('adminhtml/session')->setFormData(false);
if ($this->getRequest()->getParam('back')) {
$this->_redirect('*/*/edit', array('id' => $model->getId()));
return;
}
$this->_redirect('*/*/');
return;
} catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
Mage::getSingleton('adminhtml/session')->setFormData($data);
$this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
return;
}
}
Mage::getSingleton('adminhtml/session')->addError(Mage::helper('fondation')->__('Unable to find item to save'));
$this->_redirect('*/*/');
}
Your code is correct. if you have the field name "Name" in database table then use this code
$fieldset->addField('Name', 'text', array(
'label' => Mage::helper('fondation')->__('Name'),
'class' => 'required-entry',
'required' => true,
'name' => 'Name',
));
Copy Ordered.php
From
app/code/core/Mage/Adminhtml/Block/Dashboard/Tab/Products
to
app/code/local/Mage/Adminhtml/Block/Dashboard/Tab/Products
Rename New.php
I have modified the following code:
class Mage_Adminhtml_Block_Dashboard_Tab_Products_New extends Mage_Adminhtml_Block_Dashboard_Grid
{
public function __construct()
{
parent::__construct();
$this->setId('productsNewGrid');
}
protected function _prepareCollection()
{
if (!Mage::helper('core')->isModuleEnabled('Mage_Sales')) {
return $this;
}
if ($this->getParam('website')) {
$storeIds = Mage::app()->getWebsite($this->getParam('website'))->getStoreIds();
$storeId = array_pop($storeIds);
} else if ($this->getParam('group')) {
$storeIds = Mage::app()->getGroup($this->getParam('group'))->getStoreIds();
$storeId = array_pop($storeIds);
} else {
$storeId = (int)$this->getParam('store');
}
$todayStartOfDayDate = Mage::app()->getLocale()->date()
->setTime('00:00:00')
->toString(Varien_Date::DATETIME_INTERNAL_FORMAT);
$todayEndOfDayDate = Mage::app()->getLocale()->date()
->setTime('23:59:59')
->toString(Varien_Date::DATETIME_INTERNAL_FORMAT);
$collection = Mage::getResourceModel('catalog/product_collection');
$collection->setVisibility(Mage::getSingleton('catalog/product_visibility')->getVisibleInCatalogIds());
$collection
->addStoreFilter()
->addAttributeToFilter('news_from_date', array('or'=> array(
0 => array('date' => true, 'to' => $todayEndOfDayDate),
1 => array('is' => new Zend_Db_Expr('null')))
), 'left')
->addAttributeToFilter('news_to_date', array('or'=> array(
0 => array('date' => true, 'from' => $todayStartOfDayDate),
1 => array('is' => new Zend_Db_Expr('null')))
), 'left')
->addAttributeToFilter(
array(
array('attribute' => 'news_from_date', 'is'=>new Zend_Db_Expr('not null')),
array('attribute' => 'news_to_date', 'is'=>new Zend_Db_Expr('not null'))
)
);
$this->setCollection($collection);
return parent::_prepareCollection();
}
protected function _prepareColumns()
{
$this->addColumn('name', array(
'header' => $this->__('Product Name'),
'sortable' => false,
'index' => 'product_name'
));
$this->addColumn('price', array(
'header' => $this->__('Price'),
'width' => '120px',
'type' => 'currency',
'currency_code' => (string) Mage::app()->getStore((int)$this->getParam('store'))->getBaseCurrencyCode(),
'sortable' => false,
'index' => 'product_price'
));
$this->addColumn('ordered_qty', array(
'header' => $this->__('Quantity Ordered'),
'width' => '120px',
'align' => 'right',
'sortable' => false,
'index' => 'qty_ordered',
'type' => 'number'
));
$this->setFilterVisibility(false);
$this->setPagerVisibility(false);
return parent::_prepareColumns();
}
/*
* Returns row url to show in admin dashboard
* $row is bestseller row wrapped in Product model
*
* #param Mage_Catalog_Model_Product $row
*
* #return string
*/
public function getRowUrl($row)
{
// getId() would return id of bestseller row, and product id we get by getProductId()
$productId = $row->getProductId();
// No url is possible for non-existing products
if (!$productId) {
return '';
}
$params = array('id' => $productId);
if ($this->getRequest()->getParam('store')) {
$params['store'] = $this->getRequest()->getParam('store');
}
return $this->getUrl('*/catalog_product/edit', $params);
}
}
Then Copy Grids.php
From
app/code/core/Mage/Adminhtml/Block/Dashboard/
to
app/code/local/Mage/Adminhtml/Block/Dashboard/
added the following code:
$this->addTab('new_products', array(
'label' => $this->__('New Product'),
'content' => $this->getLayout()->createBlock('adminhtml/dashboard_tab_products_new')->toHtml(),
'class' => 'ajax'
));
I want to add a new product tab in admin dashboard,beside customers.I don't know what wrong with the New.php.I click the new product tab,it's not working.How to fix it?
I have managed to get this working with only a few more lines to change.
Update the Dashboard controller Mage_Adminhtml_DashboardController to add the new action
public function productsNewAction()
{
$this->loadLayout();
$this->renderLayout();
}
Update the admin layout.xml design\adminhtml\default\default\layout\main.xml to add the new section
<adminhtml_dashboard_productsnew>
<block type="core/text_list" name="root" output="toHtml">
<block type="adminhtml/dashboard_tab_products_new" name="adminhtml.dashboard.tab.products.new"/>
</block>
</adminhtml_dashboard_productsnew>
The you would just need to update your code in the Grids.php to the following.
$this->addTab('new_products', array(
'label' => $this->__('New Product'),
'url' => $this->getUrl('*/*/productsNew', array('_current'=>true)),
'class' => 'ajax'
));
This should then work using a call to the url rather than the block content.
You then need to select the attributes you want to show. You can do this by selecting all or by attribute code.
$collection->addAttributeToSelect('*')
$collection->addAttributeToSelect('name');
Important is the column index defined in _prepareColumns match these attribute codes Otherwise you will just get an empty row.
I would suggest packaging these changes into a new module with a controller, layout.xml and block files. There are lots of great tutorials around on how to do this, but obviously you don't have to :)
I'm trying to working with the Uploader Plugin to create a structure where a User Model can upload it's avatar with the Avatar Model, I've read the instructions several times but when I try to $this->Uploader->upload('Avatar.filename') I get no validation errors but the upload method fails.
Here is how I've written the User Model
<?php
class User extends AppModel {
public $name = 'User';
public $hasOne = array(
'Profile' => array(
'className' => 'Profile',
'conditions' => '',
'dependent' => true,
'foreignKey' => 'user_id',
'associatedKey' => 'user_id'
),
'Avatar' => array (
'className' => 'Avatar',
'foreignKey' => 'user_id',
'dependent' => true
)
);
public $validate = array(...);
// other stuff not relevant here...
?>
Here is the Avatar Model
<?php
class Avatar extends AppModel {
public $name = 'Avatar';
public $actsAs = array (
'Uploader.Attachment' => array (
'Avatar.filename' => array(
'name' => 'setNameAsImgId', // Name of the function to use to format filenames
'baseDir' => '', // See UploaderComponent::$baseDir
'uploadDir' => 'files/avatars/', // See UploaderComponent::$uploadDir
'dbColumn' => 'filename', // The database column name to save the path to
'importFrom' => '', // Path or URL to import file
'defaultPath' => '', // Default file path if no upload present
'maxNameLength' => 500, // Max file name length
'overwrite' => true, // Overwrite file with same name if it exists
'stopSave' => true, // Stop the model save() if upload fails
'allowEmpty' => true, // Allow an empty file upload to continue
'transforms' => array (
array('method' => 'resize', 'width' => 128, 'height' => 128, 'dbColumn' => 'name')
) // What transformations to do on images: scale, resize, ete
)
),
'Uploader.FileValidation' => array (
'Avatar.filename' => array (
'maxWidth' => array (
'value' => 512,
'error' => 'maxWidth error'
),
'maxHeight' => array (
'value' => 512,
'error' => 'maxWidth error'
),
'extension' => array (
'value' => array('gif', 'jpg', 'png', 'jpeg'),
'error' => 'extension error'
),
'filesize' => array (
'value' => 5242880,
'error' => 'filesize error'
)
)
)
);
public $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id',
'conditions' => '',
'order' => ''
)
);
public function setNameAsImgId ($name, $field, $file) {
/**
* Format the filename a specific way before uploading and attaching.
*
* #access public
* #param string $name - The current filename without extension
* #param string $field - The form field name
* #param array $file - The $_FILES data
* #return string
*/
// devo ricavare l'id dell'immagine appena creata per rinominare il file
return $name;
}
}
?>
This is the UsersController for edit method
<?php
App::uses('CakeEmail','Network/Email');
CakePlugin::load('Uploader');
App::import('Vendor', 'Uploader.Uploader');
class UsersController extends AppController {
public $name = 'Users';
public function edit ($id) {
$this->User->id = $id;
if (!$this->User->exists()) {
throw new NotFoundException ('Nessuna corrispondenza trovata per questo utente');
}
if (!$id) {
$this->set('flash_element','error');
$this->Session->setFlash ('Utente non valido');
}
$this->User->recursive = 1;
$this->set('user', $this->User->read());
if ($this->request->is('post')) {
$this->User->id = $this->request->data['User']['id'];
if (!$this->User->exists()) {
$this->set('flash_element','warning');
$this->Session->setFlash('Nessun utente trovato con questa corrispondenza');
}
if ($this->User->save($this->request->data)) {
$this->request->data['Profile']['user_id'] = $this->User->id;
$conditions = array(
'conditions' => array(
'Profile.id' => $this->request->data['Profile']['id']
)
);
if ($this->User->Profile->save($this->request->data, $conditions)) {
if (!empty($this->request->data['Avatar']['filename'])) {
$this->request->data['Avatar']['user_id'] = $this->User->id;
if ($this->User->Avatar->save($this->request->data)) {
$avatar = $this->User->Avatar->find('first', array(
'conditions' => array('Avatar.user_id' => $this->User->id)
));
$ext = Uploader::ext($this->request->data['Avatar']['filename']);
$filename = $avatar['Avatar']['id'].'.'.$ext;
if ($this->User->Avatar->save('Avatar.filename')) {
$this->set('flash_element','done');
$this->Session->setFlash('Avatar changed successfully');
debug('saved successfully');
} else {
debug('not saved');
$this->set('flash_element','warning');
$this->Session->setFlash('Avatar not saved on the server');
}
} else {
$this->Session->write('flash_element','error');
$this->Session->setFlash('Avatar data not saved on the server');
$this->redirect(array('action'=>'index'));
}
} else {
$this->Session->write('flash_element','done');
$this->Session->setFlash('Data successfully saved, avatar not changed');
$this->redirect(array('action'=>'index'));
}
} else {
$this->set('flash_element','error');
$this->Session->setFlash('Error on saving Profile data to the server');
}
} else {
$this->Session->write('flash_element','error');
$this->Session->setFlash('Error on saving User data to the server');
$this->redirect(array('action'=>'index'));
}
}
}
}
?>
And in the view file I have this
<?php
echo $this->Form->create('User', array ('class' => 'form'));
echo $this->Form->input('User.id', array ('type'=>'hidden', 'value'=> $user['User']['id'],'label'=> false, 'id' => 'id'));
echo $this->Form->input('User.username', array ('label'=> false, 'value' => $user['User']['username'], 'id' => 'username', 'after' => '<div class="message">Message for username field'));
echo $this->Form->input('User.email', array ('label'=> false, 'value' => $user['User']['email'], 'id' => 'email', 'after' => '<div class="message">Message for email field</div>'));
echo $this->Form->input('UserOptions.id', array ('type'=>'hidden', 'value'=> $user['UserOptions']['id'],'label'=> false, 'id' => 'UserOptions.id'));
$attributes = array ('value' => $user['UserOptions']['avatar_type'], 'empty' => false);
$options = array('0' => 'This site', '1' => 'Gravatar');
echo $this->Form->select('UserOptions.avatar_type', $options, $attributes);
/* avatar code */
echo $this->Form->input('Avatar.id', array ('type'=>'hidden', 'value'=> $user['Avatar']['id'],'label'=> false, 'id' => 'Avatar.id'));
echo $this->Form->input('Avatar.filename', array('type' => 'file'));
/* end avatar code */
echo $this->Form->input('Profile.city', array ('label'=> false, 'value' => defaultValue ('City', $user['Profile']['city']), 'id' => 'city', 'after' => '<div class="message">Message for city field</div>'));
echo $this->Form->input('Profile.country', array ('label'=> false, 'value' => defaultValue('',$user['Profile']['country']), 'id' => 'country', 'after' => '<div class="message">Message for country field</div>'));
echo $this->Form->input('Profile.url', array ('label'=> false, 'value' => defaultValue('http://', $user['Profile']['url']), 'id' => 'url', 'after' => '<div class="message">Message for url field</div>'));
echo $this->Form->input('Profile.description', array ('label'=> false, 'value' => defaultValue('Description',$user['Profile']['description']), 'id' => 'description', 'after' => '<div class="message">Message for description field</div>'));
echo $this->Form->submit('Modifica', array('id'=>'edit'));
echo $this->Form->end();
?>
In the Controller, every part of the data is saved until I reach $this->Uploader->upload('Avatar.filename', array('overwrite' => true, 'name' => $filename)) where I get a generic error.
This Plugin seems to be the best way to do it without write tons of code, but I'm not sure how to use it.
I'm not sure what's wrong with the code, can You help me to solve the problem?
I've found the problems, I forgot two things:
In the view page I've forgot 'type' => 'file'
<?php
echo $this->Form->create('User', array ('class' => 'form', 'type' => 'file'));
?>
I was used to work with 1.3 version so the app/Config/bootstrap.php configuration was missing:
<?php
CakePlugin::load('Uploader');
?>
Now it works!