File upload error cakephp - file

When I choose an image and push upload, I get this error in my controller:
Notice (8): Undefined index: File [APP/controllers/garage_car_images_controller.php, line 22]
I've also noticed that the $form->create line shown below does NOT generate form code in the inspected html. This is VERY weird.
Any ideas how to fix this? Thanks!
My view code:
<div class="title_plate">
<h1 id="title_plate_header">add image</h1>
</div>
<div id="overlay_content">
<?php
echo $form->create('GarageCarImage', array('controller' => 'garage_car_images','action' => 'add', 'type' => 'file'));
echo $form->file('File');
echo $form->hidden('garage_car_id', array('value' => $this->params['pass'][0]));
echo "<br><br>";
echo "Make this image the default? " . $form->input('default', array('type' => 'select', 'label' => false, 'options' => array('0' => 'No', '1' => 'Yes')));
echo "<br>";
echo $form->submit('Upload');
echo $form->end();
?>
</div>
My controller code:
if (!empty($this->data) &&
is_uploaded_file($this->data['GarageCarImage']['File']['tmp_name'])) {
$fileData = fread(fopen($this->data['GarageCarImage']['File']['tmp_name'], "r"),
$this->data['GarageCarImage']['File']['size']);
$this->data['GarageCarImage']['type'] = $this->data['GarageCarImage']['File']['type'];
$this->data['GarageCarImage']['user_id'] = $this->Auth->user('id');
$this->GarageCarImage->save($this->data);
}

Are you sure it doesn't generate the form code? If it didn't, I don't think you would even be able to try and submit a form. I believe submitting the form occurs because you seem to issue a request for /garageCarImages/index -- to me, that says that the form is getting generated properly.
If indeed that is the case, you should just change the value of the first parameter to the name of the controller that you want the code to execute in. For me, typically, I use an Attachment controller to do this, so I would put:
echo $form->create( 'Attachment', array(...) );
Your situation will depend on where the code is located to process the upload. Most likely it's the ImageController (guessing here...), but I'm not sure without knowing more details of your system.

Related

Cakephp Formhelper : disable required on textarea

I am trying to disable the required on that text input in my form.
However, even with
['required' => false], ['allowEmpty' => true]
which remove "required=required" from the HTML, I still get greeted with a 'This field cannot be left empty' when I try to make it be empty.
This string is located in Validator.php from what I see, but even though I tried editing or deleting what I thought was causing this, I did not find my way through.
I'm using cakephp 3.0.2
Here's my little form :
<?php
echo $this->Form->create($schedule);
echo $this->Form->input('year', [array('type' => 'text', 'readonly' => 'readonly')]);
echo $this->Form->input('month',[array('type' => 'text', 'readonly' => 'readonly')]);
echo $this->Form->input('text', ['required' => false], ['allowEmpty' => true]);
echo $this->Form->button(__('Save'));
echo $this->Form->end();
?>
Thanks for the time you'll give me.
How is your model defined? Do you have a
public $validate = array()
defined? Are you sure you did not set required=true there, and did you set 'allowEmpty => true there? Because that's where that validation belongs rather than in the form, so you should first check you're not contradicting yourself.

CakePHP How to get data from csv file after upload

I created a form with input type file, button submit to access to a function in controller, the problem is I can't get data from that file.
in controller when I call :
function displayAll() {
$adherents = $_FILES['file']['tmp_name'];
prd($adherents);
}
I found this error
Undefined index: file [APP\controllers\adherents.php, line 36]
and this is the view:
<h2>Upload filer</h2>
<br>
<fieldset class="pano bleu">
<?php echo $this->Form->create('adherentsSuph', array('action'=>'displayAll'));?>
<?php
echo $this->Form->input('file', array('type' => 'file'));
echo $bouton->block(array(
'cancel'=>array('action'=>'index'),
'submit'=>array('id'=>'addAdherentFile')
));
echo $this->Form->end();?>
</fieldset>
Add 'type' => 'file' to your form options like this:
<?php echo $this->Form->create('adherentsSuph', array('action'=>'displayAll', 'type' => 'file')); ?>
Check if is a valid request and a valid file, then use file() to read the entire file into an array and loop it.
if (!empty($this->data)) {
if (is_file($this->data['file']['tmp_name'])) {
$file = file($this->data['file']['tmp_name']);
foreach ($file as $key => $row) {
var_dump($row); die;
}
}
}
See also:
file()
is_file()
Form > Options > Type
Field naming convention
Debug $this->data to check if you need to change $this->data['file'] to $this->data['adherentsSuph']['file']
Your question is of poor quality since you are giving incomplete code. I will try to help you anyway.
Please check the following things:
Are you using the CakePHP FormHelper?
If so make sure you initialize the Form with 'type' => 'file' (see here).
Finally check, what you get in $this->request->data in your Controller.

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.

Resources