CakePHP How to get data from csv file after upload - cakephp

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.

Related

search bar using cakephp

I'm new when it comes to work with CakePHP. I'm facing a problem that is bothering me since i started doing it. I got a form with an input and when a person types in what he/she wants (it is a classified website where you can search for something that you'd like to buy eg. a blue pen) it shows the page that refers to the desired object. For example. if i type in 'blue pen', it retrieves all the data that i have in my database related to the blue pen.
Hope you can help me, there is my code:
index.ctp
<?php
echo $this->Form->create('Location', array('type' => 'get'));
echo $this->Form->input('Find');
echo $this->Form->end();
?>
and my ArticlesController
public function search() {
$obj = '';
if (!empty($this->data)) {
$obj = $this->data['Location']['Procurar'];
$opts = array(
'conditions' => array('Location.Procurar' => $obj)
);
}
$this->set('obj', $obj); // so the keyword is saved. Can also get it via $this->data
}

extract variables from find first

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.

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 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.

File upload error cakephp

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.

Resources