extract variables from find first - cakephp

I want to prepopulate some field values for a new record. I can hard code them in as you see below but I cant extract them from the $lesson array and I cant get them from hidden fields when i set the variables in the view.
In the find I get the values I need so what is the method I use to extract the variables from the find first?
http://book.cakephp.org/2.0/en/controllers/request-response.html
$lesson=$this->set( 'lesson',$this->Lesson->find('first',$options));
if ($this->request->is('post')) {
$this->TrequestAmend->create();
$this->request->data['TrequestAmend']['lesson_id']=6; //I want o set this value to lesson_id found in find first above but how???
$this->request->data['TrequestAmend']['tutor_id']=2;
$this->request->data['TrequestAmend']['student_id']=2;
if ($this->TrequestAmend->save($this->request->data)) {
$this->Session->setFlash(__('Your Tutor Requested Amended data has been saved.'));
// return $this->redirect(array('action' => 'displayall'));
}
else
$this->Session->setFlash(__('Unable to add your post.'));
}
// view
echo $this->Form->input($lessonId, array('type' => 'hidden'));
echo $this->Form->input($tutorId, array('type' => 'hidden'));
echo $this->Form->input($stId, array('type' => 'hidden'));

$lesson = $this->Lesson->find('first', $options);
$this->request->data['TrequestAmend']['lesson_id'] = $lesson['Lesson']['id'];
$this->set(compact('lesson'));

If set values to $this->request->data of model TrequestAmend you have to make sure that you created form for this model using (I write this because you haven't posted this line here).
echo $this->Form->create('TrequestAmend');
Then you have to change variables in view when you creating form inputs to its names. So do it as follows:
echo $this->Form->input('lesson_id', array('type' => 'hidden'));
echo $this->Form->input('tutor_id', array('type' => 'hidden'));
echo $this->Form->input('student_id', array('type' => 'hidden'));
And thats all, now you should be able to prepopulate form.

Related

how to get the selected values from a drop down list in cake php

I’m new to cake php. I need to get the user selected value from a drop down list in cake php. my view code is :
echo $this->Form->create('order');
echo $this->Form->input('status', array('options' => $options, 'default' => '--Select--'));
please help me to get the values(not key).
You can simply get the user selected value into your controller's method using:
$selected_value = $this->request->data['order']['status'];
You can either check the posted data into your controller's method using:
if($this->request->is('post'))
{
pr($this->request->data);die;
$selected_value = $this->request->data['order']['status'];
}
Do like this...
echo $this->Form->input('type', array(
'options' => array('Appartment', 'Villa' , 'Residential' ,'Kiosk', 'Commercial'),
'empty' => '(choose one)'

cakephp $this->request-is("post") return false for just one form, so strange?

I have many forms in the website. They are all created in the similar way like
<?php echo $this->Form->create('SysUser');?>
<fieldset>
<legend><?php echo __('Edit Basic Information'); ?></legend>
<?php
echo $this->Form->input('SysUser.first_name');
echo $this->Form->input('SysUser.family_name',array('label'=>__("Last Name")));
echo $this->Form->input('SysUser.mobile_phone_number');
echo $this->Form->input('SysUser.user_name',array('label'=>__("Screen Name")));
echo $this->Form->input('action', array('type'=>'hidden','value'=>'edit_basic_info'));
echo $this->Form->input('SysUser.id', array('type'=>'hidden','value'=>$user["id"]));
?>
</fieldset>
<?php echo $this->Form->end(__('Submit'));?>
But the type of one form becomes "put" , not "post". I never explicitly set the type to "post" when I create these forms. I gather CakePHP sets the default value to post. Now it seems something wrong about the way I create this new special form. Oddly, this was working days ago!
I don't know what's wrong. Here is it:
<?php echo $this->Form->create('Member'); ?>
<fieldset>
<legend><?php echo __('Basic Profile Setup'); ?></legend>
<?php
echo $this->Form->input('Member.gender_id');
$w = array();
for ($i = 40; $i < 120; $i++) {
$w[$i] = $i . " kg";
}
$h = array();
for ($i = 120; $i < 230; $i++) {
$h[$i] = $i . " cm";
}
echo $this->Form->input('Member.height', array(
'options' => $h,
'empty' => __("choose one")
));
echo $this->Form->input('Member.weight', array(
'options' => $w,
'empty' => __("choose one")
));
$options['minYear'] = date('Y') - 78;
$options['maxYear'] = date('Y') - 18;
echo $this->Form->input('Member.birthdate', $options);
echo $this->Form->input('Member.residential_location_id', array('label' => __("City/Location")));
echo $this->Form->input('Member.occupation_id',array('id'=>'MemberOccupationId'));
echo $this->Form->input('action', array('type' => 'hidden', 'value' => 'create_member'));
?>
</fieldset>
<?php
echo $this->Form->end(array("label" => __('Save')));
When the Request data contains a Model.id CakeRequest::method() is set to put. The preferred way to handle this in cakephp would be as follows.
if ($this->request->is(array('post', 'put'))) {
// Code
}
You can see this in baked controller, edit actions.
Not sure why it is happening, but you can set the form type this way:
<?php echo $this->Form->create('Member', array('type' => 'post')); ?>
I had this problem as well. In my situation this was happening when I had validation errors. So for the second run, the script thought it was a PUT request instead of a POST request. Now, because it was a PUT, it didn't even get inside the if-clause where I checked if it was a POST, so it would return to the input and try to create a POST request. This was looping forever.
The solution? Checking for a NOT GET.
So you would get something like this:
if (!$this->request->is('get')){
//Save logic here
}
I have seen an example like this in the Cookbook, but I can not find it. So I have a feeling it has been updated, but as far as I am concerned you have to use this method. So you will cover a PUT, as well as a POST request.
UPDATE
It is not recommended to use this approach. It is a PUT/POST based on if the id is set in the form. Since I was setting the id based on the type of request, instead of if it actually exists, it was switching over and over again. I am using 1 form for the add and the edit action. They both use the edit.ctp which is just set up more flexible.
From the Cookbook:
If $this->request->data contains an array element named after the form’s model, and that array contains a non-empty value of the model’s primary key, then the FormHelper will create an edit form for that record.
Is that the case, perhaps? What's Member's primary key?
I had the same issue and after 4 hours searching I just resolved it appending the Model name to the fields in the view like this:
<?php echo $this->Form->create('User');?>
<?php
echo $this->Form->input('User.id');
echo $this->Form->input('User.username', array('readonly' => true));
echo $this->Form->input('User.email', array('readonly' => true));
echo $this->Form->input('User.name');
echo $this->Form->input('User.phone');
echo $this->Form->input('User.gender');
echo $this->Form->input('User.locale', array('id' => 'locale_select', 'options' => array('es' => __('Spanish'), 'en' => __('English'))));
echo $this->Form->input('User.birthday', array('type' => 'date', 'dateFormat' => 'DMY', 'minYear' => date('Y') - 100, 'maxYear' => date('Y')));
?>
<?php echo $this->Form->end(__('Save', true));?>
Well, I have to say that this code is in a plugin, so I don't know if there could be any other problems. But other forms in that plugin work perfect and this one needs to have the Model name.
One of the ways I've handled this situation is to create my own detector that defines the context of post OR put. This goes in the beforeFilter() method in AppController:
// add a simple form post detector
$this->request->addDetector('formPosted', array(
'env' => 'REQUEST_METHOD',
'options' => array('post', 'put')
));
Then when you need to check if a form has been posted (or "putted"), then:
if ($this->request->is('formPosted')) { ... }
Since the detector is added in AppController, the condition can be checked from within any controller method.

CakePHP update multiple form fields from selectbox change

I'm using CakePHP 2.2. I'm adapting a method of dynamically updating a selectbox which I got from: http://www.willis-owen.co.uk/2011/11/dynamic-select-box-with-cakephp-2-0/#comment-10773 which works without issue. It updates the 'hotels' selectbox contents when the users selects a 'region' from another select box.
On the same form, I want to automatically populate multiple 'team' fields with address details from the 'hotels' model when a user selects a 'hotel' from the selectbox.
The user can then modify the address ... all of this before the user clicks submit on the 'team' add view.
In Team\add.ctp view I have the following code:
echo "<div id='address'>";
echo $this->Form->input('address_1');
echo $this->Form->input('address_2');
echo $this->Form->input('address_3');
echo $this->Form->input('city');
echo $this->Form->input('postcode');
echo $this->Form->input('country');
echo "</div>";
...
$this->Js->get('#TeamHotelId')->event('change',
$this->Js->request(array(
'controller'=>'hotels',
'action'=>'getAddress'
), array(
'update'=> '#address',
'async' => true,
'method' => 'post',
'dataExpression' => true,
'data'=> $this->Js->serializeForm(array(
'isForm' => true,
'inline' => true))
)
)
);
In my HotelsController.php I have:
public function getAddress() {
$hotel_id = $this->request->data['Team']['hotel_id'];
CakeLog::write('debug', print_r($hotel_id, true));
$address = $this->Hotel->find('first', array(
'recursive' => -1,
'fields' => array('hotel.address_1', 'hotel.address_2', 'hotel.address_3', 'hotel.city', 'hotel.postcode', 'hotel.country'),
'conditions' => array('Hotel.id' => $hotel_id)
));
CakeLog::write('debug', print_r($address, true));
$this->set('hotels', $address);
$this->set(compact('address'));
$this->layout = 'ajax';
}
hotels\get_address.ctp:
<?php
echo $this->Form->input('Team.address_1', array('value'=> $address['Hotel']['address_1']));
echo $this->Form->input('Team.address_2', array('value'=> $address['Hotel']['address_2']));
echo $this->Form->input('Team.address_3', array('value'=> $address['Hotel']['address_3']));
echo $this->Form->input('Team.city', array('value'=> $address['Hotel']['city']));
echo $this->Form->input('Team.postcode', array('value'=> $address['Hotel']['postcode']));
echo $this->Form->input('Team.country', array('value'=> $address['Hotel']['country'])); ?>
This now works and the code has been updated.
You can not do in that way as you are trying to accomplish. However, there is a way in which you can update as you want by passing an id from dropdown using ajax and populating all the other fields on the basis of that id. Please make sure in 'update'=>#id you should put the div id of a div containing all the fields you want to show on the page where you want your contents to appear on ajax request.
Note: Please follow the Richard link which you have given i.e. www.willis-owen.co.uk, it will definitely help you that you are trying to do.

CakePHP Form Input - prevent default?

I have this in my view
<?=$this->Form->create('Company')?>
<?=$this->Form->input('Company.company_category_id')?>
<?=$this->Form->input('Company.county')?>
<?=$this->Form->input('Company.name')?>
// Here i intend to insert all model fields in order to export them
<?=$this->Form->input('ExportField.company_category_id', array('label' => 'Categorie', 'type' => 'checkbox', 'options' => null))?>
// ...
<?=$this->Form->end('Submit')?>
My problem is that the helper is "autoMagically" consider that ExportField.{field} as being the form's main model field (Company in this case).
I can use a workaround to resolve this, but I want to know if I can force it somehow maintaining this approach.
Thank's!
You are declaring model in:
<?=$this->Form->create('Company')?>
As cake doc says, All parameters are optional. Try with:
<?=$this->Form->create()?>
You can use the following:
<?php echo $this->Form->create(null, array('controller' => 'controller_name', 'action' => 'action_name')?>
<?php echo $this->Form->input('Company.company_category_id')?>
<?php echo $this->Form->input('Company.county')?>
<?php echo $this->Form->input('Company.name')?>
// Here i intend to insert all model fields in order to export them
<?php echo $this->Form->input('ExportField.company_category_id', array('label' => 'Category', 'type' => 'checkbox'))?>
// ...
<?php echo $this->Form->end('Submit')?>
If you would use ModelName as null as a first argument in $this->Form->create() method, then you can easily achieve the same you needed.

How do I write data to a HABTM association of a HABTM join table in CakePHP?

I'm trying to save data with following structure:
As you can see, there is HABTM association between users and experiences table. And another HABTM between experiences_users and tags. I created following form:
<?php echo $form->create('Experience', array('action' => 'addClassic'));?>
<?php
echo $form->input('Experience.date', array('dateFormat' => 'DMY'));
echo $form->input('Experience.time', array('timeFormat' => '24', 'empty' => array(-1 => '---'), 'default' => '-1'));
echo $form->input('Experience.name');
echo $form->input('ExperiencesUser.1.note');
echo $form->input('ExperiencesUser.1.rating');
//echo $form->input('Tags.Tags', array('multiple' => 'multiple', 'options' => $tags));
//echo $form->input('ExperiencesUser.1.Tags', array('multiple' => 'multiple', 'options' => $tags));
//echo $form->input('ExperiencesUser.1.Tags.Tags', array('multiple' => 'multiple', 'options' => $tags));
echo $form->input('ExperiencesUser.1.confirmed', array('type' => 'hidden', 'value' => '1'));
echo $form->input('ExperiencesUser.1.user_id', array('type' => 'hidden'));
echo $form->input('ExperiencesUser.2.user_id', array('type' => 'hidden'));
?>
<?php echo $form->end(__('Add', true));?>
And everything works well. saveAll method creates new Experience, assings this new experience to two users (via experiences_users) and sets the stuff around.
What bothers me is that I want to assign some Tags to newly created experiences_users record (to the first one). I thought, that should be done via some of the commented stuff. Every line of this commented code creates form and sends data to $this->data, but it never gets saved.
So my question is: What is the right syntax of $this->data or $form->input in my example to save data into experiences_users_tags?
I figured it out. Cake saveAll function works only for directly associated models. Luckily Cake is able to take care of this:
view
echo $form->input('Tags.Tags', array('multiple' => 'multiple', 'options' => $tags));
controller
$this->Experience->saveAll($data, $parameters);
$this->Experience->ExperiencesUser->save($data);
Cake after calling saveAll() fills $this->data with last inserted id. So second call save() will save data to the right table and set properly foreign keys.

Resources