I have this code but the flash message is displayed incorrectly.
I want to display the message in:
http://xxx/cake/ ----(add action)
but actually the message is shown in:
http://xxx/cake/users/ ----(index action)
How can i solve this? I don't have any view to activation. I just want redirect to the add action and display the flash message after that.
class UsersController extends AppController {
public function index() {
$this->User->recursive = 0;
$this->set('users', $this->paginate());
}
public function add() {
}
public function activation() {
$email = $this->request->query['email'];
$codeLink = $this->request->query['code'];
if($this->User->activationAccount($email, $codeLink)) {
$this->Session->setFlash(__('Success'));///should be shown in add
$this->redirect(array('action' => 'add'));
}
else {
$this->Session->setFlash(__('Error.'));//should be shown in add
$this->redirect(array('action' => 'add'));
}
}
}
routes.php
Router::connect('/', array('controller' => 'users', 'action' => 'add'));
Just destroy this session:
array
'fb_400xxxxxxx96_state' => string 'ce3xxasdxxxxxxasdasdxxxxxxxf' (length=32)
public function add() {
$this->Session->destroy();
//some code
}
may be you should have a look at this tuto which cover this
Related
i'm getting redirected to this url http://localhost/project_name/PanelAdmin/users/login?redirect=%2FPanelAdmin%2Fusers%2Fedit using auth component instead of http://localhost/project_name/PanelAdmin/users/login if unauthorised access to edit action. The page which i get is the login one which is correct but i want to change the url to something like this http://localhost/project_name/PanelAdmin/users/login.
AppController.php
<?php
namespace PanelAdmin\Controller;
use App\Controller\AppController as BaseController;
use Cake\Event\Event;
class AppController extends BaseController
{
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'authorize'=> 'Controller',
'authenticate' => [
'Form' => [
// fields used in login form
'fields' => [
'username' => 'email',
'password' => 'password'
]
]
],
// login Url
'loginAction' => [
'controller' => 'Users',
'action' => 'login'
],
// where to be redirected after logout
'logoutRedirect' => [
'controller' => 'Topics',
'action' => 'index'//,
//'home'
],
// if unauthorized user go to an unallowed action he will be redirected to this url
'unauthorizedRedirect' => [
'controller' => 'Topics',
'action' => 'index'//,
//'home'
],
'authError' => 'Did you really think you are allowed to see that?',
]);
// Allow the display action so our pages controller still works and user can visit index and view actions.
$this->Auth->allow(['index','display','view']);
}
public function isAuthorized($user)
{
$this->Flash->error('You aren\'t allowed');
return false;
}
public function beforeFilter(Event $event)
{
$this->Auth->allow(['index', 'view', 'display']);
}
public function beforeRender(Event $event)
{
if (!array_key_exists('_serialize', $this->viewVars) &&
in_array($this->response->type(), ['application/json', 'application/xml'])
) {
$this->set('_serialize', true);
}
}
}
?>
UsersController.php
<?php
namespace PanelAdmin\Controller;
use Cake\Controller\Controller;
use Cake\ORM\TableRegistry;
use Cake\Event\Event;
class UsersController extends AppController
{
public function initialize()
{
parent::initialize();
$this->loadComponent('Flash'); // Include the FlashComponent
// Auth component allow visitors to access add action to register and access logout action
$this->Auth->allow(['logout', 'add']);
}
public function login()
{
if ($this->request->is('post')) {
// Auth component identify if sent user data belongs to a user
$user = $this->Auth->identify();
if ($user) {
//
$this->Auth->setUser($user);
return $this->redirect($this->Auth->redirectUrl());
}
$this->Flash->error(__('Invalid username or password, try again.'));
}
}
public function logout(){
$this->Flash->success('You successfully have loged out');
return $this->redirect($this->Auth->logout());
}
public function index()
{
$this->set('users',$this->Users->find('all'));
}
public function view($id)
{
$user = $this->Users->get($id);
$this->set('user',$user);
}
public function add()
{
$user = $this->Users->newEntity();
if($this->request->is('post')) {
$this->Users->patchEntity($user,$this->request->data);
if($this->Users->save($user)){
$this->Flash->success(__('Your account has been registered .'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('Unable to register your account.'));
}
$this->set('user',$user);
}
public function edit($id)
{
$user = $this->Users->get($id);
if ($this->request->is(['post', 'put'])) {
$this->Users->patchEntity($user, $this->request->data);
if ($this->Users->save($user)) {
$this->Flash->success(__('Your profile data has been updated.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('Unable to update your profile.'));
}
$this->set('user', $user);
}
public function delete($id)
{
$this->request->allowMethod(['post', 'delete']);
$user = $this->Users->get($id);
if ($this->Users->delete($user)) {
$this->Flash->success(__('The user with id: {0} has been deleted.', h($id)));
return $this->redirect(['action' => 'index']);
}
}
}
?>
TopicsController.php
<?php
namespace PanelAdmin\Controller;
use Cake\Controller\Controller;
use Cake\ORM\TableRegistry;
class TopicsController extends AppController
{
public function initialize()
{
parent::initialize();
$this->loadComponent('Flash'); // Include the FlashComponent
}
public function isAuthorized($user)
{
$action = $this->request->params['action'];
// registered users can add topics and view index
if (in_array($action, ['index', 'add','topics'])) {
return true;
}
// All other actions require an id or users cannot do it
if (empty($this->request->params['pass'][0])) {
return false;
}
// The owner of a topic can edit and delete it
// the owner of topic is known by its id and user_id value of topic .
if (in_array($this->request->action, ['edit', 'delete'])) {
// get topic id from the request
$topicId = (int)$this->request->params['pass'][0];
// check if the topic is owned by the user
if ($this->Topics->isOwnedBy($topicId, $user['id'])) {
return true;
}
}
return parent::isAuthorized($user);
}
public function index()
{
// find('all') get all records from Topics model
// We uses set() to pass data to view
$this->set('topics', $this->Topics->find('all'));
}
public function view($id)
{
// get() method get only one topic record using
// the $id paraameter is received from the requested url
// if request is /topics/view/5 the $id parameter value is 3
$topic = $this->Topics->get($id);
$this->set(compact('topic'));
}
public function add()
{
$topic = $this->Topics->newEntity();
//if the user topics data to your application, the POST request informations are registered in $this->request
if ($this->request->is('post')) { //
$topic = $this->Topics->patchEntity($topic, $this->request->data);
$topic->user_id = $this->Auth->user('id');
if ($this->Topics->save($topic)) {
// success() method of FlashComponent restore messages in session variable.
// Flash messages are displayed in views
$this->Flash->success(__('Your topic has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('Unable to add your topic.'));
}
$this->set('topic', $topic);
}
public function edit($id = null)
{
$topic = $this->Topics->get($id);
if ($this->request->is(['post', 'put'])) {
$this->Topics->patchEntity($topic, $this->request->data);
if ($this->Topics->save($topic)) {
$this->Flash->success(__('Your topic has been updated.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('Unable to update your topic.'));
}
$this->set('topic', $topic);
}
public function delete($id)
{
//if user wants to delete a record by a GET request ,allowMethod() method give an Exception as the only available request for deleting is POST
$this->request->allowMethod(['post', 'delete']);
$topic = $this->Topics->get($id);
if ($this->Topics->delete($topic)) {
$this->Flash->success(__('The topic with id: {0} has been deleted.', h($id)));
return $this->redirect(['action' => 'index']);
}
}
}
?>
You have to create a CustomAuthComponent.php file in src/Controller/Component/
Put the code in CustomAuthComponent.php
<?php
namespace App\Controller\Component;
use Cake\Controller\Component\AuthComponent;
class CustomAuthComponent extends AuthComponent
{
protected function _loginActionRedirectUrl()
{
return $this->_config['loginAction'];
}
}
After that in your AppController.php find and replace $this->loadComponent('Auth',..... with $this->loadComponent('CustomAuth',.......
After that find and replace $this->Auth with $this->CustomAuth in every Controller file.
That worked for me.
I made a blog and I can leave comments to my articles, then I made an Approve button, need to make the approve function.
I need to make it to work. I just can't, no matter what I try. I want to be able to approve or not a comment before it's posted. I have tried everything I could think of.
<?php
namespace App\Controller;
class CommentsController extends AppController
{
public function index()
{
$comments = $this->Comments->find('all');
$this->set(compact('comments'));
}
public function view($id = null)
{
$comment = $this->Comments->get($id);
$this->set(compact('comment'));
}
public function add()
{
$comment = $this->Comments->newEntity();
if ($this->request->is('post')) {
$comment = $this->Comments->patchEntity($comment, $this->request->data);
$comment->user_id = $this->Auth->user('id');
$comment->aproved = 0;
$comment->article_id = $this->request->data['article_id'];
if ($this->Comments->save($comment)) {
$this->Flash->success(__('Your comment has been saved.'));
return $this->redirect(['controller' => 'Articles', 'action' => 'view', $comment->article_id]);
}
$this->Flash->error(__('Unable to add your comment.'));
}
$this->set('comment', $comment);
}
public function aprove()
{
}
}
Try this
Your link should look like this:
$this->Html->link('approve', array('controller' => 'your-controller', 'action' => 'aprove', $comment_id, $value['Comment']['aproved']));
and your controller function is:
public function aprove($comment_id, $approve_value)
{
if(isset($comment_id) && !empty($comment_id)){
$approve = $this->Comments->find('first',array('conditions'=>array('id'=>$comment_id),'fields'=>array('Comment.id, Comment.approve')));
if(!empty($approve)){
$this->Comments->id = $approve['Comment']['id'];
$this->Comments->saveField('aproved', $approve_value);
}
}
}
I am trying to extend onto the 'blog tutorial' from cakephp and am having a little trouble with linking to a logged in user's homepage, which I created on a file called view.ctp.
I can link to most of my file path http://localhost:8888/blogtest/users/view/ up until I need the 'id' to define which page to send someone too.
This is how I am linking to the page:
go
I know I need some logic within the php tags to tell the browser to retrieve the id of the current logged in user.
How would I got about doing this? Where would I create a variable?*
Does the var go in the UsersController.php or is it in the User.php? Any help is greatly appreciated!
UsersController php:
<?php
// app/Controller/UsersController.php
App::uses('AppController', 'Controller');
class UsersController extends AppController {
public function beforeFilter() {
parent::beforeFilter();
// Allow users to register and logout.
$this->Auth->allow('add', 'logout');
}
public function login() {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirectUrl());
}
$this->Session->setFlash(__('Invalid username or password, try again'));
}
}
public function logout() {
return $this->redirect($this->Auth->logout());
}
public function index() {
$this->User->recursive = 0;
$this->set('users', $this->paginate());
}
public function view($id = null) {
$this->User->id = $id;
if (!$this->User->exists()) {
throw new NotFoundException(__('Invalid user'));
}
$this->set('user', $this->User->read(null, $id));
}
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) {
// Prior to 2.5 use
// $this->request->onlyAllow('post');
$this->request->allowMethod('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'));
}
}
?>
Pay attention to the blog tutorial text:
The single instruction in the action uses set() to pass data from the
controller to the view (which we’ll create next). The line sets the
view variable called ‘posts’ equal to the return value of the
find('all') method of the Post model.
It goes on here and explains exactly what you want:
<td>
<?php echo $this->Html->link($post['Post']['title'],
array('controller' => 'posts', 'action' => 'view', $post['Post']['id'])); ?>
</td>
Honestly I have doubts you tried to read it at all. If you really did read this section again. It is all there in great detail.
I am developing the simple register form.And develope the model,controller,view classes.but i am unable to show the error messages in my application.
User.php(Model class)
<?php
class User extends AppModel
{
var $name='User';
public $validate= array(
'username'=>array(
'rule'=>'notEmpty',
'required'=>true,
'message'=>'Enter your name'
),
'email' => array(
'rule' => 'notEmpty',
'message' => 'Please enter your email'
)
);
}
?>
UsersController.php
<?php
class UsersController extends AppController {
public $helpers = array('Html', 'Form');
array('action' => 'edit')
public function register() {
if ($this->User->validates()) {
$this->User->set($this->request->data);
$name = $this->request->data['User']['username'];
$email = $this->request->data['User']['email'];
}
else{
$this->flash('register fail');
}
}
}
?>
register.ctp
<?php
echo $this->Form->create('User',array('action'=>'register'));
echo $this->Form->input('username');
echo $this->Form->input('email');
echo $this->Form->end('Register');
?>
when i am click the register button above code is not showing the error messages.
Finally i got the answer to my question. i.e
User.php
<?php
class User extends AppModel
{
public $validate= array(
'username'=>array(
'rule'=>'notEmpty',
'required'=>false,
'message'=>'Enter your name'
),
'email' => array(
'rule' => 'notEmpty',
'required'=>false,
'message' => 'Please enter your email'
)
);
}
?>
UsersController.php
<?php
class UsersController extends AppController {
public $helpers = array('Html', 'Form');
public function register() {
$this->User->create();
if ($this->User->save($this->request->data)) {
$this->redirect(array('controller'=>'users', 'action'=>'welcome'));
}
else{
echo"register fail";
}
}
public function welcome(){
$this->flash('register successfully','/users/register');
}
}
?>
register.ctp
<?php
echo $this->Form->create('User');
echo $this->Form->input('username',array('required'=>'false'));
echo $this->Form->input('email',array('required'=>'false'));
echo $this->Form->end('Register');
?>
this is the correct answer for above asking question.The main mistake done in my above question was i am given required'=>'true.',now given required'=>'false.' in register.ctp class.now problem resolved.
You need to change you register action in user controller like this:
public function register() {
$this->User->create();
if ($this->User->save($this->request->data)) { //this way it automatically save or show error message if there is one
$this->flash('register success');
}
else{
$this->flash('register fail');
}
}
Hope it helps.
Try this:
add a helper
var $helpers = 'session';
then add the flash message as
$this->Session->setFlash(__('error'));
What you actually want is to show the validation errors, so instead of
$this->flash('register fail');
Do
$this->Session->setflash($this->User->validationErrors);
$this->redirect('/users/register');
I have the following piece of code:
if(Request::ajax())
{
$response_values = array(
'validation_failed' => 1,
'errors' => $validator->errors->toArray()
);
return Response::json($response_values);
}
else
{
return Redirect::route("resource.create")
->withInput()
->withErrors($validator->errors);
}
I have this a lot in my code, and would like to find a way to automate this.
I tried creating a method in BaseController but it doesn't redirect properly, I also tried an after filter, but I was unable to pass parameters to this after filter, as I would need to pass errors and route.
How could I achieve this?
This is not working for you?
class BaseController extends \Controller {
public function processAndRedirectError($validator)
{
if(Request::ajax())
{
$response_values = array(
'validation_failed' => 1,
'errors' => $validator->errors->toArray()
);
return Response::json($response_values);
}
else
{
return Redirect::route("resource.create")
->withInput()
->withErrors($validator->errors);
}
}
}
class MyController extends BaseController {
public function store()
{
$validator = Validator::make(...);
return $this->processAndRedirectError($validator);
}
}