How to add images in Photo Album using different Models - php

hello guys i want to create a gallery using two tables
album table and photo table
'album' holds the (album_name) and 'photo' holds the (pictures)
this is my form
//this is for my album name to album table
<?php echo $form->labelEx($model,'album_name'); ?>
<?php echo $form->textField($model,'album_name'); ?>
<?php echo $form->error($model,'album_name'); ?>
//this is for the pictures to the photo table
<?php $this->widget('CMultiFileUpload', array(
'name' => 'photo_name',
'model' => $model,
'accept' => 'jpeg|jpg|gif|png',
'duplicate' => 'File is already added!',
'remove'=>Yii::t('ui','Remove'),
'denied' => 'Not images', // useful,
'htmlOptions'=>array(
'multiple' => 'multiple',
'class' => 'btn btn-success fileinput-button',),
)); ?>
this is my controller
public function actionCreate()
{
$model = new Album;
$model2 = new Photo;
if (isset($_POST['Album'])) {
$model->attributes = $_POST['Album'];
$model2->attributes = $_POST['Photo'];
$photos = CUploadedFile::getInstancesByName('photo_name');
if (isset($photos) && count($photos) > 0) {
foreach ($photos as $pic) {
echo $pic->name.'<br />';
if ($pic->saveAs(Yii::getPathOfAlias('webroot').'/assets/photos/'.$pic->name)) {
$model2 = new Photo();
$model2->attributes = $_POST['Photo'];
$model2->photo_name = $pic->name;
$model2->photo_id = NULL;
$model2->isNewRecord= true;
$model2->save();
} else {
echo 'Cannot upload!';
}
}
}
if ($model->save())
$this->redirect(array('index'));
}
$this->render('create', array(
'model' => $model,
));
}
am i doing it the right way? because when i run this code its only adding the album_id and album_name in the album table
the photo table is empty. Also the actionCreate is in the AlbumController

Related

CakePHP3 - Upload image file

I am new in cakephp3. I have an Employee Table and I want to save an image path.
Below is my form in add.ctp
<?php echo $this->Form->create($employee, ['enctype' => 'multipart/form-data']); ?>
<fieldset>
<legend><?= __('Add Employee') ?></legend>
<?php
echo $this->Form->input('image_path', ['type' => 'file']);
echo $this->Form->input('first_name');
echo $this->Form->input('last_name');
echo $this->Form->input('birthday',
array(
'type' => 'date',
'label' => 'Birthday',
'dateFormat' => 'MDY',
'empty' => array(
'month' => 'Month',
'day' => 'Day',
'year' => 'Year'
),
'minYear' => date('Y')-130,
'maxYear' => date('Y'),
'options' => array('1','2')
)
);
echo $this->Form->input('address');
echo $this->Form->input('contact');
echo $this->Form->input('date_hired',
array(
'type' => 'date',
'label' => 'Date Hired',
'dateFormat' => 'MDY',
'empty' => array(
'month' => 'Month',
'day' => 'Day',
'year' => 'Year'
),
'minYear' => date('Y')-130,
'maxYear' => date('Y'),
'options' => array('1','2')
)
);
$status = array(
"employed" => "Employed",
"unemployed" => "Unemployed"
);
echo $this->Form->input('status', array('label'=>'Status', 'type'=>'select', 'options'=>$status));
?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
I want to make the upload function work in my EmployeesController.php. I have tried to save it using php move_uploaded_file but it is not working. Below is the controller.
public function add()
{
$employee = $this->Employees->newEntity();
if ($this->request->is('post')) {
$employee = $this->Employees->patchEntity($employee, $this->request->data);
$employee->user_id = $this->Auth->user('id');
if ($this->Employees->save($employee)) {
$this->Flash->success(__('The employee has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The employee could not be saved. Please, try again.'));
}
if(!empty($this->data))
{
//Check if image has been uploaded
if(!empty($this->data['employees']['image_path']['name']))
{
$file = $this->data['employees']['image_path']; //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
move_uploaded_file($file['tmp_name'], WWW_ROOT . 'CakePHP/app/webroot/img/' . $file['name']);
//prepare the filename for database entry
$this->data['employees']['product_image'] = $file['name'];
}
}
//now do the save
$this->Employees->save($this->data) ;
}
}
$users = $this->Employees->Users->find('list', ['limit' => 200]);
$this->set(compact('employee', 'users'));
$this->set('_serialize', ['employee']);
}
Try this structure in your View
<?= $this -> Form -> create($employee, ['type' => 'file']) ?>
...
<?= $this -> Form -> input('image_path', ['type' => 'file', 'label' => __('Select Image')]) ?>
<?= $this -> Form -> input('first_name') ?>
...
<?= $this -> Form -> end() ?>
Controller
public function add()
{
$employee = $this->Employees->newEntity();
if ($this->request->is('post'))
{
$employee = $this->Employees->patchEntity($employee, $this->request->data);
$employee['user_id'] = $this->Auth->user('id');
//Check if image has been uploaded
if(!empty($this->data['employees']['image_path']['name']))
{
$file = $this->data['employees']['image_path']; //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))
{
//name image to saved in database
$employee['product_image'] = $file['name'];
$dir = WWW_ROOT . 'img' . DS; //<!-- app/webroot/img/
//do the actual uploading of the file. First arg is the tmp name, second arg is
//where we are putting it
if(!move_uploaded_file($file['tmp_name'], $dir . $file['name']))
{
$this -> Flash -> error(__('Image could not be saved. Please, try again.'));
return $this->redirect(['action' => 'index']);
}
}
}
//now do the save
if ($this->Employees->save($employee))
{
$this->Flash->success(__('The employee has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The employee could not be saved. Please, try again.'));
}
}
$users = $this->Employees->Users->find('list', ['limit' => 200]);
$this->set(compact('employee', 'users'));
$this->set('_serialize', ['employee']);
}

Uploading multiple files and saving them to DB using related model in Yii2

I'm learning Yii2 by making a project.
I have two models: Company and CompanyFile. I'm using both of them in one form to create a Company, to upload related files and save them in associated table.
The problem is that the Company is being created but without uploading files and creating rows in associated table.
Here's the piece of Company Controller:
public function actionCreate()
{
$model = new Company();
$file = new CompanyFile();
if ($model->load(Yii::$app->request->post()) && $file->load(Yii::$app->request->post())) {
$model->save();
$attachments = UploadedFile::getInstances($file, 'attachment[]');
foreach($attachments as $a){
if ($a->upload()){
$file->company_id = $model->id;
$file->attachment = $a;
$file->save();
}
else {
return $this->render('create', [
'model' => $model,
'file' => $file,
]);
}
}
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
'file' => $file,
]);
}
}
Here's the piece of CompanyFile model:
public function upload()
{
if ($this->validate()){
$nameToSave = 'uploads/' . $this->attachment->baseName . '.' . $this->attachment->extension;
$this->attachment->saveAs($nameToSave);
return $nameToSave;
}
else {
return false;
}
}
Here's the views/company/_form.php:
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($model, 'name')->textarea(['rows' => 1, 'style' => 'width: 400px;']) ?>
<?= $form->field($file, 'attachment[]')->fileInput(['multiple' => true]) ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
After submitting form I'm redirected to newly created company page. No files uploaded. What may be wrong? I couldn't find any info about correct way of saving multiple files to another table in Yii2.
It needed to be
$attachments = UploadedFile::getInstances($file, 'attachment');
'attachment' without brackets.

CakePHP: validation of form upload field if file exists not working

CakePHP 2.x: I am struggling with validating an image upload field in a form for adding users. The upload field is not manditory. But it validates the field always as false while the image is uploaded. It seems the whole validation is working partially. Any help would be appreciated
User.php model :
public $validate = array(
'picture' => array(
'required' => false,
'allowEmpty' => true,
'custom' => array(
'rule' => array('imageExist'),
'message' => 'There is already a picture with that name on the server'
)
));
// function to check if file already exists
public function imageExist($check) {
$picturename = $check['picture'];
$path = WWW_ROOT . 'userimages/';
$file = $path . $picturename;
if (file_exists($file)) {
return false;
} else {
return true;
}
}
add.ctp:
<?php
echo $this->Form->create('User', array('class' => 'form-horizontal', 'role' => 'form', 'div' => false, 'type' => 'file'));
echo $this->Form->input('username', array('label' => "Username"));
echo $this->Form->input('picture', array('label' => "Avatar", 'type' => 'file'));
echo $this->Form>formDefaultActions();
echo $this->Form->end();
?>
UserController.php:
public function add() {
if ($this->request->is('post')) {
$this->User->create();
// set picture and path
$filedir = WWW_ROOT . 'userimages/';
$file = $filedir . $this->request->data['User']['picture']['name'];
// upload avatar picture
move_uploaded_file(
$this->request->data['User']['picture']['tmp_name'],
$file
);
$this->request->data['User']['picture'] = $this->request->data['User']['picture']['name'];
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been added'), 'success' );
$this->redirect(array(
'action' => 'index'
));
} else {
$this->Session->setFlash(__('The user could not be created. Please, try again'), 'error' );
}
}
}
You need to check your validation before uploading or will be always false. If you upload your file, when cakephp validates your file already exists in folder.
You can just move your logic to something like:
$this->request->data['User']['picture'] = $this->request->data['User']['picture']['name'];
if ($this->User->save($this->request->data)) {
move_uploaded_file(
$this->request->data['User']['picture']['tmp_name'],
$file
);
}
Or check, before saving:
if ($this->User->validates()) {
if ($this->User->save($this->request->data)) {
move_uploaded_file(
$this->request->data['User']['picture']['tmp_name'],
$file
);
}
}
comment this
$this->request->data['User']['picture'] = $this->request->data['User']['picture']['name'];
and also take off the 2 statements into model, required and allowEmpty.also replace in your controller:
if ($this->User->save($this->request->data))
with
if ($this->User->save($this->request->data['User']))
and the pic name should be saved into the db

CakePHP image upload by josegonzalez pulgin

I am trying to image upload in cakephp by using https://github.com/josegonzalez/cakephp-upload this plugin.I have almost done upload, now the problem is image directory not sending correctly. Here is the image
In controller I have add this code
public function add() {
if ($this->request->is('post')) {
$this->User->create();
$data = $this->request->data['User'];
if(!$data['photo']['name'])
unset($data['photo']);
if ($this->User->save($data)) {
$this->Session->setFlash(__('The img has been saved.'));
} else {
$this->Session->setFlash(__("The img hasn't been saved."));
}
}
}
And in add.ctp code is
<?php echo $this->Form->create('User', array('type'=>'file')); ?>
<fieldset>
<legend><?php echo __('Add Img'); ?></legend>
<?php
echo $this->Form->input('User.username');
echo $this->Form->input('photo',array('type'=>'file'));
echo $this->Form->input('User.photo_dir', array('type' => 'hidden'));
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
Here is the user.php model code
class User extends AppModel {
public $actsAs = array(
'Upload.Upload' => array(
'photo' => array(
'fields' => array(
'dir' => 'photo_dir'
)
)
)
);
}
photo_dir field type is varchar(255)
photo is uploading webroot\img\upload folder
How can I send full url in database table?May any body help me please?
Your controller code could look like this:
public function add() {
if ($this->request->is('post')) {
$this->User->create();
$data = $this->request->data['User'];
if(!$data['photo']['name'])
unset($data['photo']);
$data['photo']['name']='/img/upload/'.$data['photo']['name']
if ($this->User->save($data)) {
$this->Session->setFlash(__('The img has been saved.'));
} else {
$this->Session->setFlash(__("The img hasn't been saved."));
}
}
}
However this isn't actually doing any uploading and it isn't following cake's conventions very strictly.
This is a proper upload (snip-it) without the use of a plugin. Note: this is actual code from a site that kept track of teams.
controller
public function add() {
if ($this->request->is('post')) {
$this->Player->create();
if(isset($this->request->data['Player']['upload'])) {
foreach($this->request->data['Player']['upload'] as $key => $upload) {
$file=$upload;
$path=APP.'webroot/img/Players/'.$file['name'];
while(file_exists($path)) {
$r=rand(1,10000);
$file['name']=$r.$file['name'];
$path=APP.'webroot/img/Players/'.$file['name'];
}
if ($file['error'] == 0) {
if (move_uploaded_file($file['tmp_name'], $path)) {
$this->request->data['Player'][$key]='Players/'.$file['name'];;
} else {
$this->Session->setFlash(__('Something went wrong. Please try again.'));
$this->redirect(array('action' => 'index'));
}
}
}
}
if ($this->Player->save($this->request->data)) {
$this->Session->setFlash(__('The player has been saved.'), 'default', array('class' => 'alert alert-success'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The player could not be saved. Please, try again.'), 'default', array('class' => 'alert alert-danger'));
}
}
$teams = $this->Player->Team->find('list');
$ranks = $this->Player->Rank->find('list');
$this->set(compact('teams', 'ranks'));
}
view
<?php echo $this->Form->create('Player', array('role' => 'form', 'type' => 'file')); ?>
<?php echo $this->Form->input('team_id', array('class' => 'form-control', 'placeholder' => 'Team Id'));?>
<?php echo $this->Form->input('rank_id', array('class' => 'form-control', 'placeholder' => 'Rank Id'));?>
<?php echo $this->Form->input('name', array('class' => 'form-control', 'placeholder' => 'Name'));?>
<?php echo $this->Form->input('upload', array('class' => 'form-control', 'placeholder' => 'Name'));?>

CMultiFileUpload class not inserting image names on the database yii

I'm working on multi file(images) uploading functionality.
I've tried everything I got.
It's not working.
It's uploading images on the path I specified but not inserting image's names on the table column.
The table's column name is "sample"
Here's the snippet of the view:
$this->widget('CMultiFileUpload', array(
'model' => $model,
'name' => 'sample',
'attribute' => 'sample',
'accept' => 'jpeg|jpg|gif|png',
'duplicate' => 'Duplicate file!',
'denied' => 'Invalid file type',
'remove' => '[x]',
'max' => 20,
));
This is the controller's code the(the function that dealing with the part):
public function actionCreate($project_id) {
$model = new Bid();
$project = $this->loadModel('Project', $project_id);
if (count($project->bids) == 5) {
Yii::app()->user->setFlash('warning', Yii::t('bids', 'This project has already reached its maximum number of bids, so you cannot post a new bid.'));
$this->redirect(array('project/view', 'id' => $project_id));
}
if (!empty($project->bid)) {
Yii::app()->user->setFlash('warning', Yii::t('bids', 'This project has a selected bid already, so you cannot post a new bid.'));
$this->redirect(array('project/view', 'id' => $project_id));
}
if ($project->closed) {
Yii::app()->user->setFlash('warning', Yii::t('bids', 'You cannot add bids as this project has been closed.'));
$this->redirect(array('project/view', 'id' => $project_id));
}
$model->project = $project;
if (isset($_POST['Bid'])) {
$model->attributes = $_POST['Bid'];
$photos = CUploadedFile::getInstancesByName('sample');
if (isset($photos) && count($photos) > 0) {
foreach ($photos as $image => $pic) {
$pic->name;
if ($pic->saveAs(Yii::getPathOfAlias('webroot').'/images/'.$pic->name)) {
// add it to the main model now
$img_add = new Bid();
$img_add->filename = $pic->name;
$img_add->save();
}
else {
}
}
}
$model->project_id = $project->id;
$model->freelancer_id = $this->currentUser->id;
if ($model->save()) {
$this->redirect(array('project/view', 'id' => $project->id, '#' => 'bidslist'));
}
}
$this->render('create', array(
'model' => $model,
));
}
Thanks in Advance.
Please let me know if anyone needs anything else for better understanding.
If i underssot you correctly when you saving the model
$img_add = new Bid();
$img_add->sample = $pic->name;
$img_add->save();

Categories