Cakephp redirection after submission - php

I'm developing an application with Cakephp and I can't find my answer in existing topics...
I have a main menu with several action (Edit/Delete/Add) which is manage sockets. When I edit a socket and I submit my update, my socket is updated correctly BUT my redirection on the main menu doesn't work. The URL stay the same.
For example, I edit socket with id = 2. The application go to '/my/app/sockets/edit/2'. After update and submit, the application should redirect to '/my/app/sockets/index' but it doesn't work.
Below, you can see my code.
SocketsController.php :
public function index($searchCloset = null) {
$this->Paginator->settings = $this->paginate;
if($searchCloset != null) {
$sockets = $this->paginate('Socket', array(
'Closet.name LIKE' => $searchCloset
));
}
else{
$sockets = $this->paginate('Socket');
$searchCloset = '' ;
}
$this->set('sockets',$sockets);
$this->set('closets',$this->Socket->Closet->find('all'));
$this->set('searchCloset',$searchCloset);
}
public function edit($id = null){
// Bad socket management
if (!$id) {
throw new NotFoundException(__('Invalid socket'));
}
$socket = $this->Socket->findByid_socket($id);
if (!$socket) {
throw new NotFoundException(__('Invalid socket'));
}
// if there's a submit
if ($this->request->is(array('post'))) {
$this->Socket->id = $id;
if ($this->Socket->save($this->request->data)) {
// update 'lastchange' column
if($this->updateSocketStatus($this->Socket->id)){
$this->Session->setFlash(__('Your socket has been updated.'));
}
else {
$this->Session->setFlash(__('Unable to create history.'));
}
}
else {
$this->Session->setFlash(__('Unable to update your socket.'));
}
return $this->redirect(array('controller' => 'sockets','action' => 'index'));
}
// send all informations about the socket to the view
$this->set('socket',$socket);
// send closets list to the view (select menu)
$this->set('closets',$this->Socket->Closet->find('list',array(
'fields' => array('Closet.id_closet','Closet.name')
)));
}
edit.ctp :
<h2>Edit socket</h2>
<div><?php
echo $this->Form->create('Socket');
echo $this->Form->input('Socket.name', array(
'label' => 'Socket name :',
'default' => $socket['Socket']['name']
));
echo $this->Form->input('Socket.location', array(
'label' => 'Location :',
'default' => $socket['Socket']['location']
));
echo $this->Form->input('Socket.comment', array(
'label' => 'Comment :',
'default' => $socket['Socket']['comment']
));
echo $this->Form->input('Socket.closet_id',array(
'type' => 'select',
'label' => 'Closet :',
'options' => $closets,
'default' => $socket['Closet']['id_closet']
));
echo $this->Form->end('Save socket');
echo $this->Form->postButton(
'Back',
array('controller' => 'sockets','action' => 'index'),
array(
'id' => 'back_button',
'class' => 'ui-btn ui-btn-inline ui-icon-back ui-btn-icon-left'
)
);
?></div>
I've already search and it could be a cache problem.
Thanks in advance.

Can you force with
$this->redirect($this->referer());
Please, try and comment

Your request checking if-statement is omitted, because is() method accepts param of string type according to documentation.
So you should change line:
if ($this->request->is(array('post'))) { ... }
into:
if ($this->request->is('post')) { ... }

Related

magento saveAction - for beginners

I am a Magento beginner so please bear with me...
I am creating a simple extension for my site to add a custom field to my Tags in adminhtml. The custom field is just a number which I need to identify a specific Z-block (cms block extension) so that I can access it as a widget and show it on the frontend in the Tag "category".
I have created a custom module which is working: I set a field in the form using $fieldset and have extended TagController.php, both of which are being used (I made a simple trial to see whether or not they had been recognized). However, I do not know how to go about saving my custom field to DB (whether amending saveAction is enough, and I haven't done it properly, or if I need to add a custom Model or sql install).
Sorry for the "basic" question but I'm new at this, and have mostly done frontend dev (so my extension knowledge is simply limited).
Thank you to anyone who can help...
Claudia
NEW TAG FORM:
public function __construct()
{
parent::__construct();
$this->setId('tag_form');
$this->setTitle(Mage::helper('tag')->__('Block Information'));
}
/**
* Prepare form
*
* #return Mage_Adminhtml_Block_Widget_Form
*/
protected function _prepareForm()
{
$model = Mage::registry('tag_tag');
$form = new Varien_Data_Form(
array('id' => 'edit_form', 'action' => $this->getData('action'), 'method' => 'post')
);
$fieldset = $form->addFieldset('base_fieldset',
array('legend'=>Mage::helper('tag')->__('General Information')));
if ($model->getTagId()) {
$fieldset->addField('tag_id', 'hidden', array(
'name' => 'tag_id',
));
}
$fieldset->addField('form_key', 'hidden', array(
'name' => 'form_key',
'value' => Mage::getSingleton('core/session')->getFormKey(),
));
$fieldset->addField('store_id', 'hidden', array(
'name' => 'store_id',
'value' => (int)$this->getRequest()->getParam('store')
));
$fieldset->addField('name', 'text', array(
'name' => 'tag_name',
'label' => Mage::helper('tag')->__('Tag Name'),
'title' => Mage::helper('tag')->__('Tag Name'),
'required' => true,
'after_element_html' => ' ' . Mage::helper('adminhtml')->__('[GLOBAL]'),
));
$fieldset->addField('zblock', 'text', array(
'name' => 'zblock_id',
'label' => Mage::helper('tag')->__('Z-Block Id'),
'title' => Mage::helper('tag')->__('Z-Block Id'),
'required' => true,
'after_element_html' => ' ' . Mage::helper('adminhtml')->__('[GLOBAL]'),
));
$fieldset->addField('status', 'select', array(
'label' => Mage::helper('tag')->__('Status'),
'title' => Mage::helper('tag')->__('Status'),
'name' => 'tag_status',
'required' => true,
'options' => array(
Mage_Tag_Model_Tag::STATUS_DISABLED => Mage::helper('tag')->__('Disabled'),
Mage_Tag_Model_Tag::STATUS_PENDING => Mage::helper('tag')->__('Pending'),
Mage_Tag_Model_Tag::STATUS_APPROVED => Mage::helper('tag')->__('Approved'),
),
'after_element_html' => ' ' . Mage::helper('adminhtml')->__('[GLOBAL]'),
));
$fieldset->addField('base_popularity', 'text', array(
'name' => 'base_popularity',
'label' => Mage::helper('tag')->__('Base Popularity'),
'title' => Mage::helper('tag')->__('Base Popularity'),
'after_element_html' => ' ' . Mage::helper('tag')->__('[STORE VIEW]'),
));
if (!$model->getId() && !Mage::getSingleton('adminhtml/session')->getTagData() ) {
$model->setStatus(Mage_Tag_Model_Tag::STATUS_APPROVED);
}
if ( Mage::getSingleton('adminhtml/session')->getTagData() ) {
$form->addValues(Mage::getSingleton('adminhtml/session')->getTagData());
Mage::getSingleton('adminhtml/session')->setTagData(null);
} else {
$form->addValues($model->getData());
}
$this->setForm($form);
return parent::_prepareForm();
}
NEW CONTROLLER:
public function saveAction()
{
if ($postData = $this->getRequest()->getPost()) {
if (isset($postData['tag_id'])) {
$data['tag_id'] = $postData['tag_id'];
}
$data['name'] = trim($postData['tag_name']);
$data['zblock'] = $postData['zblock_id'];
$data['status'] = $postData['tag_status'];
$data['base_popularity'] = (isset($postData['base_popularity'])) ? $postData['base_popularity'] : 0;
$data['store'] = $postData['store_id'];
if (!$model = $this->_initTag()) {
Mage::getSingleton('adminhtml/session')->addError(Mage::helper('adminhtml')->__('Wrong tag was specified.'));
return $this->_redirect('*/*/index', array('store' => $data['store']));
}
$model->addData($data);
if (isset($postData['tag_assigned_products'])) {
$productIds = Mage::helper('adminhtml/js')->decodeGridSerializedInput(
$postData['tag_assigned_products']
);
$model->setData('tag_assigned_products', $productIds);
}
try {
$model->save();
Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')->__('The tag has been saved.'));
Mage::getSingleton('adminhtml/session')->setTagData(false);
if (($continue = $this->getRequest()->getParam('continue'))) {
return $this->_redirect('*/tag/edit', array('tag_id' => $model->getId(), 'store' => $model->getStoreId(), 'ret' => $continue));
} else {
return $this->_redirect('*/tag/' . $this->getRequest()->getParam('ret', 'index'));
}
} catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
Mage::getSingleton('adminhtml/session')->setTagData($data);
return $this->_redirect('*/*/edit', array('tag_id' => $model->getId(), 'store' => $model->getStoreId()));
}
}
return $this->_redirect('*/tag/index', array('_current' => true));
}
The custom field I'm trying to add is "zblock"...thanks and, again, bear with me! :)
First add the field in database table.
For example if you want to add in your custom table.
ALTER TABLE myCustomModuleTable ADD COLUMN 'myCustomField' int(10);
Thenafter, In your controller action take the model object of that table and set the field.
If you are adding data in existing table row:
$value = 6;
$rowInWhichIWantToSave = Mage:getModel('companyname/modulename')->load($rowId);
$rowInWhichIWantToSave->setData('myCustomField',$value)->save();
If you are adding a new row:
$value = 6;
$rowInWhichIWantToSave = Mage:getModel('companyname/modulename');
$rowInWhichIWantToSave->setData('myCustomField',$value)->save();
Hope this helps!!

CMultiFileUpload class not inserting image names on the database yii

I'm working on multi file(images) uploading functionality.
I've tried everything I got.
It's not working.
It's uploading images on the path I specified but not inserting image's names on the table column.
The table's column name is "sample"
Here's the snippet of the view:
$this->widget('CMultiFileUpload', array(
'model' => $model,
'name' => 'sample',
'attribute' => 'sample',
'accept' => 'jpeg|jpg|gif|png',
'duplicate' => 'Duplicate file!',
'denied' => 'Invalid file type',
'remove' => '[x]',
'max' => 20,
));
This is the controller's code the(the function that dealing with the part):
public function actionCreate($project_id) {
$model = new Bid();
$project = $this->loadModel('Project', $project_id);
if (count($project->bids) == 5) {
Yii::app()->user->setFlash('warning', Yii::t('bids', 'This project has already reached its maximum number of bids, so you cannot post a new bid.'));
$this->redirect(array('project/view', 'id' => $project_id));
}
if (!empty($project->bid)) {
Yii::app()->user->setFlash('warning', Yii::t('bids', 'This project has a selected bid already, so you cannot post a new bid.'));
$this->redirect(array('project/view', 'id' => $project_id));
}
if ($project->closed) {
Yii::app()->user->setFlash('warning', Yii::t('bids', 'You cannot add bids as this project has been closed.'));
$this->redirect(array('project/view', 'id' => $project_id));
}
$model->project = $project;
if (isset($_POST['Bid'])) {
$model->attributes = $_POST['Bid'];
$photos = CUploadedFile::getInstancesByName('sample');
if (isset($photos) && count($photos) > 0) {
foreach ($photos as $image => $pic) {
$pic->name;
if ($pic->saveAs(Yii::getPathOfAlias('webroot').'/images/'.$pic->name)) {
// add it to the main model now
$img_add = new Bid();
$img_add->filename = $pic->name;
$img_add->save();
}
else {
}
}
}
$model->project_id = $project->id;
$model->freelancer_id = $this->currentUser->id;
if ($model->save()) {
$this->redirect(array('project/view', 'id' => $project->id, '#' => 'bidslist'));
}
}
$this->render('create', array(
'model' => $model,
));
}
Thanks in Advance.
Please let me know if anyone needs anything else for better understanding.
If i underssot you correctly when you saving the model
$img_add = new Bid();
$img_add->sample = $pic->name;
$img_add->save();

cakephp, save multiple row of the same model

I'm tying to figure out how to save, for example 4 days of schedule in one view, and have each field validation message show if validation fails.
My approach was at first to use $this->SomeModel->saveAll() but couldn't save so I tried another way using foreach and all data is saved (pass validation) but no validation message is shown. if you guys know better way to do this I'm open for any suggestions.
Model
public $validate = array(
'hour_from'=>array(
'some mgs' => array(
'rule' => 'good_hours',
),
),
);
public function good_hours($data) {
//throw new Exception(($data['hour_from'] >= $this->data['Hour']['hour_to']));
if ($data['hour_from'] >= $this->data['Hour']['hour_to']) {
return false;
}
return true;
}
Controller:
if ($this->request->is('post')) {
$all_good = true;
foreach ($this->request->data['Hour'] as $day){
if ($this->Hour->save($day)){
}else {
$all_good = false;
$this->Session->setFlash('hours not saved');
}
}
//if all saves are correct rediredt to index
if ($all_good) {
$this->Session->setFlash(__('Hours saved'));
return $this->redirect(array('action' => 'index'));
}
}
View
foreach ($days as $count => $day):
$form_model ='Hour.'.$count. '.';
?>
<fieldset>
<legend><?php
$day_array = (array) $day;
$day = $day_array['date'];
echo $day;
?></legend>
<?php
echo $this->Form->input($form_model.'type_holiday_id', array(
'label'=> 'Typ urlopu',
'type' => 'select',
'options' => $type_holidays,
'empty' => true
));
echo $this->Form->input($form_model.'hour_from', array('label' => 'od'));
echo $this->Form->input($form_model.'hour_to', array('label' => 'do'));
echo $this->Form->input($form_model.'date', array('type' => 'hidden', 'value' => $day));
echo $this->Form->input($form_model.'subordinate_id', array('type' => 'hidden', 'value' => $user['User']['id']));
echo $this->Form->input($form_model.'supervisor_id', array('type' => 'hidden', 'value' => $current_user['id']));
?>
</fieldset>
Request->data array
Hour(array)
0(array)
type_holiday_id
hour_from 8
hour_to 15
date 2014-01-20
subordinate_id 193
supervisor_id 557
1(array)
type_holiday_id
hour_from 7
hour_to 14
date 2014-01-21
subordinate_id 193
supervisor_id 557
Ok i found solution, and everything works perfectly now in controller i needed to change save to saveAll, function add in Controller should look like this:
if ($this->request->is('post')) {
if ($this->Hour->saveAll($this->request->data['Hour'], Array('validate' => 'first', 'deep' => true))){ <--- most important is that data['Hour']
$this->Session->setFlash(__('Godziny robocze zapisane'));
return $this->redirect(array('action' => 'index'));
} else{
$this->Session->setFlash('Godziny robocze nie zostały zapisane.');
}
}

Cakephp AuthComponent: Login successfull despite wrong password

I'm running a 2.2.2 CakePHP Application, everything works as desired. Now I'm developing a Android App for it and therefore need to create the interfaces between those two apps. That's why I need to login users manually. So I created a whole new controller, the AndroidController, in order to bundle everything at one place. First thing to do would be the Login-Action. So I setup the following controller:
<?php
App::uses('AppController', 'Controller');
/**
* Android Controller
*
* #package app.Controller
*/
class AndroidController extends AppController {
public $components = array('RequestHandler','Auth');
public $uses = array('User');
public function beforeFilter() {
$this->Auth->allow();
}
public function login() {
//For testing purposes
$postarray = array('_method' => 'POST','data' => array('User' => array('email' => 'user#gmail.com', 'password' => 'THISisDEFINITELYaWRONGpassword')));
$id = $this->tryToGetUserID($postarray['data']['User']['email']);
if($id == 0){
//return Error json, unknown User
$this->set('result', array(
'tag' => 'login',
'success' => 0,
'error' => 1,
'error_msg' => 'Unknown User'
));
}else{
// if ($this->request->is('post')) {
$postarray['data']['User'] = array_merge($postarray['data']['User'], array('id' => $id));
$this->User->id = $id;
if ( $this->Auth->login($postarray['data']['User'])) {
// Login successfull
$this->User->saveField('lastlogin', date(DATE_ATOM));
$user = $this->User->find('all', array(
'recursive' => 0, //int
'conditions' => array('User.id' => $id)
));
$loggedInUser = array(
'tag' => 'login',
'success' => 1,
'error' => 0,
'uid' => '??',
'user' => array(
'name' => $user['0']['User']['forename'].' '.$user['0']['User']['surname'],
'email' => $user['0']['User']['email'],
'created_at' => $user['0']['User']['created'],
'updated_at' => $user['0']['User']['lastlogin']
)
);
$this->set('result', $loggedInUser);
} else {
// Login failed
$this->set('result', array(
'tag' => 'login',
'success' => 0,
'error' => 2,
'error_msg' => 'Incorrect password!'
));
}
// }
}
}
public function tryToGetUserID($email = null) {
$user = $this->User->find('list', array(
'conditions' => array('User.email' => $email)
));
if(!empty($user)){
return array_keys($user)['0'];
}else{
return 0;
}
}
}
You need to know that this method will be called as a POST request, but for testing purposes I manually created a post-array. In future I will use the $_POST array.
So, what happens: The Login with a registered user works, but it works every time! Even though the password is wrong or missing! The program never reaches the part in code with the "Login failed" comment.
Am I missing something here..?
Thank you!
If you take a closer look at the documentation you will notice that AuthComponent::login() will ...
In 2.x $this->Auth->login($this->request->data) will log the user in with whatever data is posted

The Errors messages in edit actions, doesn't appear

I have my validation rules in model, and everything is fine. It validates like I want to, but in the Edit actions, although it not validates, don't show me de red error marks under textbox.
Any tip?
Thanks.
The Model Code(Model name is Safpercent):
var $validate = array(
'sequencia' => array(
'must_be_numeric' => array(
'rule' => 'Numeric',
'message' => 'Number Field: insert only numbers.'
)
),
);
View Text Box:
echo $form->input('Safpercent.sequence', array('id' => 'sequence', 'options' => $criteria, 'label' => false, 'div' => false, 'style' => 'width: 300px'));
Controller Code:
function edit($id = null) {
$criteria = $this->Safpercent->Safrequirement->find('list', array('fields' => array('Safrequirement.sequencia', 'Safrequirement.descricao'), 'conditions' => array('Safrequirement.tipo' => 'ILC')));
$this->set('criteria', $criteria);
if (!$id && empty($this->data)) {
$this->Session->setFlash(RecordNotValid, 'flash_failure');
$this->redirect(array('controller' => 'safpercents', 'action'=>'index'));
}
if (!empty($this->data)) {
$sequencia = $this->data['Safpercent']['sequencia'];
if($this->data['Safpercent']['tipo'] == ''){$tipo = 'ILC';}else{$tipo = $this->data['Safpercent']['tipo'];}
$encontro = $this->Safpercent->Safrequirement->find('all', array('conditions' => array('sequencia' => $sequencia, 'tipo' => $tipo)));
if($encontro <> array()){
if ($this->Safpercent->save($this->data)) {
$this->Session->setFlash(RecordSaved, 'flash_success');
$this->redirect(array('controller' => 'safpercents', 'action'=>'index'));
}else{
$this->Session->setFlash(RecordNotSaved, 'flash_failure');
}
}else{
$this->Session->setFlash('A Sequência que tentou Inserir não existe. Verifique a tabela de novo, por favor.');
}
}
if (empty($this->data)) {
$this->data = $this->Safpercent->read(null, $id);
$this->set('id', $id);
}
$this->set('cod_percent',$this->Safpercent->read(null, $id));
}
(Portuguese Variables and Text in some cases)
Try
debug($this->Safpercent->validationErrors)
and see if it shows any errors.
I see now. In your controller, you are using the sequencia field that you are validating, but not doing any validation at this stage. It passes a non-number to the find query, which then returns an error or something, and the save never gets called?
Before you do this:
$sequencia = $this->data['Safpercent']['sequencia'];
You should check that the data validates, by calling this:
$this->ModelName->set($this->data);
if ($this->ModelName->validates()) {
... //do your business here
So basically, change:
if (!empty($this->data)) {
to:
$this->Safpercent->set($this->data);
if (!empty($this->data) && $this->Safpercent->validates()) {

Categories