Cakephp 3.3 - Not able to save images using plugin josegonzalez - cakephp

I am not able to save the photo name and photo dir in the users table based on logged in used id.I am trying to upload the user photo for the existing user based on his used id.The photo fields are not getting updated for the existing user. I am trying to upload the photo using this plugin josegonzalez. Please help me.
<?php echo $this->Form->create($user, ['type' => 'file']); ?>
<?php echo $this->Form->input('photo',['type' => 'file', 'class' => 'form-control']); ?>
<?php echo $this->Form->input('photo_dir', ['type' => 'hidden']); ?>
<?php echo $this->Form->button(__('Submit'), ['type'=>'submit','class' => 'btn btn-success']); ?>
<?php echo $this->Form->end(); ?>
UsersTable
$this->addBehavior('Josegonzalez/Upload.Upload', [
'photo' => [
'fields' => [
// if these fields or their defaults exist
// the values will be set.
'dir' => 'photo_dir', // defaults to `dir`
],
],
]);
UsersController/add
public function add($id=null)
{
if ($this->request->is('post')) {
if (!$id) {
$id = $this->Auth->user('id');
}
$user = $this->Users->get($id);
$fileName = $this->request->data['photo']['name'];
$user->photo = $fileName;
//$user = $this->Users->patchEntity($user, $this->request->data);
if ($this->Users->save($user)) {
$this->Flash->success(__('Your photo has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('Unable to add your photo.'));
}
$this->set('user', $user);
}

Have you tried using 'enctype' in your form tag?
<form enctype="multipart/form-data">
It is explained here.

You can use Proffer plugin. It is easy to use and can be used to generate thumbnails too. I'm using it since 3.1 and working fine. It's even working on 3.3
https://github.com/davidyell/CakePHP3-Proffer

This is how it worked. I did not use any plugin. I uploaded single image at a time.
UsersController/add function.
public function add()
{
//check for logged in user authentication
$id = $this->Auth->user('id');
$user = '';
//check if the request is post
if ($this->request->is('post')) {
$user = $this->Users->get($id);
//check if upload file is not empty
if(!empty($this->request->data['photo']['name'])){
$fileName = $this->request->data['photo']['name'];
$extention = pathinfo($fileName,PATHINFO_EXTENSION);
$arr_ext = array('jpg', 'jpeg', 'gif','png');
//check for uploded file extension
if(in_array($extention, $arr_ext)){
$newfileName=$id.'.'.$extention;
$destDir = WWW_ROOT .'img'. DS .'users'. DS . $newfileName;
//move uploded file to destination
if(move_uploaded_file($this->request->data['photo']['tmp_name'],$destDir)){
$user->photo = $newfileName;
//save the uploded image in user table
if ($this->Users->save($user)) {
$this->Flash->success(__('Your profile photo has been uploaded successfully.'));
return $this->redirect([
'controller' => 'Users',
'action' => 'view', $id
]);
} else{
$this->Flash->error(__('Unable to upload image, please try again.'));
}
}else{
$this->Flash->error(__('Unable to upload image, please try again.'));
}
}else{
$this->Flash->error(__('Please choose a image to upload.'));
}
}
}
$this->set(compact('user'));
$this->set('_serialize', ['user']);
$this->set('id', $id);
}

Related

How to upload multiple images and save it in server using cakephp 3.3

I am using cakephp 3.3. I am able to upload single image but it is not getting saved under webroot/uploads. I want to upload multiple images and save it. How can I achieve it? Please provide some inputs. I am very new to PHP programming and this framework.Thanks!
`Images\add.ctp
<?= $this->Form->create($image,['type' => 'file']) ?>
<fieldset>
<legend><?= __('Add Image') ?></legend>
<?php
echo $this->Form->input('path',['type' => 'file']);
?>
</fieldset>`
ImagesController\add
public function add()
{
$image = $this->Images->newEntity();
if ($this->request->is('post')) {
$image = $this->Images->patchEntity($image, $this->request->data);
if ($this->Images->save($image)) {
$this->Flash->success(__('The image has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The image could not be saved. Please, try again.'));
}
}
$properties = $this->Images->Properties->find('list', ['limit' => 200]);
$this->set(compact('image', 'properties'));
$this->set('_serialize', ['image']);
}
Table\ImageTable.php
$validator
->requirePresence('path', 'create')
->notEmpty('path')
->add('processImageUpload', 'custom', [
'rule' => 'processImageUpload'
]);
public function processImageUpload($check = array()) {
if(!is_uploaded_file($check['path']['tmp_name'])){
return FALSE;
}
if (!move_uploaded_file($check['path']['tmp_name'], WWW_ROOT . 'img' . DS . 'images' . DS . $check['path']['name'])){
return FALSE;
}
$this->data[$this->alias]['path'] = 'images' . DS . $check['path']['name'];
return TRUE;
}
In add.ctp make input field something like:
echo $this->Form->input('path[]',['type' => 'file','multiple'=>'multiple']);
And in controller make save method something like this:
// $image = $this->Images->newEntity();
$images= $this->Articles->newEntities($this->request->data);
if ($this->request->is('post')) {
// $image = $this->Images->patchEntity($image, $this->request->data);
if ($this->Images->saveMany($images)) {
$this->Flash->success(__('The image has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The image could not be saved. Please, try again.'));
}
}

cakephp 2, edit record in modal by bootstrap

How to edit a record with Cakephp and modal bootstrap?
Because when I edit a contact, I get the error 500?
missing view The view for UserContactsController:: admin_modal_edit()
was not found.
In to controller admin_modal_edit() I have set $this->layout = NULL;
These are the files of the app.
File: user/view.ctp with list of contact and the modal for add or edit.
BUTTON FOR EDIT OR DELETE
<?php echo $userContact['UserContactType']['title']; ?>: <?php echo $userContact['contact']; ?>
<?php echo __('Edit'); ?>
BOOTSTRAP MODAL
<?php
echo $this->Form->create('UserContact', array('url' => array('admin' => true, 'prefix' => 'admin', 'plugin' => 'user', 'controller' => 'user_contacts', 'action' => 'modal_edit')));
?>
<?php echo $this->Form->input('UserContact.id', array('class' => 'form-control')); ?>
<?php echo $this->Form->input('UserContact.user_id', array('default' => $user_id, 'type' => 'hidden')); ?>
<?php echo $this->Form->input('UserContact.user_contact_type_id', array('class' => 'form-control', 'empty' => true)); ?>
<?php echo $this->Form->input('UserContact.contact', array('class' => 'form-control')); ?>
<?php echo $this->Form->submit(__('Save'), array('div' => false, 'class' => 'btn btn-success')); ?>
<?php echo $this->Form->end(); ?>
File: controller/UsersController.php that generates view.ctp
public function admin_view($id = null) {
if (!$this->User->exists($id)) {
throw new NotFoundException(__('Invalid user'));
}
$user_id = $id;
$options = array(
'contain' => array('UserContact' => 'UserContactType', 'UserGroup', 'UserState', 'UserGender', 'UserAddress' => 'UserAddressType', 'UserPaymentType', 'Item', 'Comment'),
'conditions' => array('User.' . $this->User->primaryKey => $id));
$this->set('user', $this->User->find('first', $options));
// blocco find list
$userContactTypes = $this->UserContactType->find('list');
$userAddressTypes = $this->UserAddressType->find('list');
$this->set(compact(array('userContactTypes', 'userAddressTypes', 'user_id')));
}
File: controller/UserContactsController.php for the modal
public function admin_modal_edit() {
$id = $this->request->query('id');
$this->layout = NULL;
if ($this->request->is('post') || $this->request->is('put')) {
if ($this->UserContact->save($this->request->data)) {
$this->Session->setFlash(__('The record has been saved'), 'flash/success');
$this->redirect(array('controller' => 'users', 'action' => 'view', $this->request->data['UserContact']['user_id']));
} else {
$this->Session->setFlash(__('The record could not be saved. Please, try again.'), 'flash/error');
}
} else {
if (!empty($id)) {
$options = array('conditions' => array("UserContact.{$this->UserContact->primaryKey}" => $id));
$this->request->data = $this->UserContact->find('first', $options);
}
}
}
Your issue is that CakePHP is trying to render the 'admin_modal_edit.ctp' View template.
If you don't want CakePHP to render anything set autoRender to false:-
public function admin_modal_edit() {
$this->autoRender = false;
}
This will prevent CakePHP from looking for a View template to render.
$this->layout = null does not stop Cake from attempting to render templates. Which I suspect is what you're trying to achieve.
This error is showing because cakephp is complaining about the function admin_modal_edit for not having a view since it cannot find the admin_modal_edit.ctp in the view folder of your controller.
To fix this, add this
$this->autoRender = false
to your function admin_modal_edit to disable the rendering of view for that function.
So your function should look like this.
public function admin_modal_edit() {
/** -------------- **/
$this->autoRender = false;
/** -------------- **/
$id = $this->request->query('id');
if ($this->request->is('post') || $this->request->is('put')) {
if ($this->UserContact->save($this->request->data)) {
$this->Session->setFlash(__('The record has been saved'), 'flash/success');
$this->redirect(array('controller' => 'users', 'action' => 'view', $this->request->data['UserContact']['user_id']));
} else {
$this->Session->setFlash(__('The record could not be saved. Please, try again.'), 'flash/error');
}
} else {
if (!empty($id)) {
$options = array('conditions' => array("UserContact.{$this->UserContact->primaryKey}" => $id));
$this->request->data = $this->UserContact->find('first', $options);
}
}
}

Array to string Error while uploading an Image

i was trying to upload image using cakephp , i got the following error :
Notice (8): Array to string conversion [CORE\Cake\Model\Datasource\DboSource.php, line 1009]
<?php echo $this->Form->create('User',array('type'=>'file'));
echo $this->Form->input('profile_pic', array('type'=>'file'));
echo $this->Form->end('submit');
?>
anything wrong with what i've did ?
You study cakephp manual properly HOW form type can be File ?????? :)
Use this
<?php echo $this->Form->create('User',array('enctype'=>'multipart/form-data'));
echo $this->Form->input('profile_pic', array('type'=>'file'));
echo $this->Form->end('submit');
?>
You need to treat the file upload in the controller. If you debug the request you'll see that profile_pic field is an array:
# in controller:
if ($this->request->is('post')) {
debug($this->request->data); die();
}
# result:
array(
'User' => array(
'profile_pic' => array(
'name' => 'wappy500x500.jpg',
'type' => 'image/jpeg',
'tmp_name' => '/tmp/phptk28hE',
'error' => (int) 0,
'size' => (int) 238264
)
)
)
Short answer:
public function upload() {
if ($this->request->is('post')) {
if(isset($this->request->data['User']['profile_pic']['error']) && $this->request->data['User']['profile_pic']['error'] === 0) {
$source = $this->request->data['User']['profile_pic']['tmp_name']; // Source
$dest = ROOT . DS . 'app' . DS . 'webroot' . DS . 'uploads' . DS; // Destination
move_uploaded_file($source, $dest.'your-file-name.jpg'); // Move from source to destination (you need write permissions in that dir)
$this->request->data['User']['profile_pic'] = 'your-file-name.jpg'; // Replace the array with a string in order to save it in the DB
$this->User->create(); // We have a new entry
$this->User->save($this->request->data); // Save the request
$this->Session->setFlash(__('The user has been saved.')); // Send a success flash message
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
}
Of course you need to make extra validations on the uploaded file.
Further reading: https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=site:stackoverflow.com+cakephp+upload+file

form data not saving and not update image files and filed name in multiple tables

in this editdrprofile.ctp file not retrieves gender field value and when am click save Drprofile link in editprofile page no action donne page refreshing no image uploaded nothing changed
app/Controller/DashboardsController.php
public function index() {
$this-> loadModel('Drprofile');
$this->set('variable', $this->Drprofile->find('all', array('conditions' => array('Drprofile.user_id' => $this->Auth->user('id')))));
}
public function editdrprofile($id = null) {
$this-> loadModel('Drprofile');
if (!$id) {
throw new NotFoundException(__('Invalid post'));
}
$post = $this->Drprofile->findByuser_id($id);
if (!$post) {
throw new NotFoundException(__('Invalid post'));
}
if ($this->request->is(array('Drprofile', 'put'))) {
$this->Drprofile->user_id = $id;
// $this->set('posts', $this->carrier->find('all'));
if($this->request->is('post')){
Configure::read();
// pr($this->data);
$this->Carrier->create();
$filename = null;
if (
!empty($this->request->data['Drprofile']['image']['tmp_name'])
&& is_uploaded_file($this->request->data['Drprofile']['image']['tmp_name'])
) {
// Strip path information
$filename = basename($this->request->data['Drprofile']['image']['name']);
move_uploaded_file(
$this->data['Drprofile']['image']['tmp_name'],
WWW_ROOT . DS . 'documents' . DS . $filename
);
//$this->data['Carrier']['Resume'] = $filename;
}
//pr($filename);
// Set the file-name only to save in the database
$this->request->data['Drprofile']['image'] = $filename;
pr($this->data);
if ($this->Drprofile->save($this->request->data)) {
// ...
/*if ($this->Carrier->save($this->request->data)) {
if ($this->Carrier->save($this->data)) {
*/
$this->Session->setFlash(__('Your Details has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('Unable to add your Details'));
}
}
/*pr_('$this->Drprofile->user_id = $id');
if ($this->Drprofile->save($this->request->data)) {
//$this->Drprofile->save($this->request->data);
$this->Session->setFlash(__('Your post has been updated.'));
return $this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(__('Unable to update your post.'));*/
}
if (!$this->request->data) {
$this->request->data = $post;
}
}
in model
app/model/Drprofile.php
<?php class Drprofile extends AppModel {
var $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
}
?>
in view/dashboards/index.ctp
<?php
foreach ($variable as $post1):
?>
<table>
<tr><h3>Doctor Profile</h3></tr>
<tr> <td>TTTTTTTTTTTTTTTTTTTTTTTTTTTT</td> <td><table>
<tr><td>Name</td><td><?php echo $post1['User']['fullname'];?></td></tr>
<tr><td>Email</td><td><?php echo $post1['User']['email'];?></td></tr>
<tr><td>Mobile</td><td><?php echo $post1['User']['contactnumber'];?></td></tr>
<tr><td>Gender</td><td><?php echo $post1['User']['gender'];?></td></tr>
<tr><td>D.O.b</td><td><?php echo $post1['Drprofile']['dob'];?></td></tr>
<tr><td>Experience</td><td><?php echo $post1['Drprofile']['exp'];?></td></tr>
</table></td></tr>
</table>
<?php
echo $this->Html->link(
'Edit Profile', array('action' => 'editdrprofile', $post1['Drprofile']['user_id'])
);
?>
<?php
endforeach; ?>
app/view/editdrprofile.ctp
<h1>Edit Post</h1>
<?php
echo $this->Form->create('Drprofile');
?>
<table>
<tr><h3>Edit profile</h3></tr>
<tr><td>Name</td><td><?php echo $this->Form->text('User.fullname'); ?></td></tr>
<tr><td>Email</td><td><?php echo $this->Form->text('User.email'); ?></td></tr>
<tr><td>Mobile</td><td><?php echo $this->Form->text('User.contactnumber'); ?></td></tr>
<tr><td>Gender</td><td><?php
$options=array('M'=>'Male','F'=>'Female');
$attributes=array('legend'=>false);
echo $this->Form->radio('User.gender',$options,$attributes);
?></td></td></tr>
<tr><td>D.O.b</td><td><?php echo $this->Form->text('dob'); ?></td></tr>
<tr><td>Experience</td><td><?php echo $this->Form->select('exp', array('options' => array('1 year','2 years ','3 years','4 years','5-10 years'))); ?></td></tr>
<tr><td><?php echo $this->Form->input('drprofile.Resume', array('between'=>'<br />','type'=>'file'));?></td></tr>
<tr><td><?php echo $this->Form->end('Save Drprofile');?></td></tr>
<?php /*?><?php echo $this->Form->input('id', array('type' => 'hidden'));?><?php */?>
</table>
First thing you are doing this in Dashboards controller, and you are creating data for Drprofile. If you in the end you want to do it in DashboardsController then you should change your from to this:
echo $this->Form->create('Drprofile', array(
'url' => array('controller' => 'dashboards', 'action' => 'editdrprofile')
));
This way you are telling form what action to use. But I would suggest you move that to DprofilesController and edit that data there.
One more thing, you closed your form there and you place $this->Form->input for id after it, change that.

Cakephp Upload Image - Can not determine the mimetype

The following validation is being done in my model
'image' => array(
'uploadErrror' => array(
'rule' => 'uploadError',
'message' => 'The image upload failed.',
'allowEmpty'=> True
),
'mimeType' => array(
'rule' => array('mimeType',array('image/gif','image/png','image/jpeg')),
'message' => 'Please only upload images (gif, png, jpg).',
'allowEmpty' => true
),
'fileSize'=> array(
'rule' => array('fileSize', '<=', '1MB'),
'message' => 'Image must be less than 1MB.',
'allowEmpty' => true
),
'processImageUpload' => array(
'rule' => 'processImageUpload',
'message' => 'Unable to process image upload.',
'allowEmpty'=> true
) )
public function processImageUpload($check = array()){
if(!is_uploaded_file($check['image']['tmp_name']))
{
return FALSE;
}
$targetdir = WWW_ROOT . 'img' . DS . 'uploads' . DS . $check['image']['name'];
if(!move_uploaded_file($check['image']['tmp_name'],$targetdir))
{
return false;
}
$this->data[$this->alias]['image'] = 'uploads' . DS . $check['image']['name'];
return true;
}
The error I am receiving is the below, I also enabled debug 2 but no further clarification was provided.
Can not determine the mimetype.
I have already tried un-commenting
extension=php_fileinfo.dll
and restarted WAMPServer fully but it still did not work.
Also in the controller class I have the following code for add
public function add() {
if ($this->request->is('post')) {
$this->Image->create();
$data = $this->request->data['Image'];
if (!$data['image']['name'])
{
$this->Session->setFlash(__('There was no image provided.'));
}
if ($this->Image->save($data)) {
$this->Session->setFlash(__('The image has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The image could not be saved. Please, try again.'));
}
}
}
Add View Code
<?php echo $this->Form->create('Image',array('type'=>'file')); ?>
<fieldset>
<legend><?php echo __('Add Image'); ?></legend>
<?php
echo $this->Form->input('description');
echo $this->Form->input('image',array('type'=>'file'));
echo $this->Form->input('property_id');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
Any suggestions would be greatly appreciated.
Not sure if this is the whole problem, but:
'mimeType' => array(
'rule' => array('mimeType',array('image/gif','image/png','image/jpeg')),
'message' => 'Please only upload images (gif, png, jpg).',
'alllowEmpty' => true
),
'alllowEmpty' has 3 L's.
The closes solution which isn't checking mime but just extension is
$ext = substr(strtolower(strrchr($check['image']['name'], '.')), 1); //get the extension
$arr_ext = array('jpg', 'jpeg', 'gif'); //set allowed extensions
if (in_array($ext, $arr_ext)) {
//upload code
}
else
{
return 'Please only upload images (gif, png, jpg).';
}
Change the text ;extension=php_fileinfo.dll into extension=php_fileinfo.dll on php.ini
It works for me. Hope it help you guys. I'm using xampp.
In general, Cake expects to find the file to check at location specified in original
$this->data[$this->alias]['image']['tmp_name'] // or whatever is the name of the field
during validation. So make sure the ...['tmp_name'] points to valid location with (still) existing uploaded file.
ORIGINAL ANSWER:
I think the problem is here (I had also similar problem):
$this->data[$this->alias]['image'] = 'uploads' . DS . $check['image']['name'];
After you move the uploaded file, you assign path infromation to $this->data[$this->alias]['image'] but CakePHP thinks that there is an array with all information about uploaded file. That is why the whole validation will fail.
To be specific, CakePHP will try to look for tmp_name in $this->data[$this->alias]['image'] but it won't find it there, after that it will try to determine mime type of "nothing" and it will fail.

Resources