I have a problem validatin fields in my code usign cakephp3.4.13
It always says "This field cannot be left empty" event the username fields has value input, but when i remove the validation in userstable.php it will submit but the username field is empty in the database.
PLease help me
Userstable.php
public function validationDefault(Validator $validator)
{
$validator
->integer('id')
->allowEmpty('id', 'create');
$validator->requirePresence('username', 'Please enter username.');
$validator
->requirePresence('password', 'create')
->notEmpty('password', 'You must enter a password', 'create')
->add('password', [
'length' => [
'rule' => ['minLength', 8],
'message' => 'Passwords must be at least 8 characters long.',
]
]);
$validator
->requirePresence('age', 'create')
->notEmpty('age');
$validator
->requirePresence('address', 'create')
->notEmpty('address');
$validator
->email('email')
->requirePresence('email', 'create')
->notEmpty('email');
$validator
->requirePresence('gender', 'create')
->notEmpty('gender');
return $validator;
}
public function buildRules(RulesChecker $rules)
{
$rules->add($rules->isUnique(['email']));
$rules->add($rules->isUnique(['username']));
return $rules;
}
Userscontroller.php //register
<?php
public function register()
{
$user= $this->Users->newEntity();
if ($this->request->is('post')) {
$image_name = $this->request->data['profile_pic']['name'];
$image_tmp = $this->request->data['profile_pic']['tmp_name'];
$destination = WWW_ROOT.'img'.DS.'users'.DS.$image_name;
move_uploaded_file($image_tmp,$destination);
$this->request->data['profile_pic'] = $image_name;
$this->request->data['destination'] = $destination;
$user= $this->Users->patchEntity($user, $this->request->data);
if ($this->Users->save($user)) {
$this->Flash->success(__('Data has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The user could not be saved. Please, try again.'));
}
}
$this->set(compact('user'));
$this->set('_serialize', ['user']);
}
?>
User.php //Model/Entity
<?php
namespace App\Model\Entity;
use Cake\Auth\DefaultPasswordHasher;
use Cake\ORM\Entity;
/**
* User Entity.
*/
class User extends Entity
{
protected $_accessible = [
'*' => true,
'id' => false
];
protected function _setPassword($password)
{
return (new DefaultPasswordHasher)->hash($password);
}
}
?>
register.ctp
<div class="actions columns large-2 medium-3">
<h3><?= __('Actions') ?></h3>
<ul class="side-nav">
<li><?= $this->Html->link(__('List Users'), ['action' => 'index']) ?></li>
</ul>
</div>
<div class="users form large-10 medium-9 columns">
<div id="output"></div>
<?php
if ($this->request->session()->read('Auth.User.username')) {
echo"You must logout first ";
print $this->request->session()->read('Auth.User.username');
echo $this->Html->link('Logout',array('controller' =>'users','action' => 'logout'));
}else{
?>
<?php
//$this->Form->create($user, array('class' => 'insertForm'));
echo $this->Form->create($user, array('type'=>'file'));
?>
<fieldset>
<legend><?= __('Add User') ?></legend>
<?php
$date_posted = date("Y-m-d") ;
echo $this->Form->input('username');
echo $this->Form->input('email');
echo $this->Form->input('age');
$options = ['Male' => 'Male', 'Female' => 'Female'];
echo $this->Form->input('gender', array(
'options' => $options,
'type' => 'select',
//'empty' => 'Select the gender',
'label' => 'Gender')
);
echo $this->Form->input('address');
echo $this->Form->input('created',array('type'=>'hidden','value' => $date_posted));
echo $this->Form->input('password');
echo $this->Form->input('profile_pic', ['type' => 'file']);
?>
</fieldset>
<?php echo $this->Form->button('Register', ['type' => 'submit']); ?>
<?php } ?>
</div>
Related
please i really need help i tried almost everything on forums
The method $this->Auth->identify(); always return false
the length fo password in database is varchar(255)
my cakephp version is 3.6.8
candidatcontroller
public function login()
{
if ($this->request->is('post'))
{
$candidat = $this->Auth->identify();
if ($candidat)
{
$this->Auth->setUser($candidat);
return $this->redirect(['Controller'=>'Candidat','action'=>'index']);
}
$this->Flash->error(__('The candidat could not be saved Please try again.'));
}
}
appcontroller
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler', [
'enableBeforeRedirect' => false,
]);
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'authError' => 'Vous croyez vraiment que vous pouvez faire cela?',
'authenticate' => [
'Form' => [
'fields' => ['username' => 'email','password' => 'password']
]
],
'loginAction' => [
'controller' => 'candidat',
'action' => 'login',
],
'storage' => 'Session'
]);
}
login
<?= $this->Form->create() ?>
<fieldset>
<legend><?= __('login') ?></legend>
<?php
echo $this->Form->control('Email_cand',['label'=>'Email']);
echo $this->Form->control('password',['label'=>'mot de passe']);
?>
</fieldset>
<?= $this->Form->button(__('connecter')) ?>
<?= $this->Form->end() ?>
I have this method to display a user profile like this one in url http://localhost/sample/users/profile/john instead of http://localhost/sample/users/view/1
public function profile($username)
{
$user = $this->Users->find()->where(['username' => $username])->first();
$accountUsername = $user->username;
$this->set('profileUserName', $accountUsername);
$this->set('users', $user);
$this->set('_serialize', ['user']);
}
When I try to edit my profile It will always go to "You are not allowed to do this."
public function edit($id = null)
{
$logged_user_id=$this->Auth->user('id');
if($logged_user_id==$id){
$user = $this->Users->get($id, [
'contain' => []
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$user = $this->Users->patchEntity($user, $this->request->getData());
if ($this->Users->save($user)) {
$this->Flash->success(__('User profile successfuly updated.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The user could not be saved. Please, try again.'));
}
}
$this->set(compact('user'));
$this->set('_serialize', ['user']);
} else {
$this->Flash->error(__('You are not allowed to do this.'));
return $this->redirect(['action' => 'index']);
}
}
I tried to add this on edit method
$logged_user_id=$this->Auth->user('id');
$logged_user_name=$this->Auth->user('username');
if(($logged_user_id==$id)&&($logged_user_name == $username)){
$user = $this->Users->get($id, [
'contain' => []
]);
profile.ctp
<div class="paginator">
<ul>
<li><?= $this->Html->link(__('Edit User'), ['action' => 'edit', $users->id]) ?> </li>
<li><?= $this->Form->postLink(__('Delete User'), ['action' => 'delete', $users->id], ['confirm' => __('Are you sure you want to delete # {0}?', $users->id)]) ?> </li>
<li><?= $this->Html->link(__('List Users'), ['action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('Logout'), ['action' => 'logout']) ?> </li>
</ul>
</div>
Maybe because of the get by $id causing the problems?
public function beforeFilter(\Cake\Event\Event $event)
{
$user = $this->request->session()->read('Auth.User');
$this->set('user_id', $user['id']);
}
just edit your profile.ctp and change $users->id to $user_id
<div class="paginator">
<ul>
<li><?= $this->Html->link(__('Edit User'), ['action' => 'edit', $user_id]) ?> </li>
<li><?= $this->Form->postLink(__('Delete User'), ['action' => 'delete', $users->id], ['confirm' => __('Are you sure you want to delete # {0}?', $users->id)]) ?> </li>
<li><?= $this->Html->link(__('List Users'), ['action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('Logout'), ['action' => 'logout']) ?> </li>
</ul>
</div>
Explanation you always directly goes to "You are not allowed to do this." because of this in profile method
$user = $this->Users->find()->where(['username' => $username])->first();
the system is confused what profile to edit since you have duplicate username in the database for users table, so it throws and error "You are not allowed to do this." after finding the first row of data with the same "username value"
add this code to UsersTable.php to prevent duplicate username
$validator
->requirePresence('username')
->notBlank('username', 'A username is required')
->add('username', 'unique', [
'rule' => 'validateUnique',
'provider' => 'table',
'message' => 'Username is already used'
]);
So I have this controller and method:
Contorller/UsersController.php
<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\Event\Event;
use Cake\Network\Exception\NotFoundException;
use Cake\ORM\TableRegistry;
/**
* Jobs Controller
*
* #property \App\Model\Table\JobsTable $Jobs
*/
class UsersController extends AppController
{
public function beforeFilter(Event $event)
{
parent::beforeFilter($event);
$this->Users->allow('register');
}
public function register()
{
//Get Categories
$getCategories = TableRegistry::get('Categories');
$categories = $getCategories->find('all');
$this->set('categories',$categories);
$this->set('title', 'Registration');
$user = $this->Users->newEntity();
if ($this->request->is('post')) {
$user = $this->Users->patchEntity($user, $this->request->data);
if ($this->Users->save($user)) {
$this->Flash->success(__('The user has been saved.'));
return $this->redirect(['action' => 'register']);
}
$this->Flash->error(__('Unable to add the user.'));
}
$this->set('user', $user);
}
}
Model/Table/UsersTable.php
<?php
namespace App\Model\Table;
use Cake\ORM\Table;
use Cake\Validation\Validator;
class UsersTable extends Table
{
public function validationDefault(Validator $validator)
{
return $validator
->notEmpty('first_name', 'A username is required')
->notEmpty('last_name', 'A username is required')
->notEmpty('email', 'A username is required')
->notEmpty('username', 'A username is required')
->notEmpty('password', 'A username is required')
->add('role', 'inList', [
'rule' => ['inList', ['Employer', 'Job Seeker']],
'message' => 'Please enter a valid role'
]);
}
}
?>
Template/Users/register.ctp:
<div class="users form">
<?php echo $this->Form->create($user); ?>
<fieldset>
<legend><?= __('Create New User'); ?></legend>
<?php
echo $this->Form->input('first_name');
echo $this->Form->input('last_name');
echo $this->Form->input('email',array('type'=>'email'));
echo $this->Form->input('username');
echo $this->Form->input('password',array('type'=>'password'));
echo $this->Form->input('confirm_password',array('type'=>'password'));
echo $this->Form->input('role',array(
'type' => 'select',
'options' => ['Employer'=>'Employer','Job Seeker'=>'Job Seeker'],
'empty' => 'Select Role'
));
?>
</fieldset>
<?= $this->Form->button(__('Submit')); ?>
<?= $this->Form->end() ?>
</div>
Entity/User.php:
<?php
namespace App\Model\Entity;
use Cake\Auth\DefaultPasswordHasher;
use Cake\ORM\Entity;
/**
* User Entity.
*/
class User extends Entity
{
/**
* Fields that can be mass assigned using newEntity() or patchEntity().
*
* #var array
*/
protected $_accessible = array(
'first_name' => true,
'last_name' => true,
'email' => true,
'username' => true,
'password' => true,
'role' => true,
'created' => true
);
protected function _setPassword($password)
{
return (new DefaultPasswordHasher)->hash($password);
}
}
So when I'm trying to access /users/register view, it gives me next error:
Unknown method "allow": $this->Users->allow('register');
But if I remove next method inside of my Users controller:
public function beforeFilter(Event $event)
{
parent::beforeFilter($event);
$this->Users->allow('register');
}
It works fine, but I guess it also must work with it as well. So what am I doing wrong or missing?
I have created a CommentManager plugin for adding comments in my posts. Adding the comment form in Posts/view.ctp file and the comment form action is redirecting to CommentManager/Comments/add.
The comments are saving properly but when saving empty form, that doesn't shows the validation error messages which i have written in CommentsTable and also the entered data has gone from the form.
CommentManager/src/Controller/CommentsController/add
public function add()
{
$ccomment = $this->Comments->newEntity($this->request->data);
if ($this->request->is('post')) {
$newData = ['post_id' => $this->request->params['pass'][0]];
$ccomment = $this->Comments->patchEntity($ccomment, $newData);
if ($this->Comments->save($ccomment)) {
$this->Flash->success('The comment has been saved.');
return $this->redirect($_SERVER['HTTP_REFERER']);
} else {
$this->Flash->error('The comment could not be saved. Please, try again.');
}
}
$this->set(compact('ccomment'));
return $this->redirect($_SERVER['HTTP_REFERER']);
}
CommentManager/src/Model/Table/CommentsTable
public function validationDefault(Validator $validator) {
return $validator
->notEmpty('body', 'Body contents required.')
->notEmpty('email', 'An email is required.')
->add('email', [
'format' => [
'rule' => [
'custom',
'/^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/'
],
'message' => 'Enter a valid email.'
]
]);
}
src/Template/Posts/view.ctp
<?php echo $this->Html->link('Back', ['action' => 'index']) ?>
<?php echo $this->element('check_login'); ?>
<br/>
<?php $img_path = DS.'webroot'.DS.'images'.DS.$post->image; ?>
<img src="<?php echo empty($post->image)?'':$img_path; ?>">
<h2><?php echo $post->title; ?></h2>
<p><?php echo $post->body; ?></p>
<p><small><?php echo $post->created->format('d M Y'); ?></small></p>
<h3>Comments:</h3>
<?php foreach ($comments as $comment) { ?>
<p><?php echo $comment->body; ?></p>
<?php } ?>
<?php
echo $this->Form->create(null, ['url' => ['plugin' => 'CommentManager', 'controller' => 'Comments', 'action' => 'add', $post->id]]);
echo $this->Form->input('body', ['type' => 'textarea', 'rows' => '5', 'cols' => '5']);
echo $this->Form->input('email');
echo $this->Form->button('Save');
echo $this->Form->end();
?>
Don't call newEntity() with an empty array. Inste of
$ccomment = $this->Comments->newEntity($this->request->data);
Do:
$ccomment = $this->Comments->newEntity();
And in in the call to patchEntity() pass the $this->request->data
Hi all Iam using Cakephp 2.x, I need to output individual users' comments for each individual event. Each user has many events and many comments. I have Events, Comments and Users models and want to allow users to post and view comments on each event view.ctp. If anyone could give any starting tips to implement this functionality it would be much appreciated.
I have tried to output the comments model index table in the events view.ctp, but the table is not populated with the comments from the database, but the comments view.ctp does in fact populate the table with the comments. I have used the $this->loadModel('Comments'); function in the events controller.
<div class="events view">
<?php echo $this->Html->css('viewevent'); ?>
<?php echo $this->element('maintitlegen'); ?>
<div style="padding-top: 160px">
<h2><?php echo $event['Event']['name']; ?></h2>
<dl>
<dt><?php echo __('Event Image'); ?></dt>
<dd>
<?php echo $this->Html->image('/uploads/event/filename/thumb/small/'.$event['Event']['filename']); ?>
</dd>
<dt><?php echo __('Date'); ?></dt>
<dd>
<?php echo h($event['Event']['date']); ?>
</dd>
<dt><?php echo __('Time'); ?></dt>
<dd>
<?php echo h($event['Event']['time']); ?>
</dd>
<dt><?php echo __('Description'); ?></dt>
<dd>
<?php echo h($event['Event']['description']); ?>
</dd>
<dt><?php echo __('Dresscode'); ?></dt>
<dd>
<?php echo h($event['Event']['dresscode']); ?>
</dd>
<dt><?php echo __('Slogan'); ?></dt>
<dd>
<?php echo h($event['Event']['slogan']); ?>
</dd>
<dt><?php echo __('Price'); ?></dt>
<dd>
<?php echo h($event['Event']['price']); ?>
</dd>
<dt><?php echo __('Offers'); ?></dt>
<dd>
<?php echo h($event['Event']['offers']); ?>
</dd>
</dl>
<!--<?php foreach ($users as $user): ?>
<?php echo $user['Comment']['comment']; ?>
<?php endforeach; ?>-->
<!--<?php echo $ucomment['Comment']['comment']; ?>-->
<?php echo $this->Form->create('Comment', array('controller' => 'comments', 'action' => 'add')); ?>
<?php echo ('Add Comment'); ?>
<?php echo $this->Form->input('comment'); ?>
<?php echo $this->Form->end('Submit'); ?>
</div>
<div class="comments index">
<h2><?php echo ('Comments'); ?></h2>
<table cellpadding="0" cellspacing="0">
<tr>
<th><?php echo $this->Paginator->sort('id'); ?></th>
<th><?php echo $this->Paginator->sort('comment'); ?></th>
<th><?php echo $this->Paginator->sort('created'); ?></th>
<th><?php echo $this->Paginator->sort('modified'); ?></th>
<th><?php echo $this->Paginator->sort('user_id'); ?></th>
<th><?php echo $this->Paginator->sort('event_id'); ?></th>
<th class="actions"><?php echo __('Actions'); ?></th>
</tr>
<?php
foreach ($comments as $comment): ?>
<tr>
<td><?php echo h($comment['Comment']['id']); ?> </td>
<td><?php echo h($comment['Comment']['comment']); ?> </td>
<td><?php echo h($comment['Comment']['created']); ?> </td>
<td><?php echo h($comment['Comment']['modified']); ?> </td>
<td>
<?php echo $this->Html->link($comment['User']['name'], array('controller' => 'users', 'action' => 'view', $comment['User']['id'])); ?>
</td>
<td>
<?php echo $this->Html->link($comment['Event']['name'], array('controller' => 'events', 'action' => 'view', $comment['Event']['id'])); ?>
</td>
<td class="actions">
<?php echo $this->Html->link(__('View'), array('action' => 'view', $comment['Comment']['id'])); ?>
<?php echo $this->Html->link(__('Edit'), array('action' => 'edit', $comment['Comment']['id'])); ?>
<?php echo $this->Form->postLink(__('Delete'), array('action' => 'delete', $comment['Comment']['id']), null, __('Are you sure you want to delete # %s?', $comment['Comment']['id'])); ?>
</td>
</tr>
<?php endforeach; ?>
</table>
<p>
<?php
echo $this->Paginator->counter(array(
'format' => __('Page {:page} of {:pages}, showing {:current} records out of {:count} total, starting on record {:start}, ending on {:end}')
));
?> </p>
<div class="paging">
<?php
echo $this->Paginator->prev('< ' . __('previous'), array(), null, array('class' => 'prev disabled'));
echo $this->Paginator->numbers(array('separator' => ''));
echo $this->Paginator->next(__('next') . ' >', array(), null, array('class' => 'next disabled'));
?>
</div>
</div>
</div>
////////////////////////////////User model///////////////////////////////////////////////
<?php
class User extends AppModel {
public $name = 'User';
public $displayField = 'name';
public $validate = array(
'name'=>array(
'Please enter your name.'=>array(
'rule'=>'notEmpty',
'message'=>'Please enter your name.'
)
),
'username'=>array(
'That username has already been taken'=>array(
'rule'=>'isUnique',
'message'=>'That username has already been taken.'
),
'Valid email'=>array(
'rule'=>array('email'),
'message'=>'Please enter a valid email address'
)
),
'email'=>array(
'Valid email'=>array(
'rule'=>array('email'),
'message'=>'Please enter a valid email address'
)
),
'password'=>array(
'Not empty'=>array(
'rule'=>'notEmpty',
'message'=>'Please enter your password'
),
'Match passwords'=>array(
'rule'=>'matchPasswords',
'message'=>'Your passwords do not match'
)
),
'password_confirmation'=>array(
'Not empty'=>array(
'rule'=>'notEmpty',
'message'=>'Please confirm your password'
)
)
);
public function matchPasswords($data) {
if ($data['password'] == $this->data['User']['password_confirmation']) {
return true;
}
$this->invalidate('password_confirmation', 'Your passwords do not match');
return false;
}
public function beforeSave($options = array()) {
if (isset($this->data['User']['password'])) {
$this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
}
return true;
}
public $hasMany = array(
'Event' => array(
'className' => 'Event',
'foreignKey' => 'user_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
),
'Comment' => array(
'className' => 'Comment',
'foreignKey' => 'user_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);
public $hasOne = array(
'Profile' => array(
'className' => 'Profile',
'foreignKey' => 'user_id',
'dependent' => true));
var $actsAs = array(
'MeioUpload.MeioUpload' => array('filename'=>array(
'thumbsizes'=>array(
'small'=>array(
'width'=>'75',
'height'=>'75',
'forceAspectRatio'=>'C'
)))));
}
?>
///////////////////////////////////// Users Controller///////////////////////////////////
<?php
class UsersController extends AppController {
public $name = 'Users';
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('add');
}
public function isAuthorized($user) {
if ($user['role'] == 'admin') {
return true;
}
// if (in_array($this->action, array('delete'))) {
// if ($user['id'] != $this->request->params['pass'][0]) {
// return false;
// }
// }
return true;
}
public function login() {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
$this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash('Your username/password combination was incorrect');
}
}
}
// public function logout() {
// $this->redirect($this->Auth->logout());
// }
public function index() {
$this->User->recursive = 0;
$this->set('users', $this->User->find('all'));
}
public function view($id = null) {
$this->User->id = $id;
if (!$this->User->exists()) {
throw new NotFoundException('Invalid user');
}
if (!$id) {
$this->Session->setFlash('Invalid user');
$this->redirect(array('action' => 'index'));
}
$this->set('user', $this->User->read());
}
public function add() {
if ($this->request->is('post')) {
if ($this->User->save($this->request->data)) {
$this->Session->setFlash('Now create your profile!');
$this->Auth->login();
$this->redirect(array('controller'=> 'profiles', 'action' => 'add'));
} else {
$this->Session->setFlash('Your account cannot be created. Please try again.');
}
}
// if (!empty($user)){
// $this->request->data['Profile']['user_id'] = $this->User->id;
// $this->User->Profile->save($this->request->data);
// }
}
public function edit($id = null) {
$this->User->id = $id;
$user = $this->User->read();
if($user['User']['id'] != $this->Auth->user('id')){
$this->redirect(array('controller' => 'events','action' => 'index'));
}
if (!$this->User->exists()) {
throw new NotFoundException(__('Invalid user'));
}
if ($this->request->is('get')) {
$this->request->data = $user;
} else {
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('Your account has been updated'));
$this->redirect(array('controller' => 'events', 'action' => 'index'));
} else {
$this->Session->setFlash(__('Your account cannot be saved. Please try again.'));
}
}
}
public function delete($id = null) {
if ($this->request->is('get')) {
throw new MethodNotAllowedException();
}
if (!$id) {
$this->Session->setFlash('Invalid id for user');
$this->redirect(array('action'=>'index'));
}
if ($this->User->delete($id)) {
$this->Session->setFlash('User deleted');
$this->redirect(array('action'=>'index'));
}
$this->Session->setFlash('User was not deleted');
$this->redirect(array('action' => 'index'));
}
}
?>
I think it is safe to assume your comment table has at least the following columns:
id
user_id
event_id
comment (or name)
The view you display in the OP is the view for the events.view method. But you do not show the even model or controller. So I am not certain if you need help with the events controller or if you are trying to display event data in the users controller. The way to get all of the comments for the view you show in the OP is to pull all of the comments from the model like so:
$this->set('comments', $this->Event->Comment->find('all', array('conditions' => array('event_id' => $event_id))));
If you want the user data to be displayed along with it, you will need to either set recursive = 1 or write a join to join the user data.