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);
}
i wan't to send the same mail to multiple recipients retreived from database, using zend framework 2. With my solution i can only send email to the first row on my database, and i do not no what's the problem exactly.
This is my action in the indexController:
public function eventdetailsAction() {
$id = (int) $this->params()->fromRoute('id', 0);
$this->layout()->setVariable('lang', $this->params()->fromRoute('lang', 'en_US'));
$this->layout()->setVariable('action', $this->params()->fromRoute('action', 'index'));
$request = $this->getRequest();
$aPost = $request->getPost();
if (isset($aPost['invitUser'])) {
$user = new Container('user');
$db = $this->getServiceLocator()->get('db1');
if (!$user->offsetExists('id')) {
$idconnected = '0';
} else {
$user = new Container('user');
$db = $this->getServiceLocator()->get('db1');
if (!$user->offsetExists('id')) {
$idconnected = '0';
} else {
$idconnected = $user->offsetGet('id');
$mail = $db->query("SELECT * FROM user")->execute()->current();
print_r($mail);
exit();
$message = new Message();
foreach ($mail as $recip) {
$message->addTo($recip)
->addFrom('xxxxx#gmail.com')
->setSubject('Invitation for the event : Event Latino');
}
// Setup SMTP transport using LOGIN authentication
$transport = new SmtpTransport();
$options = new SmtpOptions(array(
'host' => 'smtp.gmail.com',
'connection_class' => 'login',
'connection_config' => array(
'ssl' => 'tls',
'username' => 'xxxxx#gmail.com',
'password' => 'xxxxxx'
),
'port' => 587,
));
$html = new MimePart('<b>Invitation for the event: Latin Night, orgonized by Mr. Jony Cornillon. Date : 06/04/2015</b>');
$html->type = "text/html";
$body = new MimeMessage();
$body->addPart($html);
//$body->setParts(array($html));
$message->setBody($body);
$transport->setOptions($options);
$transport->send($message);
}
}
}
}
And also when i put printr($mail); exit(); to show the result, only the first line will be displayed on the page. Any help please.
In the line below you are executing the query, and then obtaining the current() record from the result set the execute() call returned. That will always give you the first record in the result set.
$mail = $db->query("SELECT * FROM user")->execute()->current();
Change that to
$mail = $db->query("SELECT * FROM user")->execute();
and you should be able to iterate over the result set as expected.
i find another solution and i can succefully diplay all emails from database with print_r. However now when i put the resultset on the message->addTo(), an error will diplay. This is my new code
$sql = "SELECT * FROM user";
$statement = $db->query($sql);
$res = $statement->execute();
if ($res instanceof ResultInterface && $res->isQueryResult()) {
$resultSet = new ResultSet;
$resultSet->initialize($res);
$message = new Message();
foreach ($resultSet as $row) {
echo $row->email . PHP_EOL;
$message->addTo($row->email)
->addTo('xxxxx#hotmail.com', 'eee#web.com')
->addFrom('xxxxx#gmail.com')
->setSubject('Invitation for the event : Event Latino');
}
Any help please. Thanks.
Im new to relatively new to cakephp, right now I'm trying to use saveall() and save individual models depending on the role the user chose for the register.
Here is my View:
<?php echo $this->Form->create('User', array('type' => 'file')); ?>
<fieldset>
<legend><?php echo __('Add User'); ?></legend>
<?php
echo $this->Form->file('User.user_image');
echo $this->Form->input('User.name', array( 'label' => 'Nombre'));
echo $this->Form->input('User.last_name', array( 'label' => 'Apellidos' ));
echo $this->Form->input('User.email', array( 'label' => 'E-Mail' ));
echo $this->Form->input('User.password', array( 'label' => 'Contraseña' ));
echo $this->Form->input('User.phone', array( 'label' => 'Telefono' ));
//echo $this->Form->input('created_ip_connection');
//echo $this->Form->input('last_ip_connection');
echo $this->Form->input('User.group_id', array('empty' => 'Elige un rol', 'label' => 'Rol de Usuario'));
?>
<div style="display: none;" id="companyAdd">
<legend><?php echo __('Datos de Compañia'); ?></legend>
<?php
echo $this->Form->input('Address.exterior_number', array( 'label' => 'Numero Exterior', 'required' => false ));
echo $this->Form->input('Address.internal_number', array( 'label' => 'Numero Interior', 'required' => false ));
echo $this->Form->input('Address.street', array( 'label' => 'Calle', 'required' => false ));
echo $this->Form->input('Address.suburby', array( 'label' => 'Colonia', 'required' => false ));
echo $this->Form->input('Address.country_id', array('empty' => 'Selecciona País', 'label' => 'Pais', 'required' => false));
echo $this->Form->input('Address.state_id', array('empty' => 'Selecciona País', 'label' => 'Estado', 'required' => false));
echo $this->Form->input('Address.city_id', array('empty' => 'Selecciona Estado', 'label' => 'Municipio', 'required' => false));
echo $this->Form->input('Company.name', array( 'label' => 'Nombre de Compañia', 'required' => false ));
echo $this->Form->input('Company.description', array( 'label' => 'Descripción de Compañia', 'required' => false ));
echo $this->Form->input('Company.bank_acc', array( 'label' => 'Cuenta de Banco', 'required' => false ));
echo $this->Form->input('Company.rfc', array( 'label' => 'RFC', 'required' => false ));
?>
</div>
<div style="display: none;" id="userAdd">
<legend><?php echo __('Datos de Comprador/Proveedor'); ?></legend>
<?php
echo $this->Form->input('Buyer.company_id', array('empty' => 'Elige Comapñia', 'label' => 'Compañia', 'required' => false));
?>
</div>
</fieldset>
<?php echo $this->Form->end(__('Registrar')); ?>
Here is my controller:
public function register(){
$this->layout = 'generalLayout';
if ($this->request->is('post')) {
if($this->request->data['User']['group_id'] == 1){
$this->User->create();
if(!empty($this->data))
{
//Check if image has been uploaded
if(!empty($this->data['User']['user_image']['name']))
{
$file = $this->data['User']['user_image']; //put the data into a var for easy use
$ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
$arr_ext = array('jpg', 'jpeg', 'gif'); //set allowed extensions
//only process if the extension is valid
if(in_array($ext, $arr_ext))
{
//do the actual uploading of the file. First arg is the tmp name, second arg is
//where we are putting it
$destinationPath = 'images\users\\';
$randomCode = substr(md5(uniqid(rand(), true)), 5, 5);
$filename = $this->data['User']['name'].'_'.$randomCode."_".$file['name'];
move_uploaded_file($file['tmp_name'], WWW_ROOT . $destinationPath . $filename);
//prepare the filename for database entry
$this->request->data['User']['user_image'] = $filename;
}
}
$this->request->data['User']['created_ip_connection'] = $this->request->clientIp();
$this->request->data['User']['last_ip_connection'] = $this->request->clientIp();
if ($this->User->saveAll($this->request->data['User'])) {
$this->Session->setFlash(__('The user has been saved.'));
return $this->redirect(array('action' => 'register'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
//now do the save
//$this->products->save($this->data) ;
}
}
if($this->request->data['User']['group_id'] == 2){
$this->User->create();
if(!empty($this->data))
{
//Check if image has been uploaded
if(!empty($this->data['User']['user_image']['name']))
{
$file = $this->data['User']['user_image']; //put the data into a var for easy use
$ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
$arr_ext = array('jpg', 'jpeg', 'gif'); //set allowed extensions
//only process if the extension is valid
if(in_array($ext, $arr_ext))
{
//do the actual uploading of the file. First arg is the tmp name, second arg is
//where we are putting it
$destinationPath = 'images\users\\';
$randomCode = substr(md5(uniqid(rand(), true)), 5, 5);
$filename = $this->data['User']['name'].'_'.$randomCode."_".$file['name'];
move_uploaded_file($file['tmp_name'], WWW_ROOT . $destinationPath . $filename);
//prepare the filename for database entry
$this->request->data['User']['user_image'] = $filename;
}
}
$this->request->data['User']['created_ip_connection'] = $this->request->clientIp();
$this->request->data['User']['last_ip_connection'] = $this->request->clientIp();
if ($this->User->saveAll($this->request->data)) {
$this->Session->setFlash(__('The user has been saved.'));
return $this->redirect(array('action' => 'register'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
//now do the save
//$this->products->save($this->data) ;
}
}
if($this->request->data['User']['group_id'] == 3){
$this->Session->setFlash(__('Group 3 Happened'));
return $this->redirect(array('action' => 'register'));
}
/*$this->Session->setFlash(__('Nothing Happened'));
return $this->redirect(array('action' => 'register'));*/
}
$groups = $this->User->Group->find('list');
$this->set(compact('groups'));
$companies = $this->User->Company->find('list');
$this->set(compact('companies'));
}
And my models relations
public $hasOne = array(
'Buyer' => array(
'className' => 'Buyer',
'foreignKey' => 'user_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'Company' => array(
'className' => 'Company',
'foreignKey' => 'user_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'Provider' => array(
'className' => 'Provider',
'foreignKey' => 'user_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
I want to either send only the information needed (Meaning the models depending on the group chosen.) through the form to the controller. or in the controller use only the models sent to save the models that I want. How could I make this work. saveAll does not work cause Im sending other models with no information through the form as well. How could I make this work ?
Also how do I get the id of the user I just saved?
Ok I found out how to do it. I used the Saving Related Model Data method. I just use the information I want from the data send by the form depending on the type of the user being created. I left the view and the model untouched. I only changed the controller for the parts of when the group_id is 2(Normal User) and 3(Semi-Admin User). Using the model relations and the information being sent I could use the save() method with each model depending on the information I was given. Here is the code I hope It helps someone:
$this->layout = 'generalLayout';
if ($this->request->is('post')) {
if($this->request->data['User']['group_id'] == 1){
$this->User->create();
if(!empty($this->data))
{
//Check if image has been uploaded
if(!empty($this->data['User']['user_image']['name']))
{
$file = $this->data['User']['user_image']; //put the data into a var for easy use
$ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
$arr_ext = array('jpg', 'jpeg', 'gif'); //set allowed extensions
//only process if the extension is valid
if(in_array($ext, $arr_ext))
{
//do the actual uploading of the file. First arg is the tmp name, second arg is
//where we are putting it
$destinationPath = 'images\users\\';
$randomCode = substr(md5(uniqid(rand(), true)), 5, 5);
$filename = $this->data['User']['name'].'_'.$randomCode."_".$file['name'];
move_uploaded_file($file['tmp_name'], WWW_ROOT . $destinationPath . $filename);
//prepare the filename for database entry
$this->request->data['User']['user_image'] = $filename;
}
}
$this->request->data['User']['created_ip_connection'] = $this->request->clientIp();
$this->request->data['User']['last_ip_connection'] = $this->request->clientIp();
if ($this->User->saveAll($this->request->data['User'])) {
$this->Session->setFlash(__('The user has been saved.'));
return $this->redirect(array('action' => 'register'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
//now do the save
//$this->products->save($this->data) ;
}
}
if($this->request->data['User']['group_id'] == 2){
$this->User->create();
if(!empty($this->data))
{
//Check if image has been uploaded
if(!empty($this->data['User']['user_image']['name']))
{
$file = $this->data['User']['user_image']; //put the data into a var for easy use
$ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
$arr_ext = array('jpg', 'jpeg', 'gif'); //set allowed extensions
//only process if the extension is valid
if(in_array($ext, $arr_ext))
{
//do the actual uploading of the file. First arg is the tmp name, second arg is
//where we are putting it
$destinationPath = 'images\users\\';
$randomCode = substr(md5(uniqid(rand(), true)), 5, 5);
$filename = $this->data['User']['name'].'_'.$randomCode."_".$file['name'];
move_uploaded_file($file['tmp_name'], WWW_ROOT . $destinationPath . $filename);
//prepare the filename for database entry
$this->request->data['User']['user_image'] = $filename;
}
}
$this->request->data['User']['created_ip_connection'] = $this->request->clientIp();
$this->request->data['User']['last_ip_connection'] = $this->request->clientIp();
if ($this->User->save($this->request->data['User'])) {
//Obtener el Id de user guardado
$userId = $this->User->id;
$this->request->data['Buyer']['user_id'] = $userId;
$this->request->data['Provider'] = $this->request->data['Buyer'];
if ($this->User->Buyer->save($this->request->data['Buyer']) && $this->User->Provider->save($this->request->data['Provider'])){
$this->Session->setFlash(__('The user has been saved.'));
return $this->redirect(array('action' => 'register'));
} else {
$this->Session->setFlash(__('The Buyer or Provider could not be saved. Please, try again.'));
}
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
//now do the save
//$this->products->save($this->data) ;
}
}
if($this->request->data['User']['group_id'] == 3){
/*echo print_r($this->request->data);
return false;*/
$this->User->create();
if(!empty($this->data))
{
//Check if image has been uploaded
if(!empty($this->data['User']['user_image']['name']))
{
$file = $this->data['User']['user_image']; //put the data into a var for easy use
$ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
$arr_ext = array('jpg', 'jpeg', 'gif'); //set allowed extensions
//only process if the extension is valid
if(in_array($ext, $arr_ext))
{
//do the actual uploading of the file. First arg is the tmp name, second arg is
//where we are putting it
$destinationPath = 'images\users\\';
$randomCode = substr(md5(uniqid(rand(), true)), 5, 5);
$filename = $this->data['User']['name'].'_'.$randomCode."_".$file['name'];
move_uploaded_file($file['tmp_name'], WWW_ROOT . $destinationPath . $filename);
//prepare the filename for database entry
$this->request->data['User']['user_image'] = $filename;
}
}
//Save the user
$this->request->data['User']['created_ip_connection'] = $this->request->clientIp();
$this->request->data['User']['last_ip_connection'] = $this->request->clientIp();
if ($this->User->save($this->request->data['User'])) {
//Get the id of the user I just saved
$userId = $this->User->id;
if ($this->User->Company->Address->save($this->request->data["Address"])) {
$addressId = $this->User->Company->Address->id;
$this->request->data['Company']['user_id'] = $userId;
$this->request->data['Company']['address_id'] = $addressId;
$this->request->data['Company']['permision'] = true;
if ($this->User->Company->save($this->request->data["Company"])) {
$companyId = $this->User->Company->id;
$this->request->data['Buyer']['user_id'] = $userId;
$this->request->data['Buyer']['company_id'] = $companyId;
$this->request->data['Provider'] = $this->request->data['Buyer'];
if ($this->User->Buyer->save($this->request->data['Buyer']) && $this->User->Provider->save($this->request->data['Provider'])){
$this->Session->setFlash(__('The user has been saved.'));
return $this->redirect(array('action' => 'register'));
} else {
$this->Session->setFlash(__('The Buyer or Provider could not be saved. Please, try again.'));
}
} else {
$this->Session->setFlash(__('The company could not be saved. Please, try again.'));
}
} else {
$this->Session->setFlash(__('The Address could not be saved. Please, try again.'));
}
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
//now do the save
//$this->products->save($this->data) ;
}
}
/*$this->Session->setFlash(__('Nothing Happened'));
return $this->redirect(array('action' => 'register'));*/
}
$groups = $this->User->Group->find('list');
$this->set(compact('groups'));
$companies = $this->User->Company->find('list');
$this->set(compact('companies'));
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
In my UsersController.php
public function uploadFile()
{
$filename = '';
if ($this->request->is('post')) {
$uploadData = $this->data['uploadFile']['image'];
if ( $uploadData['size'] == 0 || $uploadData['error'] !== 0) {
return false;
}
$filename = basename($uploadData['name']);
if ($this->User->save($filename)) {
$this->Session->setFlash(__('Your imagename has been saved.'));
}
$uploadFolder = WWW_ROOT. 'files';
$filename = time() .'_'. $filename;
$uploadPath = $uploadFolder . DS . $filename;
if( !file_exists($uploadFolder) ){
mkdir($uploadFolder);
}
if (!move_uploaded_file($uploadData['tmp_name'], $uploadPath)) {
//$this->set('pdf_path', $fileName);
return false;
}
}
}
}
And in my uploadfile.ctp
<?php
echo $this->Form->create('uploadFile', array( 'type' => 'file'));
echo $this->Form->input('image', array('type' => 'file','label' => 'Pdf'));
echo $this->Form->end('Upload file');
?>
In my db I have table name "image" along with some other fields. Now I'm not able to upload file name into db.
If you have a table name called 'image', then it should be related to the user model. $this->User->save($filename) needs at least a table field called 'filename' in the User table AND it needs to be assigned to a user via $this->User->id = $user_id;
If your image table has an image model which is related to the user model, read the book's chapter 'Saving related model data' http://book.cakephp.org/2.0/en/models/saving-your-data.html#saving-related-model-data-hasone-hasmany-belongsto