CAKEPHP 4: I cannot upload many files at the same time - cakephp

Goodnight (or good morning),
I trying to upload multiple files at the same time. I am following the cookbook instructions to build the solution. I always got first file (not and array of files).
Here is my view code...
<?php
/**
* #var \App\View\AppView $this
* #var \App\Model\Entity\Upload $upload
*/
?>
<div class="row">
<aside class="column">
<div class="side-nav">
<h4 class="heading"><?= __('Actions') ?></h4>
<?= $this->Html->link(__('List Uploads'), ['action' => 'index'], ['class' => 'side-nav-item']) ?>
</div>
</aside>
<div class="column-responsive column-80">
<div class="uploads form content">
<?= $this->Form->create($upload, ['type' => 'file']) ?>
<fieldset>
<legend><?= __('Add Upload') ?></legend>
<?php
echo $this->Form->control('name');
echo $this->Form->control('document_type_id', ['options' => $documentTypes]);
echo $this->Form->control('period_id', ['options' => $periods]);
echo $this->Form->control('user_id', ['options' => $users]);
echo $this->Form->control('documents', ['type' => 'file', 'label' => __('Choose PDF Files'), 'accept' => 'application/pdf', 'multiple' => 'multiple']);
?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
</div>
</div>
</div>
And here is my controller code...
public function add()
{
$upload = $this->Uploads->newEmptyEntity();
if ($this->request->is('post')) {
$upload = $this->Uploads->patchEntity($upload, $this->request->getData());
if ($this->Uploads->save($upload)) {
if (!is_dir($this->Parameters->findByName('document_directory')->first()->toArray()['value'] )) {
mkdir($this->Parameters->findByName('document_directory')->first()->toArray()['value'], 0776, true);
}
$documents = $this->request->getData('documents');
$this->loadModel('Dockets');
$dockets = $this->Dockets->findByDocketStateId(1);
$documents_ok = 0;
$documents_nok = 0;
$dockets_without_document = 0;
foreach($documents as $documents_key => $document_to_save)
{
foreach($dockets as $dockets_key => $docket)
{
$contents = file_get_contents($document_to_save);
$pattern = str_replace('-', '', $pattern);
$pattern = str_replace('', '', $pattern);
$pattern = preg_quote($docket->cuit, '/');
$pattern = "/^.*$pattern.*\$/m";
// search, and store all matching occurences in $matches
if(preg_match_all($pattern, $contents, $matches)){
$documentsTable = $this->getTableLocator()->get('Documents');
$document = $documentsTable->newEmptyEntity();
$document->upload_id = $upload->id;
$document->document_type_id = $upload->document_type_id;
$document->period_id = $upload->period_id;
$document->docket_id = $docket->id;
$document->user_id = $this->getRequest()->getAttribute('identity')['id'];
if ($documentsTable->save($document)) {
if (!is_dir($this->Parameters->findByName('document_directory')->first()->toArray()['value'] )) {
mkdir($this->Parameters->findByName('document_directory')->first()->toArray()['value'], 0776, true);
}
$fileobject = $this->request->getData('document');
$destination = $this->Parameters->findByName('document_directory')->first()->toArray()['value'] . 'document_' . $document->id . '.pdf';
// Existing files with the same name will be replaced.
$fileobject->moveTo($destination);
}
$this->Flash->error(__('The document could not be saved. Please, try again.'));
$documents_ok = $documents_ok + 1;
unset($dockets[$dockets_key]);
unset($documents[$documents_key]);
break;
}
}
}
if(!empty($documents)){
//print_r($documents);
$documents_nok = count($documents);
unset($documents);
}
if(!empty($dockets)){
$dockets_without_document = count($dockets);
unset($dockets);
}
$message = __('There were processed ') . $documents_ok . __(' documents succesfully. ') . $documents_nok . __(' documents did not math with a docket. And ') . $dockets_without_document . __(' active dockets ddid not not have a document.');
$this->Flash->success(__('The upload has been saved. ') . $message);
return $this->redirect(['action' => 'view', $upload->id]);
}
$this->Flash->error(__('The upload could not be saved. Please, try again.'));
}
$documentTypes = $this->Uploads->DocumentTypes->find('list', ['keyField' => 'id',
'valueField' => 'document_type',
'limit' => 200]);
$periods = $this->Uploads->Periods->find('list', ['keyField' => 'id',
'valueField' => 'period',
'limit' => 200]);
$users = $this->Uploads->Users->find('list', ['keyField' => 'id',
'valueField' => 'full_name',
'conditions' => ['id' => $this->getRequest()->getAttribute('identity')['id']],
'limit' => 200]);
$this->set(compact('upload', 'documentTypes', 'periods', 'users'));
}
Can you help me to understand what I doing wrong?
Thanks,
Gonzalo

When using PHP, multi-file form inputs must have a name with [] appended, otherwise PHP isn't able to parse out multiple entries, they will all have the same name, and PHP will simply use the last occurrence of that name.
echo $this->Form->control('documents', [
'type' => 'file',
'label' => __('Choose PDF Files'),
'accept' => 'application/pdf',
'multiple' => 'multiple',
'name' => 'documents[]',
]);
Furthermore the following line:
$fileobject = $this->request->getData('document');
should probably be more like this, as there a) is no document field and b) even if there were, you most likely wouldn't want to process the same file over and over again:
$fileobject = $documents[$documents_key];
Also make sure that you have proper validation in place for the uploaded files, even if you don't seem to use the user provided file information, you should still make sure that you've received valid data!

Related

How to merge two forms with two different models in one form in CakePHP 3.5?

I am a beginner of CakePHP and I'm using version 3.5. I really get confused by it. My problem is I want to merge two forms from 2 different models. In my case, I want to merge the client transaction add form and service detail add form all in one form. Here are my codes below:
add.ctp (I merge the add client transaction form in service detail add form)
<div class="serviceDetail form large-9 medium-8 columns content">
<?= $this->Form->create($clientTransaction) ?>
<fieldset>
<legend><?= __('Add Client Transaction') ?></legend>
<?php
echo $this->Form->control($serviceDetail->client_transaction->client->id, ['options' => $clients]);
echo $this->Form->control($serviceDetail->client_transaction->client->transaction_date, ['timeFormat' => 12, 'disabled' => false]);
echo $this->Form->control($serviceDetail->client_transaction->client->status, ['type' => 'hidden', 'value' => 0]);
?>
</fieldset>
<?= $this->Form->create($serviceDetail) ?>
<fieldset>
<legend><?= __('Add Service Detail') ?></legend>
<?php
echo $this->Form->control('service_id', ['options' => $service, 'empty' => true]);
echo $this->Form->control('user_id', ['options' => $users, 'empty' => true, 'label'=> ['text' => 'Barber']]);
echo $this->Form->control('client_transaction_id', ['options' => $clientTransaction, 'empty' => true]);
?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
in my service_detail controller
public function add()
{
$this->paginate = [
'contain' => ['Service', 'Users', 'ClientTransaction']
];
$clientTransaction = $this->ServiceDetail->ClientTransaction->newEntity();
$serviceDetail = $this->ServiceDetail->newEntity();
if ($this->request->is('post')) {
$clientTransaction = $this->ServiceDetail->ClientTransaction->patchEntity($clientTransaction, $this->request->getData());
$serviceDetail = $this->ServiceDetail->patchEntity($serviceDetail, $this->request->getData());
if ($this->ServiceDetail->ClientTransaction->save($clientTransaction) && $this->ServiceDetail->save($serviceDetail)) {
$this->Flash->success(__('The transaction has been added.'));
return $this->redirect(['action' => 'add']);
}
$this->Flash->error(__('Please, try again.'));
}
$service = $this->ServiceDetail->Service->find('list', ['limit' => 200]);
$users = $this->ServiceDetail->Users->find('list',['limit' => 200, 'valueField' => 'first_name'])->where(['position' => 2]);
$clientTransaction = $this->ServiceDetail->ClientTransaction->find('list', ['limit' => 200]);
$clients = $this->ServiceDetail->ClientTransaction->Clients->find('list', ['limit' => 200]);
$serviceDetail = $this->paginate($this->ServiceDetail);
$this->set(compact('serviceDetail', 'service', 'users', 'clientTransaction'));
}
Do something like this:
$serviceDetail = $this->ServiceDetail->newEntity(
$this->request->getData(), [
'associated' => ['ClientTransaction']
]
);
https://book.cakephp.org/3.0/en/orm/saving-data.html#converting-request-data-into-entities
For your page follow this pattern:
https://book.cakephp.org/3.0/en/views/helpers/form.html#creating-inputs-for-associated-data

simple blog with croogo

I is not What is the problem, I made a simple blog in Croogo, the problem is it is not adding or modifying or delete, because Arabic language ??
function add in controller
`public function admin_add() {
$this->set('title_for_layout', __('Add Part'));
if (!empty($this->request->data)) {
$this->Part->create();
if ($this->Part->save($this->request->data)) {
$this->Session->setFlash(__('The Part has been saved'), 'default', array('class' => 'success'));
$this->redirect(array('action' => 'index'));//, $this->Part->id));
} else {
$this->Session->setFlash(__('The Part could not be saved. Please, try again.'), 'default', array('class' => 'error'));
}
}
}`
=>
model
`class Part extends AppModel {
public $name = 'Part';
var $belongsTo = array(
'Market' => array(
'className' => 'Market',
'foreignKey' => 'market_id',
)
);
protected $_displayFields = array(
'id',
'num_part',
'prix_part',
'prop_Pledge',
'prix_Pledge',
);
}
`
add view
<?php $this->extend('/Common/admin_edit'); ?>
<?php echo $this->Form->create('Part');?>
<fieldset>
<div class="tabs">
<ul>
<li><span><?php echo __('Part'); ?></span></li>
<?php echo $this->Layout->adminTabs(); ?>
</ul>
<div id="role-main">
<?php
echo $this->Form->label('num_part', 'العدد : ');
echo $this->Form->input('num_part',array('label' => false ));
echo $this->Form->label('prix_part', 'االمبلغ : ');
echo $this->Form->input('prix_part',array('label' => false ));
echo $this->Form->label('prop_Pledge', 'إقتراح التعهد : ');
echo $this->Form->input('prop_Pledge',array('label' => false ));
echo $this->Form->label('prix_Pledge', 'مبلغ التعهد : ');
echo $this->Form->input('prix_Pledge',array('label' => false ));
?>
</div>
<?php echo $this->Layout->adminTabs(); ?>
</div>
</fieldset>
<div class="buttons">
<?php
echo $this->Form->end(__('Save'));
echo $this->Html->link(__('Cancel'), array(
'action' => 'index',
), array(
'class' => 'cancel',
));
?>
</div>
message error : The requested address was not found on this server.
I don't think it is because of Arabic language because when you do :
echo $this->Form->label('prop_Pledge', 'إقتراح التعهد : ');
The second parameter is a text. I don't know which Cake version you're using but I think that the first field should be Part.prop_Pledge (Cake v3).
I suggest you to try to use debug() and exit to see where is the real problem or try to put remove arabic characters to see if this is the reason of you're problem.
Just a question where is your $this->Form->create() in view ?
line added to the database successfully but does not retoure to index
it displays an error message
Could you print the message error hello21 please ?
Hope this will help you.

CakePHP-3.0 plugin form validation error message and entered data

I have created a CommentManager plugin for adding comments in my posts. Adding the comment form in Posts/view.ctp file and the comment form action is redirecting to CommentManager/Comments/add.
The comments are saving properly but when saving empty form, that doesn't shows the validation error messages which i have written in CommentsTable and also the entered data has gone from the form.
CommentManager/src/Controller/CommentsController/add
public function add()
{
$ccomment = $this->Comments->newEntity($this->request->data);
if ($this->request->is('post')) {
$newData = ['post_id' => $this->request->params['pass'][0]];
$ccomment = $this->Comments->patchEntity($ccomment, $newData);
if ($this->Comments->save($ccomment)) {
$this->Flash->success('The comment has been saved.');
return $this->redirect($_SERVER['HTTP_REFERER']);
} else {
$this->Flash->error('The comment could not be saved. Please, try again.');
}
}
$this->set(compact('ccomment'));
return $this->redirect($_SERVER['HTTP_REFERER']);
}
CommentManager/src/Model/Table/CommentsTable
public function validationDefault(Validator $validator) {
return $validator
->notEmpty('body', 'Body contents required.')
->notEmpty('email', 'An email is required.')
->add('email', [
'format' => [
'rule' => [
'custom',
'/^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/'
],
'message' => 'Enter a valid email.'
]
]);
}
src/Template/Posts/view.ctp
<?php echo $this->Html->link('Back', ['action' => 'index']) ?>
<?php echo $this->element('check_login'); ?>
<br/>
<?php $img_path = DS.'webroot'.DS.'images'.DS.$post->image; ?>
<img src="<?php echo empty($post->image)?'':$img_path; ?>">
<h2><?php echo $post->title; ?></h2>
<p><?php echo $post->body; ?></p>
<p><small><?php echo $post->created->format('d M Y'); ?></small></p>
<h3>Comments:</h3>
<?php foreach ($comments as $comment) { ?>
<p><?php echo $comment->body; ?></p>
<?php } ?>
<?php
echo $this->Form->create(null, ['url' => ['plugin' => 'CommentManager', 'controller' => 'Comments', 'action' => 'add', $post->id]]);
echo $this->Form->input('body', ['type' => 'textarea', 'rows' => '5', 'cols' => '5']);
echo $this->Form->input('email');
echo $this->Form->button('Save');
echo $this->Form->end();
?>
Don't call newEntity() with an empty array. Inste of
$ccomment = $this->Comments->newEntity($this->request->data);
Do:
$ccomment = $this->Comments->newEntity();
And in in the call to patchEntity() pass the $this->request->data

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 Paginator issue with second model

still a novice, but I am fighting with the paginator to limit my view to 10 records [properties] and to sort it on a field in the properties model. What am I doing wrong or miss in my code to get the paginator to control my view???
I have 2 models, Regions and Properties, a region has many properties, for example, my view is /region/view/13 This shows all properties for region 13.
The paginator is displaying the correct amount of properties, set the pages correct and all seems correct, but the paginator is not limiting my view, it just displays all properties by that region in one huge list instead of limit the view to 10 per page.
The sort per sleeps doesn't work either although the url in the browser seems to be ok.
/regions/view/13/sort:sleeps/direction:asc
/regions/view/13/sort:sleeps/direction:desc
Model:
<?php
App::uses('AppModel', 'Model');
/**
* Region Model
*
* #property Country $Country
* #property Property $Property
*/
class Region extends AppModel {
/**
* Display field
*
* #var string
*/
public $displayField = 'regionname';
/**
* belongsTo associations
*
* #var array
*/
public $belongsTo = array(
'Country' => array(
'className' => 'Country',
'foreignKey' => 'country_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
/**
* hasMany associations
*
* #var array
*/
public $hasMany = array(
'Property' => array(
'className' => 'Property',
'foreignKey' => 'region_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);
}
Controller:
public function view($id = null) {
if (!$this->Region->exists($id)) {
throw new NotFoundException(__('Invalid region'));
}
$this->Region->recursive = 2; // related to associated model data, Region -> Properties -> PropertyImages
$options = array('conditions' => array('Region.' . $this->Region->primaryKey => $id));
$total = $this->Region->Property->find('count', array(
'conditions' => array('Property.region_id' => $id)
));
$this->set('total', $total); // Push to counter the view.
$this->set('region', $this->Region->find('first', $options)); // Push the properties to the view.
$this->paginate = array(
'limit' => 10,
'conditions' => array('Property.region_id' => $id),
);
$this->Region->Property->virtualFields['sleeps'] = 'Property.sleeps';
$this->set('regions', $this->paginate('Property'));
}
View:
<div class="paging">
<?php
echo $this->Paginator->prev('< ' . __('previous'), array(), null, array('class' => 'prev disabled'));
echo $this->Paginator->numbers(array('separator' => ''));
echo $this->Paginator->next(__('next') . ' >', array(), null, array('class' => 'next disabled')); ?>
</div>
<br>
<?php
echo $this->Paginator->counter(array(
'format' => __('Page {:page} of {:pages}, showing {:current} records out of {:count} total, starting on record {:start}, ending on {:end}'))); ?><br>
Total properties: <?php echo $total . "\n"; ?><br>
Sort by: <?php echo $this->Paginator->sort('sleeps'); ?>
<?php if (!empty($region['Property'])): ?>
<div class="regionviewfooter"></div>
<?php
$i = 0;
foreach ($region['Property'] as $property): ?>
<!-- We only need 1 image to show up -->
<?php foreach ($property['PropertyImage'] as $key =>$propertyImage): ?>
<div class="regionview">
<div class="regionviewleft">
<?php echo '<span style="font-size:12px;line-height:18px;font-weight:bold;">'; echo $this->Html->link(__($property['description']), array('controller' => 'properties', 'action' => 'view', $property['id'])); echo '</span>'; ?>
<div class="regionviewheader">Sleeps <?php echo $property['sleeps']; echo ' :: ' ?>
<?php
if ($property['minPrice'] == 0) {
echo 'Please call for prices';
} else {
echo 'Prices from ';
echo $this->Number->currency($property['minPrice'], 'GBP');
if ($property['maxPrice'] == 0) {
echo ' PW';
} else {
echo ' - ';
echo $this->Number->currency($property['maxPrice'], 'GBP');
echo ' PW';
}
}
echo '<span style="font-size:11px;line-height:18px;font-weight:normal;">'; echo ' :: ';
echo $this->Html->link(__('View Property'), array('controller' => 'properties', 'action' => 'view', $property['id'])); echo '</span>'; ?>
</div>
<?php echo ($property['shortDesc']); ?><br>
Add to my Enquiry List :: Property Ref. (<?php echo strtoupper($property['ref']); ?>)
</div>
<div class="regionviewright">
<!-- display image -->
<?php echo $this->Html->image(($propertyImage['filename']), array('alt' => ($propertyImage['description']),'width' => '150' ,'height' => '77')); $key ?>
<?php $key++; ?>
</div>
</div>
<div class="clear"></div>
<div class="regionviewfooter"></div>
<?php if ($key == 1) {
break; // Stop, we did 1 image.
}
?>
<?php endforeach; ?>
<?php endforeach; ?>
<?php endif; ?>
<br>Top of Page<br><br>
You're setting your paginated results to $regions, yet in your view, you're looping through and displaying $region (singular), which is a straight-up find() above, with recursive 2, which will pull all properties.
So - although there are many other things that need cleaned up with your code, for now, just use $regions (plural) instead of $region singular in your View.

Resources