Magento Saving Multiselect Value on Custom Model - magento

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
}
}

Related

delete a particular row on clicking the edit link in magento

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('*/*/');
}

Delete website in Magento can't delete store and store view

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

ModX Revo: Get Current Webuser or Manager session

How can I get the the number of all logged webuser (or manager, but not all types together). Is it possible with ModX API? Or is it necessary to inspect the DB table modx_session - but how is "data" column to readable?
I want to show a user counter, who is online (like in a forum).
Look at code in https://github.com/modxcms/revolution/blob/master/manager/controllers/default/dashboard/widget.grid-online.php - this is what you want.
I will try to solve it myself. Kind of solution:
Write a plugin that track events and persist it in database or somewhere else: OnWebLogin and OnWebLogout. Then read the count of logged in users.
Created a db table "modx_weblogin_session" (manually) userid, timestamp.
Created a Plugin:
if (isset($modx) && isset($user)) {
$eventName = $modx->event->name;
$isBackend = ($modx->context->key == 'mgr') ? true : false;
$errorMsg = '';
$userId = $user->get('id');
$output = 'WebLoginCountSession-Plugin: ' . $eventName . ' user-id: ' . $userId;
$logout = function ($userId) {
global $modx;
//Custom Mysqli Class
if (MySQLiDB::isConnected()) {
$mysqli = MySQLiDB::getConnection();
if ($mysqli instanceof mysqli) {
try {
$sql = "DELETE FROM `modx_weblogin_session` WHERE userid = ?";
$prep_state = $mysqli->prepare($sql);
$prep_state->bind_param('i', $userId);
$prep_state->execute();
} catch (Exception $e) {
//$modx->log(modX::LOG_LEVEL_ERROR, ...)
}
}
}
};
$login = function ($userId) {
global $modx;
if (MySQLiDB::isConnected()) {
$mysqli = MySQLiDB::getConnection();
if ($mysqli instanceof mysqli) {
try {
$sql = "REPLACE INTO `modx_weblogin_session` (`userid`) VALUES (?)";
$prep_state = $mysqli->prepare($sql);
$prep_state->bind_param('i', $userId);
$prep_state->execute();
} catch (Exception $e) {
//$modx->log(modX::LOG_LEVEL_ERROR, ...)
}
}
}
};
if (!$isBackend && !empty($userId)) {
switch ($eventName) {
case ('OnWebLogin'):
$output .= ' - login';
$login($userId);
break;
case ('OnWebLogout'):
$output .= ' - logout';
$logout($userId);
break;
}
}
if ($debug === true) {
return $output . ' ' . $errorMsg;
}
}

Can't save empty string into field value

I need to change value of NULL-field to empty string (in sales_flat_order table).
I tried this code:
$orders = Mage::getModel('sales/order')->getCollection()
->addAttributeToFilter('created_at', array('to' => $endDate))
->addAttributeToFilter('status', array('eq' => Mage_Sales_Model_Order::STATE_COMPLETE));
foreach ($orders as $order) {
$comment = $order->getCustomerNote();
if (is_null($comment)) {
$order->setData('customer_note', '');
try {
$order->save();
} catch (Exception $e){
echo $e->getMessage(); exit;
}
}
}
But in base I see still NULL value in this filed.
If I change empty string to any non-empty it works fine.
How can I update NULL value field to empty string?
Thanks.
The empty string is set to null in Varien_Db_Adapter_Pdo_Mysql::prepareColumnValue():
case 'varchar':
case 'mediumtext':
case 'text':
case 'longtext':
$value = (string)$value;
if ($column['NULLABLE'] && $value == '') {
$value = null;
}
break;
To reset the column value to empty string, add this in your resource model:
protected function _prepareDataForSave(Mage_Core_Model_Abstract $object)
{
$data = parent::_prepareDataForSave($object);
if ($object->getData('your_column_name') === '') {
$data['your_column_name'] = '';
}
return $data;
}
I tried and it's normal.
$order->setData('customer_note', new Zend_Db_Expr(''));
try {
$order->save();
} catch (Exception $e){
echo $e->getMessage(); exit;
}

Magento: Adminhtml form “Image” Field

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();
}
}

Resources