Magento: Adminhtml form “Image” Field - image

I have set an input field of type “Image” in an admin form using the code below:
<?php
// Tab Form
// File: app/code/local/MyCompany/Mymodule/Block/Adminhtml/Items/Edit/Tab/Form.php
class MyCompany_Mymodule_Block_Adminhtml_Items_Edit_Tab_Form extends Mage_Adminhtml_Block_Widget_Form
{
protected function _prepareForm()
{
$form = new Varien_Data_Form();
$this->setForm($form);
$fieldset = $form->addFieldset('mymodule_form', array('legend'=>Mage::helper('mymodule')->__('Item information')));
$fieldset->addField('photo', 'image', array(
'label' => Mage::helper('mymodule')->__('Photo'),
'required' => false,
'name' => 'photo',
));
if ( Mage::getSingleton('adminhtml/session')->getMymoduleData() )
{
$form->setValues(Mage::getSingleton('adminhtml/session')->getMymoduleData());
Mage::getSingleton('adminhtml/session')->setMymoduleData(null);
} elseif ( Mage::registry('mymodule_data') ) {
$form->setValues(Mage::registry('mymodule_data')->getData());
}
return parent::_prepareForm();
}
}
And then, inside the controller save the image using:
public function saveAction()
{
if($data = $this->getRequest()->getPost()) {
$model = Mage::getModel('mymodule/speakers');
$model->setData($data)->setId($this->getRequest()->getParam('id'));
$model->setKeynote($this->getRequest()->getParam('keynote'));
// Save photo
if(isset($_FILES['photo']['name']) && $_FILES['photo']['name'] != '') {
try {
$uploader = new Varien_File_Uploader('photo');
$uploader->setAllowedExtensions(array('jpg','jpeg','gif','png'));
$uploader->setAllowRenameFiles(false);
$uploader->setFilesDispersion(false);
// Set media as the upload dir
$media_path = Mage::getBaseDir('media') . DS;
// Upload the image
$uploader->save($media_path, $_FILES['photo']['name']);
$data['photo'] = $media_path . $_FILES['photo']['name'];
}
catch (Exception $e) {
print_r($e);
die;
}
}
else {
if(isset($data['photo']['delete']) && $data['photo']['delete'] == 1) {
$data['photo'] = '';
}
else {
unset($data['photo']);
}
}
if(isset($data['photo'])) $model->setPhoto($data['photo']);
try {
$model->save();
Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('mymodule')->__('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('mymodule')->__('Unable to find item to save'));
$this->_redirect('*/*/');
}
Long story short: When I save the item (using Save or Save and Continue Edit) in backend it saves well one time. Then the next time it gives the next error:
Notice: Array to string conversion in
/home/wwwadmin/public_html/aaa.bbb.ccc/public/lib/Zend/Db/Statement/Pdo.php
on line 232
The next saves ok. The next: error. The next ok… You know what I mean…
I was looking some code to see how this input type is used. But nothing yet. Neither inside the magento code. This is the only thing I’ve found: http://www.magentocommerce.com/wiki/how_to/how_to_create_pdf_upload_in_backend_for_own_module
Any ideas?
Thanks

When this line is runs:
$model->setData($data)->setId($this->getRequest()->getParam('id'));<br/>
$model->_data['image'] will be set to array('image'=>'[YOUR path]')<br/>
you should call method setData() after all manipulations with data['image'];

Try below code for save action in your controller
if ($data = $this->getRequest()->getPost()) {
$id = $this->getRequest()->getParam('id');
$model = Mage::getModel('your_model')->load($id);
if (isset($data['image']['delete'])) {
Mage::helper('your_helper')->deleteImageFile($data['image']['value']);
}
$image = Mage::helper('your_helper')->uploadBannerImage();
if ($image || (isset($data['image']['delete']) && $data['image']['delete'])) {
$data['image'] = $image;
} else {
unset($data['image']);
}
$model->setData($data)
->setId($id);
try {
$model->save();
Mage::getSingleton('adminhtml/session')->addSuccess('Your request Save.');
$this->_redirect('*/*/');
} 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;
}
} else {
Mage::getSingleton('adminhtml/session')->addError(Mage::helper('your_helper')->__('Unable to find your request to save'));
$this->_redirect('*/*/');
}
In your helper
public function uploadBannerImage() {
$path = Mage::getBaseDir('media') . DS . 'images';
$image = "";
if (isset($_FILES['image']['name']) && $_FILES['image']['name'] != '') {
try {
/* Starting upload */
$uploader = new Varien_File_Uploader('image');
// Any extention would work
$uploader->setAllowedExtensions(array(
'jpg', 'jpeg', 'gif', 'png'
));
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(true);
$uploader->save($path, $uploader->getCorrectFileName($_FILES['image']['name']));
$image = substr(strrchr($uploader->getUploadedFileName(), "/"), 1);
} catch (Exception $e) {
Mage::getSingleton('customer/session')->addError($e->getMessage());
}
}
return $image;
}
public function deleteImageFile($image) {
if (!$image) {
return;
}
try {
$img_path = Mage::getBaseDir('media') . "/" . $image;
if (!file_exists($img_path)) {
return;
}
unlink($img_path);
} catch (Exception $exc) {
echo $exc->getTraceAsString();
}
}

Related

Magento - Hidden value not set in grid serializer

I'm developing an extension for magento which display question groups from custom database table and I need to assign questions(which is loaded from another custom table ), to groups.
So far I could code the grid to display question groups, and questions. When I go to edit one question group, it displays all the questions there in the database. What I need is to select some of them and save. If I load all the questions to one screen ( so far I have 130 questions and I can load all of them to one screen by changing "view 20 per page" to read "view 200 per page" in the grid) and select what I need, and then save, it works as a charm.
But if I select some questions from page 1 and navigate to 2nd page and then select some other questions, and so on, Only the questions in the last page are saved. And all the other selections in the previous pages are lost.
I found that the hidden value of the grid serialize is overridden each time I navigate through pages so selections are lost.
Any advice is greatly appreciate.
Here is the code I used
app\code\community\Muaw\Prescription\Block\Adminhtml\Groups\Edit\Tab\Question.php
class Muaw_Prescription_Block_Adminhtml_Groups_Edit_Tab_Question extends Mage_Adminhtml_Block_Widget_Grid
{
public function __construct()
{
parent::__construct();
$this->setId('questionsGrid');
$this->setUseAjax(true);
$this->setDefaultFilter(array('in_questions' => 1));
$this->setSaveParametersInSession(false);
}
protected function _addColumnFilterToCollection($column)
{
if ($column->getId() == 'in_questions') {
$questionIds = $this->_getSelectedQuestions();
if (empty($questionIds)) {
$questionIds = 0;
}
if ($column->getFilter()->getValue()) {
$this->getCollection()->addFieldToFilter('id', array('in' => $questionIds));
} else {
if ($questionIds) {
$this->getCollection()->addFieldToFilter('id', array('nin' => $questionIds));
}
}
} else {
parent::_addColumnFilterToCollection($column);
}
return $this;
}
protected function _prepareCollection()
{
$collection = Mage::getModel('muaw_prescription/question')->getCollection();
$this->setCollection($collection);
return parent::_prepareCollection();
}
protected function _prepareColumns()
{
$this->addColumn('in_questions', array(
'header_css_class' => 'a-center',
'type' => 'checkbox',
'name' => 'in_questions',
'field_name' => 'questions[]',
'values' => $this->_getSelectedQuestions(),
'align' => 'center',
'index' => 'id'
));
$this->addColumn('id', array(
'header' => Mage::helper('catalog')->__('ID'),
'sortable' => true,
'width' => '60',
'index' => 'id'
));
$this->addColumn('question', array(
'header' => $this->__('Question'),
'index' => 'question',
'align' => 'left',
));
return parent::_prepareColumns();
}
protected function _getSelectedQuestions()
{
$customers = array_keys($this->getSelectedQuestions());
return $customers;
}
public function getSelectedQuestions()
{
$tm_id = $this->getRequest()->getParam('id');
if (!isset($tm_id)) {
$tm_id = 0;
}
$questions = array();
$groupq = Mage::getModel('muaw_prescription/qgr')->getCollection()->addFieldToFilter('group_id', $tm_id);
foreach ($groupq as $group) {
$questions[] = $group->getQuestionId();
}
$custIds = array();
foreach ($questions as $cust) {
$custIds[$cust] = array('id' => $cust);
}
return $custIds;
}
public function getGridUrl()
{
return $this->_getData('grid_url') ? $this->_getData('grid_url') : $this->getUrl('*/*/questionsGrid', array('_current' => true));
}
}
app\code\community\Muaw\Prescription\Block\Adminhtml\Groups\Edit\Tabs.php
class Muaw_Prescription_Block_Adminhtml_Groups_Edit_Tabs extends Mage_Adminhtml_Block_Widget_Tabs
{
public function __construct()
{
parent::__construct();
$this->setId('form_tabs');
$this->setDestElementId('edit_form');
$this->setTitle(Mage::helper('muaw_prescription')->__('Group Information'));
}
protected function _beforeToHtml()
{
$this->addTab('form_section', array(
'label' => Mage::helper('muaw_prescription')->__('Groups Information'),
'title' => Mage::helper('muaw_prescription')->__('Details'),
'content' => $this->getLayout()
->createBlock('muaw_prescription/adminhtml_groups_edit_tab_main')
->toHtml(),
));
$this->addTab('questions', array(
'label' => Mage::helper('muaw_prescription')->__('Associated Questions'),
'url' => $this->getUrl('*/*/questionstab', array('_current' => true)),
'content' => $this->getLayout(),
'class' => 'ajax',
));
return parent::_beforeToHtml();
}
}
app\code\community\Muaw\Prescription\controllers\Adminhtml\GroupsController.php
class Muaw_Prescription_Adminhtml_GroupsController extends Mage_Adminhtml_Controller_Action
{
protected function _initAction()
{
// load layout, set active menu and breadcrumbs
$this->loadLayout()
->_setActiveMenu('prescription/manage')
->_addBreadcrumb(
Mage::helper('muaw_prescription')->__('Group'),
Mage::helper('muaw_prescription')->__('Group')
)
->_addBreadcrumb(
Mage::helper('muaw_prescription')->__('Manage Group'),
Mage::helper('muaw_prescription')->__('Manage Group')
);
return $this;
}
public function indexAction()
{
$this->_title($this->__('Group'))
->_title($this->__('Manage Group'));
$this->_initAction();
$this->renderLayout();
}
public function QuestionAction()
{
$this->_title($this->__('Group Questions'))
->_title($this->__('Manage Group Questions'));
$this->loadLayout()
->_setActiveMenu('groups/manage')
->_addBreadcrumb(
Mage::helper('muaw_prescription')->__('Group Questions'),
Mage::helper('muaw_prescription')->__('Group Questions')
)
->_addBreadcrumb(
Mage::helper('muaw_prescription')->__('Manage Group Questions'),
Mage::helper('muaw_prescription')->__('Manage Group Questions')
);
$this->renderLayout();
}
public function newAction()
{
// the same form is used to create and edit
$this->_forward('edit');
}
public function editAction()
{
$this->_title($this->__('Group'))
->_title($this->__('Manage Group'));
$model = Mage::getModel('muaw_prescription/groups');
$newsId = $this->getRequest()->getParam('id');
if ($newsId) {
$model->load($newsId);
if (!$model->getId()) {
$this->_getSession()->addError(Mage::helper('muaw_prescription')->__('Group does not exist.'));
return $this->_redirect('*/*/');
}
$this->_title($model->getTitle());
$breadCrumb = Mage::helper('muaw_prescription')->__('Edit Item');
} else {
$this->_title(Mage::helper('muaw_prescription')->__('New Item'));
$breadCrumb = Mage::helper('muaw_prescription')->__('New Item');
}
$this->_initAction()->_addBreadcrumb($breadCrumb, $breadCrumb);
$data = Mage::getSingleton('adminhtml/session')->getFormData(true);
if (!empty($data)) {
$model->addData($data);
}
Mage::register('question_item', $model);
$this->renderLayout();
}
public function saveAction()
{
$redirectPath = '*/*';
$redirectParams = array();
// check if data sent
$data = $this->getRequest()->getPost();
if (isset($data['links'])) {
$customers = Mage::helper('adminhtml/js')->decodeGridSerializedInput($data['links']['questions']);
}
//print_r($customers);exit;
if ($data) {
$data = $this->_filterPostData($data);
$model = Mage::getModel('muaw_prescription/groups');
if (empty($data['pid'])) {
$arr = array();
$arr['form_key'] = $data['form_key'];
$arr['name'] = $data['name'];
$model->addData($arr);
$out = $model->save()->getId();
} else {
$arr = array();
$arr['form_key'] = $data['form_key'];
$arr['id'] = $data['pid'];
$arr['name'] = $data['name'];
$model->load($data['pid'])->addData($arr);
$model->setId($data['pid'])->save();
$out = $data['pid'];
}
try {
$hasError = false;
$this->_getSession()->addSuccess(Mage::helper('muaw_prescription')->__('The Group has been saved.'));
// check if 'Save and Continue'
if ($this->getRequest()->getParam('back')) {
$redirectPath = '*/*/edit';
$redirectParams = array('id' => $out);
}
$groupq = Mage::getModel('muaw_prescription/qgr')->getCollection()->addFieldToFilter('group_id', $out);
$sel_question = array();
foreach ($groupq as $group) {
if (!empty($group->getQuestionId())) {
$sel_question[$group->getId()] = $group->getQuestionId();
}
}
$del_arr = $new_arr = array();
$del_arr = array_diff($sel_question, $data['questions']);
$new_arr = array_diff($data['questions'], $sel_question);
if (!empty($data['questions'])) {
if (!empty($del_arr)) {
foreach ($del_arr as $del => $val) {
$id = $del;
$model_qgr = Mage::getModel('muaw_prescription/qgr');
try {
$model_qgr->setId($id)->delete();
} catch (Exception $e) {
//echo $e->getMessage();
}
}
}
} else {
$collection = Mage::getModel('muaw_prescription/qgr')->getCollection()->addFieldToFilter('group_id', $out);
foreach ($collection as $item) {
$id = $item->getId();
$model_qgr = Mage::getModel('muaw_prescription/qgr');
try {
$model_qgr->setId($id)->delete();
} catch (Exception $e) {
//echo $e->getMessage();
}
}
}
if (!empty($new_arr)) {
foreach ($new_arr as $new) {
if ($new != 'on') {
$new_data = array();
$new_data['question_id'] = $new;
$new_data['group_id'] = $out;
try {
$model_qgr = Mage::getModel('muaw_prescription/qgr')->setData($new_data);
$insertId = $model_qgr->save()->getId();
} catch (Exception $e) {
//echo $e->getMessage();
}
}
}
} else {
}
} catch (Mage_Core_Exception $e) {
$hasError = true;
$this->_getSession()->addError($e->getMessage());
} catch (Exception $e) {
$hasError = true;
$this->_getSession()->addException($e, Mage::helper('muaw_prescription')->__('An error occurred while saving the Group.'));
}
if ($hasError) {
$this->_getSession()->setFormData($data);
$redirectPath = '*/*/edit';
$redirectParams = array('id' => $data['pid']);
}
}
$this->_redirect($redirectPath, $redirectParams);
}
public function deleteAction()
{
// check if we know what should be deleted
$itemId = $this->getRequest()->getParam('id');
if ($itemId) {
try {
$model = Mage::getModel('muaw_prescription/groups');
$model->load($itemId);
if (!$model->getId()) {
Mage::throwException(Mage::helper('muaw_prescription')->__('Unable to find a group.'));
}
$model->delete();
$this->_getSession()->addSuccess(
Mage::helper('muaw_prescription')->__('The group has been deleted.')
);
} catch (Mage_Core_Exception $e) {
$this->_getSession()->addError($e->getMessage());
} catch (Exception $e) {
$this->_getSession()->addException($e,
Mage::helper('muaw_prescription')->__('An error occurred while deleting the group.')
);
}
}
$this->_redirect('*/*/');
}
protected function _initGroups()
{
$groupModel = Mage::getModel('muaw_prescription/groups');
$groupId = (int)$this->getRequest()->getParam('id', 0);
if ($groupId) {
try {
$groupModel->load($groupId);
if (!$groupModel->getId()) {
throw new Exception($this->__('This group no longer exists'));
}
} catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
return null;
}
}
Mage::register('current_group', $groupModel);
return $groupModel;
}
protected function _isAllowed()
{
switch ($this->getRequest()->getActionName()) {
case 'new':
case 'save':
return Mage::getSingleton('admin/session')->isAllowed('groups/manage/save');
break;
case 'delete':
return Mage::getSingleton('admin/session')->isAllowed('groups/manage/delete');
break;
default:
return Mage::getSingleton('admin/session')->isAllowed('groups/manage');
break;
}
}
protected function _filterPostData($data)
{
$data = $this->_filterDates($data, array('time_published'));
return $data;
}
public function gridAction()
{
$this->loadLayout();
$this->renderLayout();
}
protected function _isAjax()
{
if ($this->getRequest()->isXmlHttpRequest()) {
return true;
}
if ($this->getRequest()->getParam('ajax') || $this->getRequest()->getParam('isAjax')) {
return true;
}
return false;
}
public function questionsTabAction()
{
$itemId = $this->getRequest()->getParam('id');
$groupq = Mage::getModel('muaw_prescription/qgr')->getCollection()->addFieldToFilter('group_id', $itemId);
$sel_question = array();
foreach ($groupq as $group) {
if (!empty($group->getQuestionId())) {
$sel_question[] = $group->getQuestionId();
}
}
$saved_question_ids = $sel_question; // your load logic here
if (!empty($saved_question_ids)) {
$this->loadLayout()
->getLayout()
->getBlock('muaw.tab.questions')
->setQuestions($saved_question_ids);
} else {
$this->loadLayout()
->getLayout()
->getBlock('muaw.tab.questions')
->setQuestions($this->getRequest()->getPost('questions', null));
}
$this->renderLayout();
}
public function questionsGridAction()
{
$this->loadLayout()
->getLayout()
->getBlock('muaw.tab.questions')
->setQuestions($this->getRequest()->getPost('questions', null));
$this->renderLayout();
}
public function questionsAction()
{
$this->loadLayout();
$this->getLayout()->getBlock('muaw.tab.questions')
->setQuestions($this->getRequest()->getPost('questions', null));
$this->renderLayout();
}
}
app\design\adminhtml\default\default\layout\muaw_prescription.xml
<adminhtml_groups_edit>
<update handle="editor"/>
<reference name="left">
<block type="muaw_prescription/adminhtml_groups_edit_tabs" name="groups.edit.tabs" />
</reference>
<reference name="content">
<block type="muaw_prescription/adminhtml_groups_edit" name="groups.edit" />
</reference>
</adminhtml_groups_edit>
<adminhtml_groups_questionstab>
<block type="core/text_list" name="root" output="toHtml">
<block type="muaw_prescription/adminhtml_groups_edit_tab_question" name="muaw.tab.questions"/>
<block type="adminhtml/widget_grid_serializer" name="muaw.serializer.questions">
<reference name="muaw.serializer.questions">
<action method="initSerializerBlock">
<grid_block_name>muaw.tab.questions</grid_block_name>
<data_callback>getSelectedQuestions</data_callback>
<hidden_input_name>links[questions]</hidden_input_name>
<reload_param_name>questions</reload_param_name>
</action>
<action method="addColumnInputName">
<input_name>position</input_name>
</action>
</reference>
</block>
</block>
</adminhtml_groups_questionstab>
<adminhtml_groups_questionsgrid>
<block type="core/text_list" name="root">
<block type="muaw_prescription/adminhtml_groups_edit_tab_question" name="muaw.tab.questions"/>
</block>
</adminhtml_groups_questionsgrid>

Unset sessions after form success not working

When I deselect my check box in my modify & access permissions it does not unset it from sessions if form is submitted success full.
What I am trying to achieve is on my edit function if any check box is not checked then it will unset from sessions when form is submitted success full. Because the reason need it unset from sessions is because when user logs in the permissions modify and access are set into sessions.
How can I make this work what I am after I have tried it in my edit but not unset when check box is empty
If i use this $this->session->unset_userdata('modify'); it unset all the modify array in sessions I just need it to unset the one that matches the unchecked check box.
public function edit() {
$this->load->model('admin/user/model_user_group');
if ($this->input->server('REQUEST_METHOD') == 'POST') {
$this->model_user_group->editUserGroup($this->uri->segment(4), $this->input->post());
if ($this->session->userdata('user_id') == TRUE) {
if (isset($_POST['permission[access]'])) {
$this->session->unset_userdata('permission[access]');
}
if (isset($_POST['permission[modify]'])) {
$this->session->unset_userdata('permission[modify]');
}
}
redirect('admin/users_group');
}
$this->getForm();
}
public function getForm() {
$data['title'] = "Users Group";
$this->load->model('admin/user/model_user_group');
$user_group_info = $this->model_user_group->getUserGroup($this->uri->segment(4));
if ($this->uri->segment(4) == FALSE) {
$data['name'] = $this->input->post('name');
} else {
$data['name'] = $user_group_info['name'];
}
if ($this->uri->segment(4) == FALSE) {
$data['user_group_id'] = $this->input->post('user_group_id');
} else {
$data['user_group_id'] = $user_group_info['user_group_id'];
}
$ignore = array(
'admin',
'dashboard',
'filemanager',
'login',
'menu',
'register',
'online',
'customer_total',
'user_total',
'chart',
'activity',
'logout',
'footer',
'header',
'permission'
);
$data['permissions'] = array();
$files = glob(FCPATH . 'application/modules/admin/controllers/*/*.php');
foreach ($files as $file) {
$permission = basename(strtolower($file), '.php');
if (!in_array($permission, $ignore)) {
$data['permissions'][] = $permission;
}
}
$permission_access = $this->input->post('permission');
if (isset($permission_access)) {
if (isset($permission_access['access'])) {
$data['access'] = $permission_access['access'];
} elseif (!empty($user_group_info['permission']['access'])) {
$data['access'] = $user_group_info['permission']['access'];
} else {
$data['access'] = array();
}
}
$permission_modify = $this->input->post('permission');
if (isset($permission_modify)) {
if (isset($permission_modify['modify'])) {
$data['modify'] = $permission_modify['modify'];
} elseif (!empty($user_group_info['permission']['modify'])) {
$data['modify'] = $user_group_info['permission']['modify'];
} else {
$data['modify'] = array();
}
}
$this->load->view('template/user/users_group_form.tpl', $data);
}
I have found away to get it working I have got sessions from database then re set the sessions in form, without using unset_sessions();
public function edit() {
$this->load->model('admin/user/model_user_group');
if ($this->input->server('REQUEST_METHOD') == 'POST') {
$this->model_user_group->editUserGroup($this->uri->segment(4), $this->input->post());
$user_group_query = $this->db->query("SELECT permission FROM " . $this->CI->db->dbprefix . "user_group
WHERE user_group_id = '" . (int)$this->session->userdata('user_group_id') . "'");
$permissions = unserialize($user_group_query->row('permission'));
$this->session->set_userdata($permissions);
redirect('admin/users_group');
}
$this->getForm();
}

Magento Saving Multiselect Value on Custom Model

I have create a custom model in Magento which can get to and edit in the admin. I'm having trouble dealing with array's however. When I go to save the model, the text field saves fine, but the multiselect field just saves as 'array' and I'm then unable to go and edit it.
I need to know how to save seperate row in databse not comma seprate .
Can anybody help with this? Any help much appreciated!!!
public function saveAction() {
if ($data = $this->getRequest()->getPost()) {
if(isset($_FILES['image']['name']) && $_FILES['image']['name'] != null) {
try {
/* Starting upload */
$uploader = new Varien_File_Uploader('image');
// Any extention would work
$uploader->setAllowedExtensions(array('jpg','jpeg','gif','png'));
$uploader->setAllowRenameFiles(false);
// Set the file upload mode
// false -> get the file directly in the specified folder
// true -> get the file in the product like folders
// (file.jpg will go in something like /media/f/i/file.jpg)
$uploader->setFilesDispersion(false);
// We set media as the upload dir
$path = Mage::getBaseDir('media') . DS.'magentothem/vendorlist'.DS ;
$uploader->save($path, $_FILES['image']['name'] );
} catch (Exception $e) {
}
//this way the name is saved in DB
$basepath=Mage::getBaseUrl().'media/magentothem/vendorlist/';
$basepath=str_replace("index.php/","",$basepath);
$data['image'] = '<img src="'.$basepath.$_FILES['image']['name'].'" width="150" height="100px" alt="" />';
}
**$data['productid'] = join("," ,$_POST['productid']);**
$model = Mage::getModel('vendorlist/vendorlist');
$model->setData($data)->setId($this->getRequest()->getParam('id'));
try {
if ($model->getCreatedTime == NULL || $model->getUpdateTime() == NULL) {
$model->setCreatedTime(now())
->setUpdateTime(now());
} else {
$model->setUpdateTime(now());
}
$model->save();
Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('vendorlist')->__('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('vendorlist')->__('Unable to find item to save'));
$this->_redirect('*/*/');
}
if you want separate rows in your table, I assume the the id column is not the PK.
In this case you could try:
$model = Mage::getModel('vendorlist/vendorlist');
$productIds = Mage::app()->getRequest()->getParam('productid');
foreach ($productIds as $productId) {
$model->setData($data)->setProductid($productId)->setId($this->getRequest()->getParam('id'));
try {
if ($model->getCreatedTime == NULL || $model->getUpdateTime() == NULL) {
$model->setCreatedTime(now())
->setUpdateTime(now());
} else {
$model->setUpdateTime(now());
}
$model->save();
//remove what is after, put it after the try/catch
} catch (Exception $e) {
//handle exception
}
}

How to get carrier by "shipping method" in magento

Typical magento's order has shipping_method. For example, in my case, it is "flatrate_flatrate".
How to bind carrier ("flatrate") with shipping_method?
Thanks for response.
public function getShippingMethodsList($quoteId, $store=null)
{
$quote = $this->_getQuote($quoteId, $store);
$quoteShippingAddress = $quote->getShippingAddress();
if (is_null($quoteShippingAddress->getId())) {
$this->_fault("shipping_address_is_not_set");
}
try {
$quoteShippingAddress->collectShippingRates()->save();
$groupedRates = $quoteShippingAddress->getGroupedAllShippingRates();
$ratesResult = array();
foreach ($groupedRates as $carrierCode => $rates ) {
$carrierName = $carrierCode;
if (!is_null(Mage::getStoreConfig('carriers/'.$carrierCode.'/title'))) {
$carrierName = Mage::getStoreConfig('carriers/'.$carrierCode.'/title');
}
foreach ($rates as $rate) {
$rateItem = $this->_getAttributes($rate, "quote_shipping_rate");
$rateItem['carrierName'] = $carrierName;
$ratesResult[] = $rateItem;
unset($rateItem);
}
}
} catch (Mage_Core_Exception $e) {
$this->_fault('shipping_methods_list_could_not_be_retrived', $e->getMessage());
}
return $ratesResult;
}

Fatal error:Class 'Mage_Adminhtml_Controller_action' not found in BookmarksController.php on line 4

it shows:
Fatal error: Class 'Mage_Adminhtml_Controller_action' not found in .../app/code/local/Magentix/SocialBookmarking/controllers/Adminhtml/BookmarksController.php on line 4
I check it and find that nothing is in bookmarkscontroller.php.on line 4. What's wrong is it?
and I also check it that the social bookmarket plugin still shows in the front page here.
Original code:
<?php
/** http://www.magentix.fr **/
class Magentix_SocialBookmarking_Adminhtml_BookmarksController extends Mage_Adminhtml_Controller_action {
protected function _initAction() {
$this->loadLayout()
->_setActiveMenu('cms/socialbookmarking')
->_addBreadcrumb(Mage::helper('adminhtml')->__('Items Manager'), Mage::helper('adminhtml')->__('Item Manager'));
return $this;
}
public function indexAction() {
$this->_initAction()->renderLayout();
}
public function editAction() {
$id = $this->getRequest()->getParam('id');
$model = Mage::getModel('socialbookmarking/bookmarks')->load($id);
if ($model->getId() || $id == 0) {
$data = Mage::getSingleton('adminhtml/session')->getFormData(true);
if (!empty($data)) {
$model->setData($data);
}
Mage::register('socialbookmarking_data', $model);
$this->loadLayout();
$this->_setActiveMenu('cms/socialbookmarking');
$this->_addBreadcrumb(Mage::helper('adminhtml')->__('Item Manager'), Mage::helper('adminhtml')->__('Item Manager'));
$this->_addBreadcrumb(Mage::helper('adminhtml')->__('Item News'), Mage::helper('adminhtml')->__('Item News'));
$this->getLayout()->getBlock('head')->setCanLoadExtJs(true);
$this->_addContent($this->getLayout()->createBlock('socialbookmarking/adminhtml_bookmarks_edit'))
->_addLeft($this->getLayout()->createBlock('socialbookmarking/adminhtml_bookmarks_edit_tabs'));
$this->renderLayout();
} else {
Mage::getSingleton('adminhtml/session')->addError(Mage::helper('socialbookmarking')->__('Bookmark does not exist'));
$this->_redirect('*/*/');
}
}
public function newAction() {
$this->_forward('edit');
}
public function saveAction() {
if ($data = $this->getRequest()->getPost()) {
if(isset($_FILES['bookmarkimage']['name']) && $_FILES['bookmarkimage']['name'] != '') {
try {
$uploader = new Varien_File_Uploader('bookmarkimage');
$uploader->setAllowedExtensions(array('jpg','jpeg','gif','png'));
$uploader->setAllowRenameFiles(false);
$uploader->setFilesDispersion(false);
$path = Mage::getBaseDir('media').DS.'social';
$uploader->save($path, $_FILES['bookmarkimage']['name']);
} catch (Exception $e) {
}
$data['image'] = 'social/'.$_FILES['bookmarkimage']['name'];
}
if(isset($data['bookmarkimage']['delete'])) $data['image'] = '';
$model = Mage::getModel('socialbookmarking/bookmarks');
$model->setData($data)->setId($this->getRequest()->getParam('id'));
try {
if ($model->getCreatedTime == NULL || $model->getUpdateTime() == NULL) {
$model->setCreatedTime(now())->setUpdateTime(now());
} else {
$model->setUpdateTime(now());
}
$model->save();
Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('socialbookmarking')->__('Bookmark 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('socialbookmarking')->__('Unable to find bookmark to save'));
$this->_redirect('*/*/');
}
public function deleteAction() {
if( $this->getRequest()->getParam('id') > 0 ) {
try {
$model = Mage::getModel('socialbookmarking/bookmarks');
$model->setId($this->getRequest()->getParam('id'))->delete();
Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('socialbookmarking')->__('Bookmark was successfully deleted'));
$this->_redirect('*/*/');
} catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
$this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
}
}
$this->_redirect('*/*/');
}
public function massDeleteAction() {
$socialbookmarkingIds = $this->getRequest()->getParam('socialbookmarking');
if(!is_array($socialbookmarkingIds)) {
Mage::getSingleton('adminhtml/session')->addError(Mage::helper('socialbookmarking')->__('Please select bookmark(s)'));
} else {
try {
foreach ($socialbookmarkingIds as $socialbookmarkingId) {
$socialbookmarking = Mage::getModel('socialbookmarking/bookmarks')->load($socialbookmarkingId);
$socialbookmarking->delete();
}
Mage::getSingleton('adminhtml/session')->addSuccess(
Mage::helper('adminhtml')->__(
'Total of %d record(s) were successfully deleted', count($socialbookmarkingIds)
)
);
} catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
}
}
$this->_redirect('*/*/index');
}
public function massStatusAction() {
$socialbookmarkingIds = $this->getRequest()->getParam('socialbookmarking');
if(!is_array($socialbookmarkingIds)) {
Mage::getSingleton('adminhtml/session')->addError($this->__('Please select bookmark(s)'));
} else {
try {
foreach ($socialbookmarkingIds as $socialbookmarkingId) {
$socialbookmarking = Mage::getSingleton('socialbookmarking/bookmarks')
->load($socialbookmarkingId)
->setStatus($this->getRequest()->getParam('status'))
->setIsMassupdate(true)
->save();
}
$this->_getSession()->addSuccess(
$this->__('Total of %d record(s) were successfully updated', count($socialbookmarkingIds))
);
} catch (Exception $e) {
$this->_getSession()->addError($e->getMessage());
}
}
$this->_redirect('*/*/index');
}
protected function _sendUploadResponse($fileName, $content, $contentType='application/octet-stream') {
$response = $this->getResponse();
$response->setHeader('HTTP/1.1 200 OK','');
$response->setHeader('Pragma', 'public', true);
$response->setHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0', true);
$response->setHeader('Content-Disposition', 'attachment; image='.$fileName);
$response->setHeader('Last-Modified', date('r'));
$response->setHeader('Accept-Ranges', 'bytes');
$response->setHeader('Content-Length', strlen($content));
$response->setHeader('Content-type', $contentType);
$response->setBody($content);
$response->sendResponse();
die;
}
}
Your extended class name is misspelled - Mage_Adminhtml_Controller_action should be Mage_Adminhtml_Controller_Action.
Make sure you:
included the file in bookmarkscontroller.php
put BookMarksController is in the right place

Resources