how to create form in cake php - cakephp

I am very new in cake php, i want to know how to create form in cake php,please describe,when we go to create a form then what i have to do,like create model and controller everything

In the view file, something like this would work:
<?php
echo $this->Form->create();
echo $this->Form->input('firstname', array('label' => 'Enter your first name:'));
echo $this->Form->input('email', array('label' => 'Enter your email address:'));
echo $this->Form->input('password', array('label' => 'Enter your password:'));
echo $this->Form->end('Save');
?>
In your controller:
if($this->request->is('post')){
$this->User->save( $this->request->data );
}
You can apply some sort of validation in your model, look in the documentation for that.

Best option to learn about cakephp is it's own doc book
But I'm providing you some basic code to create form :
$this->Form->create('ModelName');
$this->Form->input('ModelName.fieldname', array('type'=>'text', 'label'=>'Modified-Name'));
$this->Form->end(__('Submit'));
Here array('type'=>'text'...): type shows which type of input field you want.
(...'label'=>'Modified-Name'): By default it shows field text as fieldname but by using 'label' you can modify your field text.

$this->form->create('controlpage',
array(
'action'=>'controll',
'class'=>'class',
'enctype' => 'multipart/form-data',
'onsubmit'=>'return valid()'
));

Block quote
Create form in html save it as ctp
Block quote
And call it in view. enter code hereUse cake php book to read further.

Related

Cake Bake issue with views using cakephp3.0

I am new to cakephp framework and i am using cakephp3.0 now i used baking concept instead of using scaffolding. After baking it automatically generated all pages based on my tables in database and it generated code in models,controllers and views.Now my question is "if it is possible to change the code in views to change field types (from text box to radio button) according to my requirements."
Please help me.
Thanks in advance
Yes, after you bake your project you can change the fields types. Navigate to the folder where all your views are located, for example: app\View\MyViewName. Baking is a great tool to get something up and running fast. If you have a fairly structured website mostly used for data entry this is a great tool. I used it for simple data entry websites and it has saved me so much typing! Just add some data validation/constraints in the model and you're good to go!
A freshly baked view will look a little something like this:
<div class="MyForm Form">
<?php echo $this->Form->create('MyForm'); ?>
<fieldset>
<legend><?php echo __('Add My Form'); ?></legend>
<?php
echo $this->Form->input('field1');
echo $this->Form->input('field2');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
</div>
<div class="actions">
<h3><?php echo __('Actions'); ?></h3>
<ul>
<li><?php echo $this->Html->link(__('List My Forms'), array('action' => 'index')); ?></li>
</ul>
</div>
Change the input methods to look something like this:
$options = array('Y' => 'Yes', 'N' => 'No');
echo $this->Form->radio('myFields', $options);

Saving User and Detail rows with Cake 2.4.5

I am very new to cake and I was wondering how i would be able to create a new user and also be able to create the contact details
database is like so
Users
user_id
contact_detail_id
password
role_id
username
Contact_Details
contact_detail_id
address1
address2
and many other fields
In the User model I have assigned public $hasOne = array('ContactDetail');
Since the user will have one contactdetail
Now what I need to know is how would this would be saved in the add method as many said to use the saveassociated although this doesn't seem to be working.
The add view is like so and from my understanding this is correct
<?php echo $this->Form->create('User', array('action' => 'add')); ?>
<fieldset>
<legend><?php echo __('Add User'); ?></legend>
<?php
echo $this->Form->input('User.username');
echo $this->Form->input('User.password');
echo $this->Form->input('roles');
echo $this->Form->input('ContactDetail.name');
echo $this->Form->input('ContactDetail.surname');
echo $this->Form->input('ContactDetail.address1');
echo $this->Form->input('ContactDetail.address2');
echo $this->Form->input('ContactDetail.country');
echo $this->Form->input('ContactDetail.email');
echo $this->Form->input('ContactDetail.fax');
?>
<label>Are you interested in buying property in Malta?</label>
<?php
$interest_buy = array('0'=>'no','1' => 'yes');
echo $this->Form->input('ContactDetail.interest_buy_property',array('type'=>'radio','options'=>$interest_buy,'value'=>'0','legend'=>FALSE));
?>
<label>Are you interested in renting property in Malta?</label>
<?php
$interest_rent = array('0'=>'no','1' => 'yes');
echo $this->Form->input('ContactDetail.interest_rent_property',array('type'=>'radio','options'=>$interest_rent,'value'=>'0','legend'=>FALSE));
echo $this->Form->input('ContactDetail.mobile');
echo $this->Form->input('ContactDetail.phone');
echo $this->Form->input('ContactDetail.postcode');
echo $this->Form->input('ContactDetail.town');
echo $this->Form->input('ContactDetail.newsletter',array('type'=>'checkbox','label'=>'Would you like to register for the newsletter?' ,'checked'=>'1','legend'=>FALSE,));
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
Please see Arun explanation about what to put in your model first and then, you can use $this->User->saveAll(); or $this->User->saveAssociated(); to save both tables at the same time.
If you want to save ContactDetail first and then save User, You can do this second option, but it is not recomended.
$this->User->ContactDetail->create();
$this->User->ContactDetail->save($this->request->data);`
this->request->data['User']['contact_detail_id'] = $this->User->ContactDetail->id`;
$this->User->Create();
$this->User->save($this->request->data);`
But I prefer the first option, to try the first option again,
Note: Make sure ContactDetail and User relationship are there in the model like this in User Model
public $hasOne= array(
'ContactDetail' => array(
'className' => 'ContactDetail',
'foreignKey' => 'contact_detail_id'
)
);
Hope it helps.
In the first look into your database, you should use the following database structure, this will help you in a more directions:
User Model
id
username
password
role_id
ContactDetail Model
id
user_id
address1
address2
Define hasMany model relationship in the User Model with ContactDetail like:
$hasMany => array('ContactDetail');
Now populate an array of Contact details with (id => address1) pair using:
$this->ContactDetail->find('list', array('conditions' => array('user_id' => $user_id)),
'fields' => array('ContactDetail.id', 'ContactDetail.address1')));
Now to save an associated details, use SaveAssociated Method.

cakephp view printing out the same values from database

created a view function and any time i click the link to view a template, the url at the top of the page is correct but it spits out the same list of fields in the database.
the fields are
accounts - id, company name, abn
template - id, name, description, account_id
field - id, name, field type, template_id
function view(){
$accounts=$this->User->AccountsUser->find('list',
array('fields'=>array('id', 'account_id'),
'conditions' =>array('user_id' =>
$this->Auth->user('id'))));
$templates=$this->Template->find('first',
array('conditions' => array(
'Template.account_id' => $accounts)));
$fields=$this->Field->find('all',
array('conditions' => array(
'Field.template_id' => Set::extract('/Template/id', $templates))));
$this->set('template', $templates);
$this->set('account', $accounts);
$this->set('field', $fields);
}
here is the view
<div class = "conlinks">
</br></br></br></br></br><h2>Here is your template fields</h2></br>
<?php foreach($field as $fields): ?>
<tr>
<td align='center'><?php echo $fields['Field']['name']; ?>
</tr></br>
<?php endforeach; ?>
</div>
so the problem is its grabbing the exact same list of fields, not the correct template_id when it prints out the fields
You should be able to debug this for yourself. Just narrow the bug down step by step.
For starters, in your view function, do a print_r on the following variables, and make sure each one contains a logical result:
$accounts
$templates
$fields
If you find unexpected results there, I'd be looking at the parameters you pass into each of your finds, and making sure they're OK. You're passing in $accounts as an array to your find condition - make sure it matches the format that cake expects. Do the same for Set::extract('/Template/id', $templates).
Also look at the SQL that Cake is producing.
If you're not already using it, I'd highly recommend installing Cake's Debug Kit Toolbar - https://github.com/cakephp/debug_kit/ because it makes debugging variables and SQL much easier.
If you do the above steps and can't solve your problem, you should at least be able to narrow it down to a line or two of code. Update your answer to show what line or two is causing the problem, and include print_r's of some of the variables you're working with. That should help others on StackOverflow to give you a specific answer.
Hope that helps!
the issue was I wasn't getting the parameters when click the link
function view($name){
$fields = $this->Template->Field->find('list',array(
'fields'=> array('name'),
'conditions' => array(
'template_id'=> $name)));
$this->set('field', $fields);
}
and the view
<div class = "conlinks">
</br><h2>Here is your template fields</h2>
<?php foreach($field as $name): ?>
<tr>
<td align='center'>
<?php echo $name; ?>
</tr></br>
<?php endforeach; ?>
</br>
<?php
echo $this->Html->link('Back', '/templates/view', array('class' => 'button'));?>
</div>

cakephp Form helper $this->data empty

I have a problem with the Form Helper that returned $this->data keeps being empty. In my Forms before there was no problems and I cant figure out what's different here.
For this Form there's not a model containing the data, its just user input for doing a search.
This is my View:
<?php
echo $this->Form->create();
echo $this->Form->input('Postleitzahl');
$options=array('10'=>10,'20'=>20);
echo $this->Form->input('Entfernung',array('type'=> 'select' , 'options'=>array(($options))));
echo $this->Form->end('Suchen');
?>
<?php
echo $this->Form->create(null, array('type' => 'post')); # not sure if that's needed
echo $this->Form->input('Search.Postleitzahl');
$options=array('10'=>10,'20'=>20);
echo $this->Form->input('Search.Entfernung',array('options'=> $options)); # seems shorter and should work
echo $this->Form->end('Suchen');
?>
The above should result into a $this->data array containing something similar to this:
['Search']
['Postleitzahl']: 102929
['Enfernung']: 'foobar'
Just don't double array your array:
'options'=>$options
Not necessarily related to Cake, but the answer to the problem when I had it: if you're including a file upload in your POST, double-check that the file you're uploading isn't larger than the limit specified in your php.ini file.

Cakephp Validation

I am using an Account Controller which doesnt have its own table but uses User Model.
All works fine except - when I validate any form. It says validation fails (when I try to fail the validation to check) but doesnt throw the error below the field
View
<?php echo $this->Form->input('id'); ?>
<label for="UserPassword">New Password:</label>
<?php echo $this->Form->text('password', array('type' => 'password', 'value' => 'harsha')); ?><em>Password must be min 6 characters.</em> <?php echo $form->error('password'); ?>
Controller Action
if($this->User->saveField('password', $this->data['User']['password'], array('validate' => 'first'))) {
$this->Session->setFlash('Password has been changed.', 'flash-success');
} else {
$this->Session->setFlash('There was some problem with our system. Please try after some time.', 'flash-warning');
}
Try debug()ing the contents of $this->validationErrors in your view, as well as $this->data in your controller just after a form submission. This should give you a lot more information to work from.
I suspect that your problem is Cake is building form inputs based on the wrong model -- building form fields for Account.id and Account.password instead of User.id and User.password. This is because FormHelper takes its default model from the controller/view it's invoked from, which in your case appears AccountsController.
In order to generate the User.id and User.password fields your controller's submission handling expects, you'll need to prepend User. in your FormHelper calls. Thus:
$this->Form->input('User.id');
$this->Form->text('User.password');
Have you tried:
echo $session->flash();
Note that whatever the manual says, it returns, not echoes. I logged this a while back and it has been changed in the 1.3 manual, but not the 1.2.
Hi you who's asking If you want to show error-message that return from UserModel's validate So you can add line code bellow after input form password
<?php
if ($this->Form->isFieldError('password')) {
echo $this->Form->error('password', array('class' => 'error'));
?>
and if you want to show error-message that set by method setFlash
you must redirect page and then use $this->Session->flash('flash-name') in page you want to show it
<?php
//in UsersController
$this->Session->setFlash('message here', 'flash-name');
//in view
echo $this->Session->flash('flash-name');
?>
Good luck!

Resources