CakePHP Find Condition Breaking Submit - php

When using the conditions paramater of find, the user id doesn't submit along with the other fields.
public function add() {
if ($this->request->is('post')) {
$this->Thing->create();
if ($this->Thing->save($this->request->data)) {
$this->Session->setFlash(__('The Thing has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The Thing could not be saved. Please, try again.'));
}
}
$users = $this->Thing->User->find('list', array(
'fields' => array('User.username'),
'conditions' => array('User.ownedby' => '3')
));
$this->set(compact('users'));}
Here is my view:
<div class="things form">
<?php echo $this->Form->create('Thing'); ?>
<fieldset>
<legend><?php echo __('Add Thing'); ?></legend>
<?php
echo $this->Form->input('user_id');
?>
<div id="user-info">
</div>
</fieldset>
<?php echo $this->Form->end(__('Submit'
)); ?>
</div>
However, when I omit the condition parameter, it submits just fine. Any ideas? In case you were wondering, I'm using the conditions parameter to sort the list of users that results in the select dropdown this creates.
Thanks.

Related

Adding a Child in Parent View CakePHP

I am trying to add a child in a parent view in CakePHP.
Meaning, I have a Lesson I want to add to a Course in the Course view.
I tried doing it via a simple form helper - adding a $course['Lesson']:
<div class="lessons form">
<?php echo $this->Form->create($course['Lesson']); ?>
<fieldset>
<legend><?php echo __('Add Lesson'); ?></legend>
<?php
echo $this->Form->input('name');
echo $this->Form->input('description');
echo $this->Form->input('course_id', array(
'value'=>$course['Course']['id']
));
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
</div>
But that doesn't seem to do it.
Am I missing something in the Controller/Model?
let's think course controller
//course controller
public function add_lesson() {
if ($this->request->is('post')) {
$this->Lesson->create();
if ($this->Lesson->save($this->request->data)) {
$this->Session->setFlash(__('The Lesson has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The Lesson could not be saved. Please, try again.'));
}
}
$this->set('courses', $this->Course->find('list'));
}
//add_Lesson View
<?php echo $this->Form->create('Lesson', array('url' => array('controller'=>'courses', 'action'=>'add_lesson')) ); ?>
<fieldset>
<legend><?php echo __('Add Lesson'); ?></legend>
<?php
echo $this->Form->input('name');
echo $this->Form->input('description');
echo $this->Form->input('course_id');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
If you want to use Course controller you can save your data like this:
$this->Course->Lesson->save($this->request->data);
in this case you will need to make sure after submitting your form your data is structure as below:
array(
'Course' => array(
'id' => 1
),
'Lesson' => array(
'name' => 'name'
'description' => 'balbalbala'
'course_id' => 1
),
);

cakephp saving data into database

i am new in cake php.I want to insert form data into database.But could not inserted.please help
controller:
officetypesController.php
<?php
class OfficetypesController extends AppController {
public function add() {
if ($this->request->is('post')) {
$this->Officetype->create();
if ($this->Officetype->save($this->request->data)) {
$this->Session->setFlash(__('The data has been saved'));
}
$this->Session->setFlash(
__('The data could not be saved. Please, try again.')
);
}
}
}
?>
view
add.ctp
<div class="users form">
<?php echo $this->Form->create('User'); ?>
<fieldset>
<legend><?php echo __('Add User'); ?></legend>
<?php echo $this->Form->input('name');
//echo $this->Form->input('password');
echo $this->Form->input('under', array(
'options' => array('1' => 'HO', '2' => 'RO')
));
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
</div>
model
officetype.php
<?php
class Officetype extends AppModel {
}
database:
table name :officetypes ,
fields name :id,name,under
when i click submit button than showing the message "The data could not be saved. Please, try again."
public function add() {
if ($this->request->is('post')) {
$this->Officetype->create();
if ($this->Officetype->save($this->request->data)) {
$this->Session->setFlash(__('The data has been saved'));
} else {
$this->Session->setFlash(__('The data could not be saved. Please, try again.'));
}
}
}
Check the database to see if the records are added.
Why is the form related to users if you want to add office types?
<div class="office_type form">
<?php echo $this->Form->create('Officetype'); ?>
<fieldset>
<legend><?php echo __('Add Office type'); ?></legend>
<?php echo $this->Form->input('name');
echo $this->Form->input('under', array(
'options' => array('1' => 'HO', '2' => 'RO')
));
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
</div>

CakePHP 3 step registration

I am trying to create a 3 step registration page withh cakePHP.
First step is OK, it inserts the data in db but the second step is not working. Can someone help please?
Here is my controller code:
<?php
App::uses('Controller', 'Controller');
class UsersController extends AppController {
public $name = 'Users';
public function beforeFilter(){
parent::beforeFilter();
$this->Auth->allow('signup');
}
public function login(){
if($this->request->is('post')){
if($this->Auth->login()){
$this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash('Invalid username or password!', 'default', array('class' => 'errormsg'));
}
}
}
public function logout(){
$this->redirect($this->Auth->logout());
}
// SIGN UP ACTIONS
public function signup($step = null){
// SET STEP VARIABLE
$this->set('s', $step);
// STEP 1 - REGISTER
if(empty($step)){
if ($this->request->is('post')) {
if ($this->User->save($this->request->data)) {
$this->Session->write('regUser', $this->request->data['User']['email']);
// $this->Session->setFlash('The user has been saved, please enter other information!',
// 'default', array('class' => 'okormsg'));
$regUser = $this->User->find( 'first', array('conditions' => array(
'User.username' => $this->Session->read('regUser'))));
$id = $regUser['User']['id'];
$this->Session->write('regUserId', $id);
$this->redirect(array('personal-info'));
} else {
$this->Session->setFlash( 'There was an error, please check the fields bellow!',
'default', array('class' => 'errormsg'));
}
}
// STEP 2 - PERSONAL INFORMATION
} elseif($step == 'personal-info') {
if ($this->request->is('post')) {
$id = $this->Session->read('regUserId');
$this->User->id = $id;
if ($this->User->save($this->request->data)) {
$this->Session->setFlash('The user has been saved');
$this->redirect(array('complete'));
} else {
$this->Session->setFlash('User could not be saved. Please, try again.');
}
}
// STEP 3 - COMPLETE REGISTRATION
} elseif($step == 'complete') {
}
}
}
?>
Here is the Model:
<?php
class User extends AppModel {
public $validate = array (
'name'=>array(
'Please enter your name!'=>array(
'rule'=>'notEmpty',
'message'=>'Please enter your name!'
)
),
'surname'=>array(
'Please enter your surname!'=>array(
'rule'=>'notEmpty',
'message'=>'Please enter your surname!'
)
),
'email'=>array(
'Valid email'=>array(
'rule'=>array('email'),
'message'=>'Please enter a valid Email address!'
),
'Already exists'=>array(
'rule'=>'isUnique',
'message'=>'This Email is already registered in our database!'
)
),
'password'=>array(
'Not empty'=>array(
'rule'=>'notEmpty',
'message'=>'Please enter your password!'
),
'Match password'=>array(
'rule'=>'matchPasswords',
'message'=>'Your passwords do not match!'
)
),
'password_confirm'=>array(
'Not empty'=>array(
'rule'=>'notEmpty',
'message'=>'Please confirm your password!'
)
),
'terms'=>array(
'Agree'=>array(
'rule'=>'notEmpty',
'required'=>true,
'message'=>'You must agree to Terms and conditions!'
)
)
);
public function matchPasswords($data){
if ($data['password'] == $this->data['User']['password_confirm']){
return true;
} else {
$this->invalidate('password_confirm', 'Your passwords do not match!');
return false;
}
}
public function beforeSave(){
if(!empty($this->data['User']['password'])) {
$this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
}
if (empty($this->data['User']['username'])) {
$this->data['User']['username'] = $this->data['User']['email'];
}
return true;
}
}
?>
And here is the view for signup.ctp
<!-- SIGN UP STEPS -->
<!-- SIGN UP - 1 (REGISTER) -->
<?php if(empty($s)): ?>
<div id="register" class="container padded">
<div id="register">
<div class="paginate active">Register</div>
<div class="paginate">Personal Information</div>
<div class="paginate">Complete Registration</div>
<h1>User Registration</h1>
<p>Welcome to user registration! You can sign up yourself and start improving your business. User registration is FREE and once you register yourself you can select apropiate business package for your company and start advertising.<br />
<span style="color:#900">All field are required!</span></p>
<?php
echo $this->Form->create();
echo $this->Form->input('name');
echo $this->Form->input('surname');
echo $this->Form->input('email');
echo $this->Form->input('password');
echo $this->Form->input('password_confirm', array('label'=>'Password Confirmation','type'=>'password'));
echo $this->Form->input('terms', array('label'=>false, 'type'=>'checkbox'));
?> I accept Terms Of Use <?
echo $this->Form->end('Continue Registration');
?>
</div>
</div>
<!-- SIGN UP - 2 (PERSONAL INFO) -->
<?php elseif($s == 'personal-info'): ?>
<div id="register" class="container padded">
<div id="register">
<div class="paginate">Register</div>
<div class="paginate active">Personal Information</div>
<div class="paginate">Complete Registration</div>
<h1>User Registration</h1>
<p>Welcome to user registration! You can sign up yourself and start improving your business. User registration is FREE and once you register yourself you can select apropiate business package for your company and start advertising.<br />
<span style="color:#900">All field are required!</span></p>
<?php
echo $this->Form->create();
echo $this->Form->input('phone');
echo $this->Form->input('address');
echo $this->Form->input('city');
echo $this->Form->input('ptt', array('label'=>'Postal Code'));
echo $this->Form->input('state');
echo $this->Form->input('country');
echo $this->Form->end('Complete Registration');
?>
</div>
</div>
<!-- SIGN UP - 3 (COMPLETE) -->
<?php elseif($s == 'complete'): ?>
<div id="register" class="container padded">
<div id="register">
<div class="paginate">Register</div>
<div class="paginate">Personal Information</div>
<div class="paginate active">Complete Registration</div>
<h1>User Registration</h1>
<p>Welcome to user registration! You can sign up yourself and start improving your business. User registration is FREE and once you register yourself you can select apropiate business package for your company and start advertising.<br />
<span style="color:#900">All field are required!</span></p>
</div>
</div>
<? else: ?>
<div id="register" class="container padded">
<div id="register">
Unknown page!
</div>
</div>
<? endif; ?>
So as I said on first step it's all OK, it saves the user in DB but on second step I would like to put more information and when I submit it displays the Session flash message that User can not be saved, so that means that second user information is not saved in DB.
Please help!
Found solution. There was an error in validating. On second step it tried to validate Terms of Use checkbox. So here is the complete code of 3 STEP REGISTRATION:
USER CONTROLLER:
<?php
App::uses('Controller', 'Controller');
class UsersController extends AppController {
public $name = 'Users';
public function beforeFilter(){
parent::beforeFilter();
$this->Auth->allow('signup');
}
public function login(){
if($this->request->is('post')){
if($this->Auth->login()){
$this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash('Invalid username or password!', 'default', array('class' => 'errormsg'));
}
}
}
public function logout(){
$this->redirect($this->Auth->logout());
}
// SIGN UP ACTIONS
public function signup($step = null){
// SET STEP VARIABLE
$this->set('s', $step);
// STEP 1 - REGISTER
if(!$step){
$this->set('r', 1);
if ($this->request->is('post')) {
if ($this->User->save($this->request->data)) {
$this->Session->write('regUser', $this->request->data['User']['email']);
// $this->Session->setFlash('The user has been saved, please enter other information!',
// 'default', array('class' => 'okormsg'));
$regUser = $this->User->find( 'first', array('conditions' => array(
'User.username' => $this->Session->read('regUser'))));
$id = $regUser['User']['id'];
$this->Session->write('regUserId', $id);
$this->redirect(array('personal-info'));
} else {
$this->Session->setFlash( 'There was an error, please check the fields bellow!',
'default', array('class' => 'errormsg'));
}
}
// STEP 2 - PERSONAL INFORMATION
} elseif($step == 'personal-info') {
$id = $this->Session->read('regUserId');
$this->User->id = $id;
if ($this->request->is('post')) {
if ($this->User->save($this->request->data, array('validate' => false))) {
$this->redirect(array('complete'));
} else {
$this->Session->setFlash( 'User could not be saved. Please, try again.',
'default', array('class' => 'errormsg'));
}
}
// STEP 3 - COMPLETE REGISTRATION
} elseif($step == 'complete') {
// Send email function
}
}
}
USER MODEL:
<?php
class User extends AppModel {
public $validate = array (
'name'=>array(
'Please enter your name!'=>array(
'rule'=>'notEmpty',
'message'=>'Please enter your name!'
)
),
'surname'=>array(
'Please enter your surname!'=>array(
'rule'=>'notEmpty',
'message'=>'Please enter your surname!'
)
),
'email'=>array(
'Valid email'=>array(
'rule'=>array('email'),
'message'=>'Please enter a valid Email address!'
),
'Already exists'=>array(
'rule'=>'isUnique',
'message'=>'This Email is already registered in our database!'
)
),
'password'=>array(
'Not empty'=>array(
'rule'=>'notEmpty',
'message'=>'Please enter your password!'
),
'Match password'=>array(
'rule'=>'matchPasswords',
'message'=>'Your passwords do not match!'
)
),
'password_confirm'=>array(
'Not empty'=>array(
'rule'=>'notEmpty',
'message'=>'Please confirm your password!'
)
),
'terms'=>array(
'Agree'=>array(
'rule'=>'notEmpty',
'required'=>true,
'message'=>'You must agree to Terms and conditions!'
)
)
);
public function matchPasswords($data){
if ($data['password'] == $this->data['User']['password_confirm']){
return true;
} else {
$this->invalidate('password_confirm', 'Your passwords do not match!');
return false;
}
}
public function beforeSave(){
if(!empty($this->data['User']['password'])) {
$this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
}
if(!empty($this->data['User']['email'])){
if (empty($this->data['User']['username'])) {
$this->data['User']['username'] = $this->data['User']['email'];
}
}
}
}
?>
VIEW '/Users/signup.ctp'
<!-- SIGN UP STEPS -->
<!-- SIGN UP - 1 (REGISTER) -->
<?php if(empty($s)): ?>
<div id="register" class="container padded">
<div id="register">
<div class="paginate active">Register</div>
<div class="paginate">Personal Information</div>
<div class="paginate">Complete Registration</div>
<h1>User Registration</h1>
<p>Welcome to user registration! You can sign up yourself and start improving your business. User registration is FREE and once you register yourself you can select apropiate business package for your company and start advertising.<br />
<span style="color:#900">All field are required!</span></p>
<?php
echo $this->Form->create();
echo $this->Form->input('name');
echo $this->Form->input('surname');
echo $this->Form->input('email');
echo $this->Form->input('password');
echo $this->Form->input('password_confirm', array('label'=>'Password Confirmation','type'=>'password'));
echo $this->Form->input('terms', array('label'=>false, 'type'=>'checkbox'));
?> I accept Terms Of Use <?
echo $this->Form->end('Continue Registration');
?>
</div>
</div>
<!-- SIGN UP - 2 (PERSONAL INFO) -->
<?php elseif($s == 'personal-info'): ?>
<div id="register" class="container padded">
<div id="register">
<div class="paginate">Register</div>
<div class="paginate active">Personal Information</div>
<div class="paginate">Complete Registration</div>
<h1>User Registration</h1>
<p>This personal information are not required.<br />
<?php
echo $this->Form->create();
echo $this->Form->input('phone');
echo $this->Form->input('address');
echo $this->Form->input('city');
echo $this->Form->input('ptt', array('label'=>'Postal Code'));
echo $this->Form->input('state');
echo $this->Form->input('country');
echo $this->Form->end('Complete Registration');
?>
</div>
</div>
<!-- SIGN UP - 3 (COMPLETE) -->
<?php elseif($s == 'complete'): ?>
<div id="register" class="container padded">
<div id="register">
<div class="paginate">Register</div>
<div class="paginate">Personal Information</div>
<div class="paginate active">Complete Registration</div>
<h1>Congratulation!</h1>
<p>Your account has been created and <strong>Email</strong> has been send to your inbox. Please check you inbox and verify address by clicking on the link provided in mail.</p>
</div>
</div>
<? else: ?>
<div id="register" class="container padded">
<div id="register">
Unknown page!
</div>
</div>
<? endif; ?>
If someone wants to make registration with more steps, the rest is just the same!
You should consider splitting the steps into individual actions and views to make things simpler and easier to read/debug.
Step 1
Since you will create the User account at this point, you should automatically log in the user once saved and validated. Then you don't have to persist the information in the Session, which is bad in my experience.
An email can be sent to the user at this point from Model afterSave()
Step 2
I would move this to an action called "profile" which allows a user to update their additional profile information. Since they are already logged in you can easily find() the User and save their profile. This can be reused in the future too.
Step 3
This is just the "thank you" page from what I can see. You can redirect to the PagesController and render a simple thankyou.ctp rather than using the User Controller action which does nothing for the view.
The login can still happen even though their email address is not verified. You would only allow access to certain parts of the website until they have clicked the link sent to them in an email.
try checking $step as below.
if(!$step){
empty is used to check if array is empty or not.

Cakephp multiple drop down list with view

I'm trying to get drop down list in Cake for below two finds by list:
function add() {
if (!empty($this->data)) {
$this->User->create();
if ($this->User->save($this->data)) {
$this->Session->setFlash(__('The User has been saved', true));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The User could not be saved. Please, try again.', true));
}
$group = $this->User->Group->find('list');
$commune = $this->User->Commune->find('list');
$this->compact('group','commune');
}
}
The model already has belongsTo defined in User model for Group and Commune models with their ids but I cannot seem to get group and commune to show up as drop down list in the add view page.
Below is what I have for add view page.
<div class="Users form">
<?php echo $this->Form->create('User');?>
<fieldset>
<legend><?php __('Add User'); ?></legend>
<?php
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->input('group_id', array('type' => 'select'));
echo $this->Form->input('commune_id');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit', true));?>
</div>
<div class="actions">
<h3><?php __('Actions'); ?></h3>
<ul>
<li><?php echo $this->Html->link(__('List Users', true), array('action' => 'index'));?></li>
</ul>
</div>
Is there a reason why it's not working?
you need to use plurals in order to automatically load those options into the form fields.
$groups, $communes
Try this in the view:
$this->Form->input('Group');
Alternatively:
$this->Form->input('group_id', array('type' => 'select', 'options' => $group));
You're setting $group and $commune but the view is looking for $group_id and $commune_id.

Missing validation message in cakephp application

I'm trying to add a layout for a cakephp application but now my validation message is no longer being displayed. When validating a comment on a blog entry, the validation message thats suppose to be at the top is not displayed.
If you changing the layout means that you missed to add
<?php
if ($this->Session->check('Message.flash')){
echo $this->Session->flash();
}
?>
before the
Other possible place is in the current controller.
Search if you have code like:
$this->Session->setFlash('...');
The first code is responsible for displaying the message, while the second one is responsible for setting the message.
But the code definitely will help more :)
Here is my add function in comments_controller.php
function add(){
debug($this->data);
//if the user submitted a comment post
if (!empty($this->data)){
//display the 'add view'
$this->Comment->create();
if ($this->MathCaptcha->validates($this->data['Comment']['security_code'])) {
if ($this->Comment->save($this->data)){
$this->Session->setFlash(__('The Comment has been added.', true));
$this->redirect('/posts/index/'.$this->data['Comment']['post_id']);
}
//failed validation
else{
debug($this->data);
$this->Session->setFlash(__('Comment could not be saved. Please try again.', true));
}
}
else {
$this->Session->setFlash(__('Please enter the correct answer to the math question.', true));
$this->redirect('/posts/index/'.$this->data['Comment']['post_id']);
}
Here is my entry.ctp where my posts and comments reside:
<div id="article">
<h2><?php echo $entry[0]['Post']['title']; ?></h2>
<p class="date"><em>Modified:</em> <?php $date = new DateTime($entry[0]['Post']['modified']);
echo $date->format('Y-m-d');?></p>
<p class="date"><em>Author:</em> <?php echo $entry[0]['User']['username']; ?></p>
<p class="intro"><?php echo $entry[0]['Post']['content']; ?></p>
<h2>Comments:</h2>
<div id="comments_success"></div>
<!-- show the comment -->
<?php
echo $form->create('Comment', array('action' => 'add'));
echo $form->input('name', array('class' => 'validate[required] text-input'));
echo $form->input('email', array('class' => 'validate[required,custom[email]] text-input'));
echo $form->input('text', array('id' => 'commenttext', 'type' => 'textarea', 'label' => 'Comment:', 'rows' => '10', 'class' => 'validate[required] text-input'));
//captcha
echo $form->input('security_code', array('label' => 'Please Enter the Sum of ' . $mathCaptcha));
echo $form->input( 'Comment.post_id', array( 'value' => $entry[0]['Post']['id'] , 'type' => 'hidden') );
echo $form->end('Submit');
?>
<!-- comments -->
<ol>
<?php
foreach ($entry[0]['Comment'] as $comment) :
?>
<li>
<h3><?php echo $comment['name']; ?></h3>
<p class="date"><em>Date:</em> <?php echo $comment['created']; ?></p>
<p class="text"> <?php echo $comment['text']; ?></p>
</li>
<?php
endforeach;
?>
</ol>
</div>
This is the index function in my posts_controller
function index($entry_id = null) {
if (isset($entry_id)){
$entry = $this->Post->findAllById($entry_id);
$comments = $this->Post->Comment->getCommentsFromPostID($entry_id);
$this->set('entry' , $entry);
$this->set('mathCaptcha', $this->MathCaptcha->generateEquation());
$this->render('entry');
}
else{
$posts = $this->Post->find('all');
$this->set(compact('posts'));
}
}
I know this is old, but ust make sure you have the following code somewhere visible in your app/views/layouts/default.ctp (or whatever is your layout for this application)
<?php echo $this->Session->flash(); ?>
It will echo nothing if there is no message to be displayed, but if there is a message, then it will be output accordingly.

Categories