Passing param through form cakePHP 2.2 - cakephp

I am in a view (view/1) and i want to pass a param to one of my functions on its controller.
I have tried this:
echo $this->Form->create('Post', array('action' => 'move'));
But then, it doesn't pass the param $id which is on the URL.
I have seen it works well on the edit view just doing this:
echo $this->Form->create('Post');
Why is it not working with my view / controller function?
Also, if i try to pass them with something like this:
echo $this->Form->create('Post', array('action' => 'move', 1));
It prints something like this:
<form action="/posts/move" 1="1"
Thanks

To pass the argument, you can simply pass the param in action as:-
echo $this->Form->create('Post', array('action' => 'move/1'));
In Controller,
debug($this->request->params['pass'][0]);
Since edit view already contains the id of the post being edited, we don't need to do explicitly pass the id in form create.

Pass it in Cake style:)
echo $this->Form->create('Post', array('action' => array( 'action' => 'move', 1 ) ));
-or-
echo $this->Form->create('Post', array('url' => Router::url( array( 'action' => 'move', 1 ) ) ));
That will accomplish it while taking routing into account.

Related

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 get PassedArgs to work in Pagination in CakePHP?

I have a page which returns results that are filtered on an organization_id. The URL looks like this:
nameofview/organization_id:1/page:2/
I'm using the built in Paginator controls and I pass $this->PassedArgs into it like this:
<div class="paging">
<?php echo $paginator->prev('<< '.__('previous', true), array('url' => $this->PassedArgs), null, array('class'=>'disabled'));?>
| <?php echo $paginator->numbers(array('url' => $this->passedArgs));?>
<?php echo $paginator->next(__('next', true).' >>', array('url' => $this->passedArgs), null, array('class'=>'disabled'));?>
</div>
The links look good for the "numbers" but don't work for Next and Previous. The links for both are taking me back to the same page. I think it is because it is passing the "Page" param.
Anyone have an idea how I can pass the correct args to $paginator->numbers?
I tried $this->passedArgs['organization_id'] but that returns errors.
Try this at the top of your view:
$paginator->options(array('url' => $this->passedArgs));
That way, you can drop array('url' => $this->passedArgs) from your prev/next/numbers lines, it should work just fine.

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