save() function in cakephp save null values - cakephp

My problem is that i dont know save() function of cakephp insert null values in posts table !
When I try to add a post: http://i.stack.imgur.com/fhRVn.png
After redirecting the inserted data is null: http://i.stack.imgur.com/YstBb.png
My PostsController.php is:
App::uses('AppController', 'Controller');
class PostsController extends AppController{
public $components = array('Session');
public $helpers = array('Html', 'Form');
public function index() {
$this -> set('posts', $this->Post->find('all'));
}
public function view($id = null){
if(!$id){
throw new NotFoundException(_('il faut choisir un post'));
}
$post=$this->Post->findById($id);
if(!$post){
throw new NotFoundException(_('invalide Post !'));
}
$this->set('post',$post);
} // fin de "view"
public function add(){
if($this->request->is('post'))
{
$this->Post->create();
if ($this->Post->save($this->request->data)) {
$this->Session->setFlash(__('Your post has been saved.'));
return $this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(__('Unable to add your post.'));
}
//debug($this->Post->validate);
}//fin d'ajout
} // fin de "appcontroller"
My Post.php model file is:
class Post extends appModel {
//public $name='Post';
public $validate = array(
'title' => array('rule' => 'notEmpty'),
'body' => array('rule' => 'notEmpty')
);
}
My view form post is:
echo $this->Form->create('post');
echo $this->Form->input('title');
echo $this->Form->input('body',array('rows' => '3'));
echo $this->Form->end('Ajouter');

in your view maybe your problem that you Model is Post not post
echo $this->Form->create('Post');
echo $this->Form->input('title');
echo $this->Form->input('body',array('rows' => '3'));
echo $this->Form->end('Ajouter');

Related

$this->auth->login() Not Working

Hello Everyone i'm trying to login after i have successfully add user data into database, but login is not working,I'm new to cakephp.Please Help me out.
here is the code
appcontroller:
class AppController extends Controller {
public $components = array(
'DebugKit.Toolbar' ,'Session',
'Auth' => array(
'loginRedirect' => array('controller' => 'users', 'action' => 'index'),
'logoutRedirect' => array('controller' => 'users', 'action' => 'login')
)
);}
UsersController:
public function login(){
if ($this->request->is('Post')) {
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirectUrl());
}//$this->Flash->error(__('Invalid username or password, try again'));
}
}
login.ctp:
<?php
echo $this->Form->create('User');
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->end('login');
?>
Add password hashing to your User model
User.php
App::uses('AppModel', 'Model');
class User extends AppModel {
public function beforeSave($options = array()) {
if(isset($this->data['User']['password'])) {
$this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
}
}
}
after that truncate your user table and save fresh user and then check again the login.

About Model CakePHP

i have 2 table in database.there are categories and posts.
categories have id , name
posts have id , category
and i have 2 files.
PostsController.php
edit.ctp
i edit category by edit.ctp when i save its
image >> http://s704.photobucket.com/albums/ww41/018115496/edit.png
It is not save category's name but save a category's id into Posts.
image >> http://i704.photobucket.com/albums/ww41/018115496/index.png
This is my code
PostsController.php
class PostsController extends AppController {
public $helpers = array('Html', 'Form');
public $uses = array('Post','Category');
public function index() {
$this->set('posts', $this->Post->find('all'));
}
public function edit($id = null) {
$this->loadModel('Category');
$categories = $this->Category->find("list",array('field'=>array('Category.name')));
$this->set("categories", $categories);
if (!$id) {
throw new NotFoundException(__('Invalid post'));
}
$post = $this->Post->findById($id);
if (!$post) {
throw new NotFoundException(__('Invalid post'));
}
if ($this->request->is(array('post', 'put'))) {
$this->Post->id = $id;
if ($this->Post->save($this->request->data)) {
$this->Session->setFlash(__('Your post has been updated.'));
return $this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(__('Unable to update your post.'));
}
if (!$this->request->data) {
$this->request->data = $post;
}
}
}
and edit.ctp
<?php
echo $this->Form->create('Post');
echo $this->Form->input('category', array('options' => $categories));
echo $this->Form->end('Save Post');
?>
i think i because find("list") but i don't know how to solve.
Thank you.
I have fixed your problem, You need to replace this
//PostsController.php
public function edit($id = null) {
$this->loadModel('Category');
$categories = $this->Category->find("list",array('field'=>array('Category.name','Category.name')));
$this->set("categories", $categories);
if (!$id) {
throw new NotFoundException(__('Invalid post'));
}
$post = $this->Post->findById($id);
if (!$post) {
throw new NotFoundException(__('Invalid post'));
}
if ($this->request->is(array('post', 'put'))) {
$this->Post->id = $id;
if ($this->Post->save($this->request->data)) {
$this->Session->setFlash(__('Your post has been updated.'));
return $this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(__('Unable to update your post.'));
}
if (!$this->request->data) {
$this->request->data = $post;
}
}
When calling find('list'), the fields passed are used to determine what should be used as the array key and value, and optionally what to group the results by. By default, the primary key for the model is used for the key, and the display field (which can be configured using the model attribute displayField) is used for the value. Some further examples to clarify:
$justCategories = $this->Category->find('list', array(
'fields' => array('Category.name')
));
$Categories = $this->Category->find('list', array(
'fields' => array('Category.name', 'Category.name')
));
With the above code example, the resultant vars would look something like this:
$justCategories = Array
(
//[id] => 'name',
[1] => 'Books',
[2] => 'Baby',
[3] => 'Business & Industrial'
)
$Categories = Array
(
//[name] => 'name',
['Books'] => 'Books',
['Baby'] => 'Baby',
['Business & Industrial'] => 'Business & Industrial'
)
Read find(‘list’) in CakePHP

CakePHP: AUTH->LOGIN()... whether user/pass wrong...it redirects to index page [duplicate]

This question already has answers here:
Login Script in 2.4.2 is not working
(2 answers)
Closed 8 years ago.
my problem is : 'when i enter wrong username-password combination, it still redirects me to index page, while it should be redirected to login page again '.. what is the problem ??Pl help me... i am atteching my code...
here is AppController:
class AppController extends Controller {
public $components=array('DebugKit.Toolbar',
'Session','Auth' => array(
'loginRedirect' => array('controller' => 'users', 'action' => 'login'),
'logoutRedirect' => array('controller' => 'users', 'action' => 'index')
));
public function beforeFilter(){
$this->Auth->allow('index','register');
}
}
here is UsersController:
class UsersController extends AppController
{
public $name='Users';
public $uses=array('user');
public $helpers = array('Html', 'Form','Session');
public function beforeFilter() {
parent::beforeFilter();
}
public function index()
{
}
public function login() {
if ($this->request->is('post')) {
/* login and redirect to url set in app controller */
if ($this->Auth->login($this->request->data)) {
$this->Session->setFlash(__('Successful!!!'));
$this->Session->write('user',$this->data['user']['username'],time()+3600);
return $this->redirect(array('action'=>'index'));
}
$this->Session->setFlash(__('Invalid username or password, try again'));
}
// else{ echo "fail";exit;}
}
public function logout() {
/* logout and redirect to url set in app controller */
$this->Session->destroy();
return $this->redirect($this->Auth->logout());
}
public function register() {
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('controller' => 'users','action' => 'index'));
}
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
}
here is User Model:
<?php
class User extends AppModel
{
var $name='User';
var $validate=array(
'username'=> array(
'rule'=>'notEmpty',
'message'=>'Enter Your USername'),
'password'=>array(
'rule'=>'notEmpty',
'message'=>'Enter your Password'
),
'Confirm_password'=>array(
'rule'=>'match',
'message'=>'password not match, try again'
)
);
public function match(){
if($this->data['user']['password']===$this->data['user']['Confirm_password'])
{
return true;
}
return false;
}
public function beforeSave($options = array()) {
/* password hashing */
if (isset($this->data[$this->alias]['password'])) {
$this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
}
return true;
}
}
?>
here is my login ctp:
<h2>LOGIN-MYSITE</h2>
<?php echo $this->Form->create('user',array('action'=>'login'));
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->end('LOGIN');
?>
Remove 'index' from
$this->Auth->allow('index','register');
Keep
$this->Auth->allow('register');

cakephp insert data in two table within one model and control

I have Two Table ones and twos I have A Foreign Key in 'two' table two_one_id
I Want to insert data in both table at a time , means insert data within one form, so how to manage controller and model, can I make one model and one controller for this ? then How To Create The Model And Controller For This
Which Type Of Relation Should Have I Prefer For Both Table?
I Have Made Two Different Tabele One.php and Two.php
and I Have Made Two Controller OnesController.php and twosController.php
Can I Use Scaffold In Both Of Them And Using Scaffold Can I Insert Data In Two Table Within A Controller And Model, If It Is Possible Using Scaffolding , Then How Done It, Or In This Code I Have Tried Without Scaffolding , Manual Manage View */
/*One.php File
public $displayField = 'name';
public $hasOne = array(
'Two' => array(
'className' => 'Two',
'foreignKey' => 'two_one_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
}
//Two.php
<?php
App::uses('AppModel', 'Model');
class Two extends AppModel {
public $displayField = 'sname';
public $belongsTo = array(
'One' => array(
'className' => 'One',
'foreignKey' => 'two_one_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
}
//OnesController.php
<?php
App::uses('AppController', 'Controller');
/**
* Ones Controller
*
* #property One $One
* #property PaginatorComponent $Paginator
*/
class OnesController extends AppController {
/**
* Helpers
*
* #var array
*/
public $helpers = array('Html','Form');
public $uses = array('One','Two');
public $components = array('Paginator');
public function index() {
$this->One->recursive = 0;
$this->set('ones', $this->Paginator->paginate());
}
public function view($id = null) {
if (!$this->One->exists($id)) {
throw new NotFoundException(__('Invalid one'));
}
$options = array('conditions' => array('One.' . $this->One->primaryKey => $id));
$this->set('one', $this->One->find('first', $options));
}
public function add() {
if ($this->request->is('post')) {
$this->One->create();
if ($this->One->save($this->request->data)) {
$this->Session->setFlash(__('The one has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The one could not be saved. Please, try again.'));
}
}
}
public function edit($id = null) {
if (!$this->One->exists($id)) {
throw new NotFoundException(__('Invalid one'));
}
if ($this->request->is(array('post', 'put'))) {
if ($this->One->save($this->request->data)) {
$this->Session->setFlash(__('The one has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The one could not be saved. Please, try again.'));
}
} else {
$options = array('conditions' => array('One.' . $this->One->primaryKey => $id));
$this->request->data = $this->One->find('first', $options);
}
}
public function delete($id = null) {
$this->One->id = $id;
if (!$this->One->exists()) {
throw new NotFoundException(__('Invalid one'));
}
$this->request->onlyAllow('post', 'delete');
if ($this->One->delete()) {
$this->Session->setFlash(__('The one has been deleted.'));
} else {
$this->Session->setFlash(__('The one could not be deleted. Please, try again.'));
}
return $this->redirect(array('action' => 'index'));
}}
You may want to look into: $this->One->saveAll($this->request->data)
http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-saveall-array-data-null-array-options-array
You Just Set Following Code to Your Controller
OnesControllers.php
public function add() {
if ($this->request->is('post')) {
$this->One->create();
}
if (!empty($this->request->data)) {
// We can save the User data:
// it should be in $this->request->data['User']
$one = $this->One->save($this->request->data);
// If the user was saved, Now we add this information to the data
// and save the Profile.
if (!empty($one)) {
// The ID of the newly created user has been set
// as $this->User->id.
$this->request->data['Two']['two_one_id'] = $this->One->id;
// Because our User hasOne Profile, we can access
// the Profile model through the User model:
$this->One->Two->save($this->request->data);
}
}
And Set This in Your View
view/one/add.ctp
<div class="ones form">
<?php echo $this->Form->create('One'); ?>
<fieldset>
<legend><?php echo __('Add One'); ?></legend>
<?php
echo $this->Form->input('name',array('rows' => '10'));
echo $this->Form->create('Two');
echo $this->Form->input('sname');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
</div>

Auth login action not generating query in CakePHP

I have a simple login form, just like the Cake Blog Tutorial.
It works like a charm when I use 'UsersController' and 'User' model naming conventions, passing the rights queries in debug.
But when I change it to other name, Alunos in my case, it generates no QUERY and give me 'Incorrect username and/or password.'.
My login.ctp
<H1> Login </H1>
<?php
debug($this->data);
echo $this->Form->create('Aluno', array('action' => 'login'));
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->end('Login');
?>
My AppController
<?php
class AppController extends Controller {
public $components = array (
'Session',
'Auth' => array (
'loginAction' => array ('controller'=>'alunos', 'action'=>'login'),
'loginRedirect'=>array ('controller'=>'alunos', 'action'=>'inicio'),
'logoutRedirect'=>array ('controller'=>'alunos', 'action'=>'index'),
'authError'=>"Ops, você não está autorizado a fazer isso.",
'authorize'=>array('Controller'),
)
);
public function isAuthorized($user) {
return true;
}
public function beforeFilter() {
$this->Auth->allow('index', 'add');
$this->set('logged_in', $this->Auth->loggedIn());
$this->set('current_user', $this->Auth->user());
}
}
And my 'AlunosController.php' (see that its not USERSController, like common codes)
<?php
class AlunosController extends AppController {
public $name = 'Alunos';
public function beforeFilter(){
parent::beforeFilter();
}
public function index() {}
public function login(){
debug($this->Auth->login());
if ($this->request->is('post')) {
if ($this->Auth->login()){
$this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash('Incorrect username and/or password.');
}
}
}
public function logout() {
$this->redirect($this->Auth->logout());
}
public function add() {
debug($this->Auth->login());
if($this->request->is('post')) {
if ($this->Aluno->save($this->request->data)) {
$this->Session->setFlash('Cadastrado.');
}else {
$this->Session->setFlash('Falha no cadastro.');
}
}
}
public function inicio() {
debug($this->Auth->login());
}
}
?>
My debug($this->data) in login.ctp result:
array(
'Aluno' => array(
'password' => '*****',
'username' => 'anyuser'
)
)
What am I doing wrong?
Add this code to your app controller:
function beforeFilter() {
$this->Auth->userModel = 'Aluno'; <-- Should be singular. My mistake
parent::beforeFilter();
}
UPDATE FOR CAKE2
// Place in beforeFilter() of AppController.php
$this->Auth->authenticate = array(
'Form' => array(
'userModel' => 'Aluno'
)
);
Your problem is because you are not telling cake what to use for a user table. This is why your first instance works, and the second does not.
Change this:
echo $this->Form->create('Aluno', array('action' => 'login'));
to:
echo $this->Form->create('Alunos', array('url' => 'alunos/login'));
To call Alunos Controller's login() method.

Resources