Magento - Hidden value not set in grid serializer - magento

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>

Related

How can i display error messages in CodeIgniter

Controller:
public function add_year() {
$session_id = $this->session->userdata('id');
if (!empty($session_id)) {
$this->form_validation->set_rules('year_name', 'Year Name', 'required');
if ($this->form_validation->run() == FALSE) {
$data = array(
'page_title' => 'Add Year',
'page_name' => 'year/add_year',
'admin_username' => $this->session->userdata('username')
);
$this->load->view('admin/template', $data);
} else {
$this->year_model->insert($_POST);
redirect('admin/Year');
}
} else {
redirect('admin/Login');
}
}
Model:
public function insert($data) {
$result = $this->db->get_where('year', array('year_name' => $data['year_name']))->row_array();
if (empty($result)) {
$insert_data = array('year_name' => $data['year_name']);
$this->db->insert('year', $insert_data);
} else {
$error = "Year Name Already Exits";
return $error;
}
}
View:
<div class="text-danger">
//display error message
</div>
MY Question: How can i display model error message in view............................................................
use below updated code for your solution
Model :
public function insert($data) {
$result = $this->db->get_where('year', array('year_name' => $data['year_name']))->row_array();
if (empty($result)) {
$insert_data = array('year_name' => $data['year_name']);
$this->db->insert('year', $insert_data);
} else {
$error = "Year Name Already Exits";
return $error;
}
return TRUE;
}
add_year
public function add_year() {
$session_id = $this->session->userdata('id');
if (!empty($session_id)) {
$this->form_validation->set_rules('year_name', 'Year Name', 'required');
if ($this->form_validation->run() == FALSE) {
$data = array(
'page_title' => 'Add Year',
'page_name' => 'year/add_year',
'admin_username' => $this->session->userdata('username')
);
$this->load->view('admin/template', $data);
} else {
$ret = $this->year_model->insert($_POST);
if(!$ret){
$this->session->set_flashdata('error_view',$ret);
}
redirect('admin/Year');
}
} else {
redirect('admin/Login');
}
}
in view
<?php
echo $this->session->flashdata('error_view');
?>
Use this Code
Note : please set your table and field name in is_unique function !
Controller:
public function add_year() {
$session_id = $this->session->userdata('id');
if (!empty($session_id))
{
$this->form_validation->set_rules('year_name', 'Year Name', 'required|is_unique[table_name.field_name]');
if ($this->form_validation->run() == FALSE) {
$res['error']='<div class="alert alert-danger">'.validation_errors().'</div>';
}
else {
if( $this->year_model->insert($_POST)==true)
{
redirect('admin/Year');
}
}
} else
{
redirect('admin/Login');
}
}
Model
public function insert($data) {
$result = $this->db->get_where('year', array('year_name' => $data['year_name']))->row_array();
if (empty($result)) {
$insert_data = array('year_name' => $data['year_name']);
$this->db->insert('year', $insert_data);
return true;
} else {
return false;
}
}
View File
<div class="panel-body">
<?php if(validation_errors()) { ?>
<div class="alert alert-danger"><?php echo validation_errors(); ?></div>
<?php } ?>

Return false limits multiple error message to one?

On my multiple upload library, I have a set error function.
On my upload function I use a in_array to check file extensions. If the in_array detects error it displays multiple error messages correct.
The problem I am having is for some reason when I use return FALSE; under the $this->set_error('file_extension_not_allowed') then will on display one message. Not sure why return FALSE limits error messages.
Question: How is it possible to use my return false but be able to display multiple message correct.
<?php
class Multiple_upload {
public $set_errors = array();
public function __construct($config = array()) {
$this->CI =& get_instance();
$this->files = $this->clean($_FILES);
empty($config) OR $this->set_config($config);
}
public function set_config($config) {
foreach ($config as $key => $value) {
$this->$key = $value;
}
return $this;
}
public function upload($field = 'userfile') {
$allowed_extension = explode('|', $this->allowed_types);
if (empty($this->upload_path)) {
$this->set_error('upload_path_not_set', 'upload_path_check');
return FALSE;
}
if (!realpath(FCPATH . $this->upload_path)) {
$this->set_error('upload_path_in_correct', 'location_check');
return FALSE;
}
if (!empty($this->files[$field]['name'][0])) {
foreach ($this->files[$field]['name'] as $key => $value) {
$this->file_name = $this->files[$field]['name'][$key];
$get_file_extension = explode('.', $this->files[$field]['name'][$key]);
$this->get_file_extension_end = strtolower(end($get_file_extension));
$array_1 = array(
$allowed_extension,
);
$array_2 = array(
$get_file_extension[1],
);
if (!in_array($array_2, $array_1)) {
$this->set_error('file_extension_not_allowed', 'extension_check');
return FALSE;
}
}
return $this;
}
}
public function set_error($message, $type) {
$this->CI->lang->load('upload', 'english');
$this->error_message[] = $this->CI->lang->line($message);
return $this;
}
public function display_error_messages($open_tag = '<p>', $close_tag = '</p>') {
foreach($this->error_message as $msg) {
var_dump($msg);
}
}
public function clean($data) {
if (is_array($data)) {
foreach ($data as $key => $value) {
unset($data[$key]);
$data[$this->clean($key)] = $this->clean($value);
}
} else {
$data = htmlspecialchars($data, ENT_COMPAT, 'UTF-8');
}
return $data;
}
}
Maybe this can help...
public function upload($field = 'userfile')
{
$allowed_extension = explode('|', $this->allowed_types);
if (empty($this->upload_path))
{
$this->set_error('upload_path_not_set', 'upload_path_check');
return FALSE;
}
if (!realpath(FCPATH . $this->upload_path))
{
$this->set_error('upload_path_in_correct', 'location_check');
return FALSE;
}
if (!empty($this->files[$field]['name'][0]))
{
$check_error = 0;//added this
foreach ($this->files[$field]['name'] as $key => $value)
{
$this->file_name = $this->files[$field]['name'][$key];
$get_file_extension = explode('.', $this->files[$field]['name'][$key]);
$this->get_file_extension_end = strtolower(end($get_file_extension));
$array_1 = array(
$allowed_extension,
);
$array_2 = array(
$get_file_extension[1],
);
if (!in_array($array_2, $array_1))
{
$this->set_error('file_extension_not_allowed', 'extension_check');
$check_error++;
}
}
if($check_error > 0 )
{
return FALSE;
}
return $this;
}
}

Cakephp does not expire page after logout

I am learning cakePHP, I have written the example of the manual, the problem is with the method logout of the UsersController, when I press the link logout the application is redirected to the login form, but the back button of the browser allows to return to a page that requires an authenticated user, an example about of this occurs with the page to add posts
Source Code
UsersController.php
<?php
class UsersController extends AppController {
public function beforeFilter() {
parent::beforeFilter();
// Allow users to register and logout.
$this->Auth->allow('add', 'logout');
}
public function add() {
if ($this->request->is('post')) {
$this->User->create();
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved'));
return $this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(
__('The user could not be saved. Please, try again.')
);
}
}
public function edit($id = null) {
$this->User->id = $id;
if (!$this->User->exists()) {
throw new NotFoundException(__('Invalid user'));
}
if ($this->request->is('post') || $this->request->is('put')) {
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved'));
return $this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(
__('The user could not be saved. Please, try again.')
);
} else {
$this->request->data = $this->User->read(null, $id);
unset($this->request->data['User']['password']);
}
}
public function delete($id = null) {
$this->request->onlyAllow('post');
$this->User->id = $id;
if (!$this->User->exists()) {
throw new NotFoundException(__('Invalid user'));
}
if ($this->User->delete()) {
$this->Session->setFlash(__('User deleted'));
return $this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(__('User was not deleted'));
return $this->redirect(array('action' => 'index'));
}
public function login() {
//$this->layout=null;
if ($this->request->is('post')) {
if ($this->Auth->login()) {
$this->Session->write('userid',$this->Auth->user('id'));
//$this->Session->write('userid',AuthComponent::user('id'));
return $this->redirect($this->Auth->redirect());
}
$this->Session->setFlash(__('Invalid username or password, try again'));
}
}
public function logout() {
$this->Session->delete('userid');
$this->Session->destroy();
return $this->redirect($this->Auth->logout());
}
}
?>
PostsController.php
<?php
class PostsController extends AppController {
public $helpers = array('Html', 'Form');
public function isAuthorized($user) {
// All registered users can add posts
if ($this->action === 'add') {
return true;
}
// The owner of a post can edit and delete it
if (in_array($this->action, array('edit', 'delete'))) {
$postId = (int) $this->request->params['pass'][0];
if ($this->Post->isOwnedBy($postId, $user['id'])) {
return true;
}
}
return parent::isAuthorized($user);
}
public function index() {
if ($this->Session->read('userid')) {
$this->set('posts', $this->Post->find('all', array('conditions' => array('Post.user_id' => AuthComponent::user('id')))));
} else {
$this->set('posts', $this->Post->find('all'));
}
}
public function view($id = null) {
if (!$id) {
throw new NotFoundException(__('Invalid post'));
}
$post = $this->Post->findById($id);
if (!$post) {
throw new NotFoundException(__('Invalid post'));
}
$this->set('post', $post);
}
public function add() {
if ($this->Auth->loggedIn()) {
if ($this->request->is('post')) {
$this->request->data['Post']['user_id'] = $this->Auth->user('id');
$this->Post->create();
if ($this->Post->save($this->request->data)) {
$this->Session->setFlash(__('Your post has been saved.'));
return $this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(__('Unable to add your post.'));
}
} else {
return $this->redirect(array('controller' => 'users', 'action' => 'login'));
}
}
public function edit($id = null) {
if (!$id) {
throw new NotFoundException(__('Invalid post'));
}
$post = $this->Post->findById($id);
if (!$post) {
throw new NotFoundException(__('Invalid post'));
}
if ($this->request->is(array('post', 'put'))) {
$this->Post->id = $id;
if ($this->Post->save($this->request->data)) {
$this->Session->setFlash(__('Your post has been updated.'));
return $this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(__('Unable to update your post.'));
}
if (!$this->request->data) {
$this->request->data = $post;
}
}
public function delete($id) {
if ($this->request->is('get')) {
throw new MethodNotAllowedException();
}
if ($this->Post->delete($id)) {
$this->Session->setFlash(
__('The post with id: %s has been deleted.', h($id))
);
return $this->redirect(array('action' => 'index'));
}
}
}
?>
AppController.php
<?php
App::uses('Controller', 'Controller');
/**
* Application Controller
*
* Add your application-wide methods in the class below, your controllers
* will inherit them.
*
* #package app.Controller
* #link http://book.cakephp.org/2.0/en/controllers.html#the-app-controller
*/
class AppController extends Controller {
public $components = array(
'Session',
'Auth' => array(
'loginRedirect' => array('controller' => 'posts', 'action' => 'index'),
'logoutRedirect' => array('controller' => 'users','action' => 'login'),
'authorize' => array('Controller') // Added this line
)
);
public function isAuthorized($user) {
// Admin can access every action
if (isset($user['role']) && $user['role'] === 'admin') {
return true;
}
// Default deny
return false;
}
public function beforeFilter() {
$this->Auth->allow('index','view','login','helloajax');
}
}
?>
please check beforeFilter function from your AppController
you have explicitly allowed some action through AuthComponent
public function beforeFilter() {
$this->Auth->allow('index','view','login','helloajax');
}
Please verify actions you want to allow for unauthenticated visitor.
Since AppController is extended by every single controller in cakephp. Which turn out to like you are allowing unauthenticated users to access your index,view,login etc actions for every single controller you have created or will create.

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

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