How to save this data in cakePHP? - php

I have a User Model and a Boarder Model, Not every User is a Boarder but Every Boarder is a User.
User model
class User extends AppModel
{
public $primaryKey = "user_id";
public $hasMany = 'Boarder';
}
Boarder model
class Boarder extends AppModel
{
public $belongsTo = 'User';
}
add.ctp of my Boarders View
<?php
echo $this->Form->create('Boarder', array('role' => 'form', 'novalidate' => true));
echo $this->Form->input('user_name');
echo $this->Form->input('bdr_home_address');
echo $this->Form->end();
?>
So during submit, add function in controller will now receive an array something like this
Array
(
[Boarder] => Array
(
[user_name] => 'John',
[bdr_home_address] => 'Some Street, Some City'
)
)
[user_name] will be saved in Users Model while [bdr_home_address] will be saved in Boarders model. as indicated in my $this->Form->create the request will be directed to BoardersController, action add. So how will I be able to save this?
BoardersController
class BoardersController extends AppController
{
public function add()
{
}
}

If every Boarder is a User, the Boarder table should include a user_id field.
The add.ctp form can look like
<?php
echo $this->Form->create('Boarder', array('role' => 'form', 'novalidate' => true));
echo $this->Form->input('User.username');
echo $this->Form->input('Boarder.home_address');
echo $this->Form->submit();
echo $this->Form->end();
?>
The add function from the controller is:
public function add()
{
if ($this->request->is('post')) {
debug($this->request->data);
if ($this->Boarder->saveAssociated($this->request->data)) {
// saved
} else {
// not saved
}
}
}

Related

Session value saved to database in yii

In the form when I echo the session value it is prompted no errors, but when I try to save it on the database in the model the value is not saved.
Here is my view:
(I just posted here what I think is needed.)
<?php
$userid = Yii::app()->session['iduser'];
echo $userid;
?>
Here is my controller:
The contentid, title and content are saved in the database only the userid is my problem. In my database I set the userid as int(11) not null
public function actionContent(){
$model=new ContentForm;
if(isset($_POST['ContentForm'])) {
$model->attributes=$_POST['ContentForm'];
if($model->save())
$this->redirect(array('content','contentid'=>$model->contentid));
$this->redirect(array('content','title'=>$model->title));
$this->redirect(array('content','content'=>$model->content));
$this->redirect(array('content','userid'=>$model->userid));
}
$this->render('content',array('model'=>$model));
}
And here is my model:
<?php
class ContentForm extends CActiveRecord{
public $content;
public $title;
public $userid;
public function tableName(){
return 'tbl_content';
}
public function attributeLabels(){
return array(
'contentid' => 'contentid',
'content' => 'content',
'title' => 'title',
'userid' => 'userid',
);
}
public function rules(){
return array(
array('content, title, userid', 'safe'),
);
}
}
Your user id Stored in Session it can accessed anywhere in the MVC
Try this on your controller
public function actionContent(){
$model=new ContentForm;
if(isset($_POST['ContentForm'])) {
$model->attributes=$_POST['ContentForm'];//The post values
$model->userid=Yii::app()->session['iduser'];
if($model->save())
$this->redirect(array('content','contentid'=>$model->contentid));
//$this->redirect(array('content','title'=>$model->title));
//$this->redirect(array('content','content'=>$model->content)); //Why this to many redirects here the first redirect only works here
//$this->redirect(array('content','userid'=>$model->userid));
}
$this->render('content',array('model'=>$model));
}

Unable to Show error message in cakephp 2.x validations

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

How to create multiple objects in add method of controller with CakePHP

I have a ProductsController with an add view that as an autocomplete field ('brand_name') on it where the user can enter a brand name.
In my handler I want to check if the brand name already exists in the database, the brand_id should be set on the product. If it does not exists in the database, a new Brand should be created and inserted in the database.
The code beneath is simplified:
app/Model/Product.php
class Product extends AppModel {
public $belongsTo = array('Brand');
}
app/Controller/ProductsController.php
class ProductsController extends AppController {
public $helpers = array('Html', 'Form', 'Session');
public $components = array('Session');
public function add() {
if ($this->request->is('post')) {
$this->Product->create();
$brand = $this->Product->Brand->find(
'first',
array(
'conditions' => array(
'Brand.name' => $this->request->data['Product']['brand_name']
)
)
);
if($brand)
{
$this->request->data['Product']['brand_id'] = intval($brand['Brand']['id']);
}
else
{
// Add new brand
//$this->Product->Brand->create();
$this->Product->Brand->name = $this->request->data['Product']['brand_name'];
}
if ($this->Product->saveAll($this->request->data)) {
$this->Session->setFlash(__('The product has been saved.'));
//$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('Unable to add the product.'));
}
}
}
}
Everything works fine, except for creating and inserting the new Brand object. How do I create this object in code?
I'm brand new to CakePHP so if my approach is wrong, please let me know.
I've fixed this by adding a new value to the $this->request->data array, like this:
if($brand)
{
$this->request->data['Product']['brand_id'] = intval($brand['Brand']['id']);
}
else
{
$this->request->data['Brand']['name'] = $this->request->data['Product']['brand_name'];
}

CakePHP - Only one Query from external Model

I've two Models:
class Post extends AppModel {
var $name = 'Post';
var $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id'
)
);
}
and
class User extends AppModel {
var $name = 'User';
var $hasMany = 'Post';
}
Now I'm having a problem with a query in the PostsController. I've an add() function and the view add.ctp which is basically a form. Now I would like to show some User information in that form.
class PostsController extends AppController {
var $name = 'Posts';
var $helper = array('Html', 'Form');
var $uses = array('User');
public function index() {
$this->set('posts', $this->Post->find('all'));
}
function add() {
$user_id = 1;
$this->set('user', $this->User->findById($user_id));
if ($this->request->is('post')) {
if ($this->Post->save($this->request->data)) {
$this->Session->setFlash('Your post has been saved.');
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash('Unable to add your post.');
}
}
}
}
But now the add-view-page shows that actually two queries where triggered. So if I print_r($user) within the add-view I'm getting an array with two arrays. One for a Post with user_id = 1 and one for the actual User with id = 1. But I would like to get only the User id = 1.
Try setting recursive to false on the User model before calling findById, so you won't get any data from associated models. Like this:
function add() {
$user_id = 1;
$this->User->recursive = false;
$this->set('user', $this->User->findById($user_id));
if ($this->request->is('post')) {
if ($this->Post->save($this->request->data)) {
$this->Session->setFlash('Your post has been saved.');
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash('Unable to add your post.');
}
}
}

CakePHP-2.0.4: How can i create a form to save records for has many through relation?

Post.php (posts table):
<?php
class Post extends AppModel {
public $useTable='posts';
public $hasMany=array('PostsTag');
}
Tag.php (tags table):
<?php
class Tag extends AppModel {
public $useTable = 'tags';
public $hasMany = array('PostsTag');
}
PostsTag.php (posts_tags table):
<?php
class PostsTag extends AppModel {
public $useTable = 'posts_tags';
public $belongsTo = array('Post','Tag');
}
Now how can i create a form to save a post and a tag record with posts_tags record?
Is this correct?
<?php
echo $this->Form->create('Post', array('url' => array('controller' => 'posts', 'action' =>'add')));
echo $this->Form->input('Post.title');
echo $this->Form->input('Post.body',array('rows'=>'20'));
echo $this->Form->input('Post.category_id',array('type'=>'select','options'=>$categoryList) );
echo $this->Form->input('PostsTag.name',array('type'=>'text') );
echo $this->Form->input('Post.mark',array('type' => 'checkbox', 'checked' => 'true','label' => 'Publish'));
echo $this->Form->end('Add Post');
?>
What will be the input field for
echo $this->Form->input('PostsTag.name',array('type'=>'text') );
What would i write in place of 'PostsTag.name' ?
What's the way to save has many through relation records?
Can someone can answer?

Categories