cakephp, save multiple row of the same model - php

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.');
}
}

Related

Cakephp redirection after submission

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')) { ... }

ASK CakePHP - work with password field

I have searched many topic in here but I can't solve my problem. Please check this for me.
I made the register page and when I made for password field...
I had users_controller.php like:
class UsersController extends AppController
{
var $name = "Users";
var $helpers = array('Paginator','Html');
var $paginate = array();
//Doi tuong component de thuc thi thao tac login
public $components = array
(
'Auth' => array
(
'authorize' => 'controller',
'loginRedirect' => array
(
'admin' => FALSE,
'controller' => 'users',
'action' => 'dashboard'
),
'loginError' => 'Invalid account',
'authError' => 'You don\'t have permission'
),
'Session'
);
//Ham loc cac user truoc khi truy cap trang
public function beforeFilter()
{
parent::beforeFilter();
$this->Auth->allow('add');
$this->Auth->allow('viewuserall');
}
//Ham them moi user
public function add()
{
$this->layout = 'TDCake';
$this->User->set($this->data);
if($this->User->valid_user() == TRUE)
{
if(!empty($this->data))
{
$this->User->create();
if($this->User->save($this->data))
{
$this->Session->setFlash('User has been created!');
$this->redirect(array('action'=>'login'));
}
else
{
$this->Session->setFlash('Please correct the errors');
}
};
}
else
{
$this->Session->setFlash("Your data is NOT available");
}
}
//Ham login cho user
public function login()
{
$this->layout = 'TDCake';
if
(
!empty($this->data) &&
!empty($this->Auth->data['User']['username'])&&
!empty($this->Auth->data['User']['password'])
)
{
$user = $this->User->find
(
'first',array
(
'conditions'=>array
(
'User.email'=>$this->Auth->data['User']['username'],
'User.password'=>$this->Auth->data['User']['password']
),
'recursive' => -1
)
);
if(!empty($user) && $this->Auth->login($user))
{
if($this->Auth->autoRedirect)
{
$this->redirect($this->Auth->redirect());
}
}
else
{
$this->Session->setFlash
(
$this->Auth->loginError,
$this->Auth->flashElement,
array(),'auth'
);
}
}
}
//Ham logout cho user
public function logout()
{
$this->redirect($this->Auth->logout());
}
//Ham gi cha biet, de do tinh sau =))
public function dashboard()
{
$this->layout = 'TDCake';
}
//Ham view cac user khong dieu kien trong table users
function viewuserall()
{
$this->layout = 'TDCake';
$this->paginate=array
(
'limit' => 10,
'order' => array('id' => 'asc'),
);
$data = $this->paginate("User");
$this->set("data",$data);
}
}
User.php in Model is:
class User extends AppModel
{
var $name = "User";
var $validate = array();
function validate_passwords()
{
if($this->data[$this->alias]['pass'] == $this->data[$this->alias]['rpass'])
{
return $this->data[$this->alias]['pass'] = $this->data['User']['password'];
}
else return FALSE;
}
function valid_user()
{
$this->validate = array
(
//Kiem tra username truoc khi add
'username' => array
(
'rule01_notEmpty' => array
(
'rule' => 'notEmpty',
'message' => 'You must enter your Username !'
),
'rule02_max16' => array
(
'rule' => array('maxLength', 20),
'message' => 'Your Username must be less than 20 chars !'
),
'rule03_exists' => array
(
'rule' => 'isUnique',
'message' => 'Your Username have already existed !'
)
),
//Kiem tra email truoc khi add
'email' => array
(
'rule01_notEmpty' => array
(
'rule' => 'notEmpty',
'message' => 'You must enter your Email !'
),
'rule02_exists' => array
(
'rule' => 'isUnique',
'message' => 'Your Email have already existed !'
),
'rule03_emailtype' => array
(
'rule' => 'email',
'message' => 'You didn\'t type a email !'
)
),
//Kiem tra password truoc khi add
'pass' => array
(
'length' => array
(
'rule' => array('between', 6, 20),
'message' => 'Your password must be between 8 and 40 characters.',
),
),
'rpass' => array
(
'length' => array
(
'rule' => array('between', 6, 20),
'message' => 'Your password must be between 8 and 40 characters.',
),
'compare' => array
(
'rule' => 'validate_passwords',
'message' => 'The passwords you entered do not match.',
)
)
);//End this->validate=array
if($this->validates($this->validate==TRUE))
{
return TRUE;
}
else
{
return FALSE;
}
}//End function valid_user
}
add.ctp is
echo $this->Session->flash('auth');
echo $this->Form->create();
echo $this->Form->input('username', array('label' => ('Username')));
echo $this->Form->input('email', array('label' => ('Email')));
echo $this->Form->input('pass', array('label' => ('Password'),'type' => 'password', 'value' => ''));
echo $this->Form->input('rpass', array('label' => ('Repeat Password'), 'type' => 'password', 'value' => ''));
echo $this->Form->input('firstname', array('label' =>('Firstname')));
echo $this->Form->input('lastname', array('label' =>('Lastname')));
echo $this->Form->input('dob', array('label' =>('DOB'),'type' => 'date'));
echo $this->Form->end('Register');
Explanation:
So, in this case, I can validate 2 Password Fields (empty, not equal,...), but it can't insert to the database. That mean it INSERTED current data into the DB but password column in DB is EMPTY. In database, my password column name "password" also.
In another case, I change the name "pass" into "password" for the
echo $this->Form->input('pass', array(
Of course, I have changed any place related to...
and in that case, it can be inserted the password but can not validate anything.
I am too confused about this...I don't know what I am wrong is....can anybody help me.
I am not sure why you are doing an assignment in your validate function:
return $this->data[$this->alias]['pass'] = $this->data['User']['password'];
And even if you were doing an assignment, it should be:
return $this->data['User']['password'] = $this->data[$this->alias]['pass'];
Realize that the field "password" is getting the value from $this->data which has the information, not the other way around.
Also. It would be better (in terms of clarity), to break this code in two lines.
$this->data['User']['password'] = $this->data[$this->alias]['pass'];
return $this->data['User']['password'];
You should name your field the exact name "password" if that's what it is called in the database AND if you are not explicitly assigning it.
Your add function is not doing the above, and further more, as a best practice, you should be hashing the password.
See the CakePHP book on tutorials and examples.
Take some time to go through it with all the snippets and recommendations. And don't forget the standards. :)

Validation messages are not showing in cakephp 2.4.x

Here is my validation rule in User.php
public $validate = array(
'username' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'User name is required'
),
'alphaNumeric'=>array(
'rule' => 'alphaNumeric',
'required' => true,
'message' => 'Alphabets and numbers only'
)
))
and this is my view page code
<?php
echo $this->Form->create('User');
echo $this->Form->input('username', array('label' => 'Username'));
echo $this->Form->input('email', array('label' => 'Email'));
echo $this->Form->input('password', array('label' => 'Password'));
echo $this->Form->submit('Sign Up');
echo $this->Form->end();
?>
Here is my controller code
public function register() {
$this->layout = 'starter';
//debug($this->validationErrors);
if ($this->request->is('post')) {
if ($this->User->validates()) {
$this->User->save($this->request->data);
$this->Session->setFlash(__('Please login your account'));
$this->redirect('/users/login');
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
}
but validation message is not showing. What is wrong in my code?...
Your code is wrong.
if ($this->request->is('post')) {
if ($this->User->validates()) {
$this->User->save($this->request->data);
this is not how it could ever work as the data is not passed prior to validation.
You need to first pass the data, then validate, then optionally save (or save and validate together):
if ($this->request->is('post')) {
if ($this->User->save($this->request->data)) {}
or, careful not to retrigger validation twice:
if ($this->request->is('post')) {
$this->User->set($this->request->data);
if ($this->User->validates()) {
$success = $this->User->save(null, array('validate' => false));
But that is documented.
The latter only makes sense if you really need to do this in two steps.
In your comment you have written you have changed layout page.It may you miss
<?php echo $this->Session->flash(); ?>
this line.Add this line in your view/layouts/yourlayout.ctp file.
Disable HTML5 required in your view page code
<?php
echo $this->Form->create('User');
echo $this->Form->input('username', array('label' => 'Username','required'=>'false'));
echo $this->Form->input('email', array('label' => 'Email','required'=>'false'));
echo $this->Form->input('password', array('label' => 'Password','required'=>'false'));
echo $this->Form->submit('Sign Up');
echo $this->Form->end();
?>

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

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