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();
?>
Related
I am getting this error in CakePHP from my forgot_password method which is in UsersController.
public function forgot_password() {
$this->layout = 'signin';
if (!empty($this->data)) {
$user = $this->User->findByUsername($this->data['User']['username']);
if (empty($user)) {
$this->Session->setflash('Sorry, the username entered was not found.');
$this->redirect('/users/forgot_password');
}else{
$user = $this->__generatePasswordToken($user);
if ($this->User->save($user) && $this->__sendForgotPasswordEmail($user['User']['id'])) {
$this->Session->setflash('Password reset instructions have been sent to your email address.
You have 24 hours to complete the request.');
$this->redirect('/users/login');
}
}
}
}
Here is the forgot_password.ctp file
<header class="panel-heading text-center">
<strong>Forget Password</strong>
</header>
<h3>Enter Your Username</h3>
<?php
echo $this->Form->create('User', array('action' => 'forgot_password', 'id' => 'web-form', 'class'=>'panel-body wrapper-lg'));
echo $this->Form->input('username', array('label' => 'Username', 'between'=>'<br />', 'type'=>'text', 'div' => 'form-group','class' => 'form-control input-lg'));
?>
<div class="form-group">
<?php echo $this->Form->submit('Send Password Reset Instructions', array('class' => 'btn btn-primary btn-techuz', 'id' => 'submit')); ?>
</div>
<?php echo $this->Form->end(); ?>
It's not necessary to specify the form action if it's same as the view. In case you'd like to redirect to a different action, try this:
<?php
echo $this->Form->create('User', array(
'url' => array(
'controller' => 'users','action' => 'forgot_password'
),
'id' => 'web-form',
'class' =>'panel-body wrapper-lg'
)
); ?>
If you follow the convention and define this "url" index as an array of controller and index, you're bound to be safe and deprived of errors.
Peace! xD
Got the solution, no need to mention 'action' => 'forgot_password' in forgot_password.ctp file until it is redirect to another method.
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')) { ... }
I am trying to image upload in cakephp by using https://github.com/josegonzalez/cakephp-upload this plugin.I have almost done upload, now the problem is image directory not sending correctly. Here is the image
In controller I have add this code
public function add() {
if ($this->request->is('post')) {
$this->User->create();
$data = $this->request->data['User'];
if(!$data['photo']['name'])
unset($data['photo']);
if ($this->User->save($data)) {
$this->Session->setFlash(__('The img has been saved.'));
} else {
$this->Session->setFlash(__("The img hasn't been saved."));
}
}
}
And in add.ctp code is
<?php echo $this->Form->create('User', array('type'=>'file')); ?>
<fieldset>
<legend><?php echo __('Add Img'); ?></legend>
<?php
echo $this->Form->input('User.username');
echo $this->Form->input('photo',array('type'=>'file'));
echo $this->Form->input('User.photo_dir', array('type' => 'hidden'));
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
Here is the user.php model code
class User extends AppModel {
public $actsAs = array(
'Upload.Upload' => array(
'photo' => array(
'fields' => array(
'dir' => 'photo_dir'
)
)
)
);
}
photo_dir field type is varchar(255)
photo is uploading webroot\img\upload folder
How can I send full url in database table?May any body help me please?
Your controller code could look like this:
public function add() {
if ($this->request->is('post')) {
$this->User->create();
$data = $this->request->data['User'];
if(!$data['photo']['name'])
unset($data['photo']);
$data['photo']['name']='/img/upload/'.$data['photo']['name']
if ($this->User->save($data)) {
$this->Session->setFlash(__('The img has been saved.'));
} else {
$this->Session->setFlash(__("The img hasn't been saved."));
}
}
}
However this isn't actually doing any uploading and it isn't following cake's conventions very strictly.
This is a proper upload (snip-it) without the use of a plugin. Note: this is actual code from a site that kept track of teams.
controller
public function add() {
if ($this->request->is('post')) {
$this->Player->create();
if(isset($this->request->data['Player']['upload'])) {
foreach($this->request->data['Player']['upload'] as $key => $upload) {
$file=$upload;
$path=APP.'webroot/img/Players/'.$file['name'];
while(file_exists($path)) {
$r=rand(1,10000);
$file['name']=$r.$file['name'];
$path=APP.'webroot/img/Players/'.$file['name'];
}
if ($file['error'] == 0) {
if (move_uploaded_file($file['tmp_name'], $path)) {
$this->request->data['Player'][$key]='Players/'.$file['name'];;
} else {
$this->Session->setFlash(__('Something went wrong. Please try again.'));
$this->redirect(array('action' => 'index'));
}
}
}
}
if ($this->Player->save($this->request->data)) {
$this->Session->setFlash(__('The player has been saved.'), 'default', array('class' => 'alert alert-success'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The player could not be saved. Please, try again.'), 'default', array('class' => 'alert alert-danger'));
}
}
$teams = $this->Player->Team->find('list');
$ranks = $this->Player->Rank->find('list');
$this->set(compact('teams', 'ranks'));
}
view
<?php echo $this->Form->create('Player', array('role' => 'form', 'type' => 'file')); ?>
<?php echo $this->Form->input('team_id', array('class' => 'form-control', 'placeholder' => 'Team Id'));?>
<?php echo $this->Form->input('rank_id', array('class' => 'form-control', 'placeholder' => 'Rank Id'));?>
<?php echo $this->Form->input('name', array('class' => 'form-control', 'placeholder' => 'Name'));?>
<?php echo $this->Form->input('upload', array('class' => 'form-control', 'placeholder' => 'Name'));?>
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.');
}
}
I want to make a validation form in cakephp my code form is:
view
<div class="well">
<?php
echo $this->Form->create(false);
echo $this->Form->input('name', array('label' => 'name '));
echo $this->Form->input('PHONE_NUMBER', array('label' => 'PHONE_NUMBER '));
echo $this->Form->input('EMAIL', array('label' => 'EMAIL '));
echo $this->Form->input('ISSUE', array('label' => 'ISSUE '));
echo $this->Form->input('IP', array('label' => 'IP '));
echo $this->Form->submit('Send.');
?>
Controller
<?php
class ContactController extends AppController {
public function index() {
if (empty($_POST) === FALSE) {
$message = '';
$message .=$_POST['data']['EMAIL'] . ' <br/>';
$message .=$_POST['data']['name'] . ' <br/>';
$message .=$_POST['data']['PHONE_NUMBER'] . ' <br/>';
$message .=$_POST['data']['ISSUE'] . ' <br/>';
$message .=$_SERVER['REMOTE_ADDR'] . ' <br/>';
mail('mohmed#lcegy.com', 'Support From Website ', $message);
$this->Session->setFlash("Thanks , an email just sent .");
}
}
}
My question is how to implement validation in this form and how to get the IP address of the visitor?
You may want to update your index() function to look something similar to this: I think it's more of the cakePHP convention.
public function index() {
if ($this->request->is('post')) {
$message = '';
$message = $this->request->data['EMAIL'];
...
}
}
For validation, you can add that to your model. You could do something similar:
public $validate = array(
'EMAIL' => 'email',
'name' => array(
'rule' => 'alphaNumeric',
'required' => true
)
);
For more validation, you can look at the documentation: http://book.cakephp.org/2.0/en/models/data-validation.html
You can use $_SERVER['REMOTE_ADDR'] to get the client's IP Address.
You Can Do Validation From Your Model by setting Rules as follows
public $validate =
array(
'Email' => array
(
'rule' => 'notempty'
),
);
Best way to do it by model as above given answers but you can also do it at view page by simply adding attributes "require" and define proper types like emails, numbers. eg. in your form:
<?php
echo $this->Form->create(false);
echo $this->Form->input('name', array('label' => 'name ', 'required' => true));
echo $this->Form->input('PHONE_NUMBER', array('label' => 'PHONE_NUMBER ', 'required' => true,'type'=>'number'));
echo $this->Form->input('EMAIL', array('label' => 'EMAIL ', 'required' => true, 'type' => 'email'));
echo $this->Form->input('ISSUE', array('label' => 'ISSUE ', 'required' => true));
echo $this->Form->input('IP', array('label' => 'IP ', 'required' => true));
echo $this->Form->submit('Send.');
?>