i created a edit link and want to edit the row content and save the changes to database using magento. i created the delete link it works properly
if( $this->getRequest()->getParam('class') > 0 ) {
try {
$model = Mage::getModel('test/test');
$model->setId($this->getRequest()->getParam('class'))
->setTitle('new title')->setUpdateTime(strtotime('now'))->save();
Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')->__('Item was successfully edited'));
$this->_redirect('*/*/');
} catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
$this->_redirect('*/*/');
}
}
If you want to delete row then add below action in the controller hope this helps.
public function deleteAction() {
if( $this->getRequest()->getParam('class') > 0 ) {
try {
$model = Mage::getModel('test/test');
$model->setId($this->getRequest()->getParam('class'))
->delete();
Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')->__('Item was successfully deleted'));
$this->_redirect('*/*/');
} catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
}
}
$this->_redirect('*/*/');
}
Related
I have a controller extended from Mage_Adminhtml_System_StoreController, below is the action I overwrite:
public function deleteWebsitePostAction()
{
$multiWebEnable = Mage::getStoreConfig('web/multi_web_general/multi_web');
$itemId = $this->getRequest()->getParam('item_id');
if (!$model = Mage::getModel('core/website')->load($itemId)) {
$this->_getSession()->addError(Mage::helper('core')->__('Unable to proceed. Please, try again'));
$this->_redirect('*/*/');
return;
}
if (!$model->isCanDelete()) {
$this->_getSession()->addError(Mage::helper('core')->__('This website cannot be deleted.'));
$this->_redirect('*/*/editWebsite', array('website_id' => $model->getId()));
return;
}
$this->_backupDatabase('*/*/editWebsite', array('website_id' => $itemId));
try {
$model->delete();
if ($multiWebEnable) {
$websiteCode = $model->getCode();
$websiteDir = BP . DS . 'mpshop' . DS . $websiteCode;
if (is_dir($websiteDir)) {
$objects = scandir($websiteDir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if (filetype($websiteDir . DS . $object) == "dir") {
rmdir($websiteDir . DS . $object);
} else {
unlink($websiteDir . DS . $object);
}
}
}
reset($objects);
rmdir($websiteDir);
}
}
$this->_getSession()->addSuccess(Mage::helper('core')->__('The website has been deleted.'));
$this->_redirect('*/*/');
return;
} catch (Mage_Core_Exception $e) {
$this->_getSession()->addError($e->getMessage());
} catch (Exception $e) {
$this->_getSession()->addException($e, Mage::helper('core')->__('Unable to delete website. Please, try again later.'));
}
$this->_redirect('*/*/editWebsite', array('website_id' => $itemId));
}
I tried to comment out this function in my controller but the issue still there.
I'm confused with this. I need to know why this can happens, give me some suggestion... THanks
Any help will be appreciated.
Well,
After research deep inside, I realise one foreign key was missing between core_website table and core_store, core_store_group.
The solution here is download Magento Database Repair Tool which available to download at Magento homepage.
Hope this help.
Note that deleting websites can only be done from admin panel which is why the standalone script has that.
( Placed in root/var folder )
This will delete your website from a standalone file:
require_once( 'app/Mage.php' );
umask(0);
Mage::app( 'admin' );
function deleteWebsitePostAction()
{
try
{
$sWebsiteId = 'a';
$oWebsite = Mage::getModel( 'core/website' )->load( $sWebsiteId );
if( !empty( $oWebsite->getId() ) )
{
$oWebsite->delete();
}
}
catch( Exception $oException )
{
Mage::logException( $oException );
}
}
deleteWebsitePostAction();
To implement this in the admin panel ensure that you are submitting the correct variable to the controller, in this case I chose the name website_id so your form should have an somewhere.
public function deleteWebsitePostAction()
{
try
{
$sWebsiteId = $this->getRequest()->getParam( 'website_id' );
$sWebsiteId = 'a';
$oWebsite = Mage::getModel( 'core/website' )->load( $sWebsiteId );
if( !empty( $oWebsite->getId() ) )
{
$oWebsite->delete();
}
else
{
$this->_getSession()->addError( 'Unable to proceed. Please, try again' );
$this->_redirect( '*/*/' );
return;
}
}
catch( Exception $oException )
{
Mage::logException( $oException );
$this->_getSession()->addError( 'Unable to delete website. Please, try again' );
}
}
Disable your cache from Admin> System> Cache management
Refresh your cache and check again.
You can also delete your cache from cache management or [root]/var/cache
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
}
}
i need to massupdate customer streetaddress using magento. for this i wrote bultupdate function in customer grid controller. here is the query but it is not working. how can i change this query to update street address using customerid
public function massUpdateAction()
{
$customerIds = $this->getRequest()->getParam('customer');
$street_type = $this->getRequest()->getParam('street');
if (!is_array($customerIds)) {
$this->_getSession()->addError($this->__('Please select customer(s).'));
} else {
if (!empty($customerIds)) {
try {
foreach ($customerIds as $customerId) {
Mage::getSingleton('customer/address')
->updateAttributes($customerIds, array('billing_street_full' => $street_type), $storeId);
}
$this->_getSession()->addSuccess(
$this->__('Total of %d record(s) have been Updated.', count($customerIds))
);
} catch (Exception $e) {
$this->_getSession()->addError($e->getMessage());
}
}
}
$this->_redirect('*/*/index');
}
Try this:
try {
foreach ($customerIds as $customerId) {
$addresses = Mage::getModel('customer/customer')->load($customerId)->getAddressesCollection();
foreach ($addresses as $address) {
$address->setData('billing_street_full', $street_type)->save();
}
}
$this->_getSession()->addSuccess(
$this->__('Total of %d record(s) have been Updated.', count($customerIds))
);
} catch (Exception $e) {
$this->_getSession()->addError($e->getMessage());
}
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
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();
}
}