php code to upload multiple images cakephp - cakephp

i am new in cakephp and try to learn.
my table structure is
table name - drivers
fields - id,name,
table - drivers_uploads
fields - id,driver_id,documentname,documentpath
i try to upload multiple files in my table.
My code is working well in folder it uploads multiple images but in table i want to insert all rows
i want to insert multiple file for same id and the id goes in drivers tables and the remaining files insert multiple rows for same id in drivers_upload table.
thanks in advance.
for ex
I need data to be inserted in below tables format.
**drivers tables **
id , name
16 lucky
driver_uploads tables
id,driver_id, document_name
1 16 mo.docx
2 16 ro.docx
controller code
public function add() {
$this->Driver->create();
if ($this->request->is('post')) {
for($i=1;$i<4;$i++)
{
if(empty($this->data['Driver']['document'.$i]['name'])){
unset($this->request->data['Driver']['document'.$i]);
}
if(!empty($this->data['Driver']['document'.$i]['name']))
{
$file=$this->data['Driver']['document'.$i];
$ary_ext=array('jpg','jpeg','gif','png','xlsx','docx'); //array of allowed extensions
$ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
if(in_array($ext, $ary_ext))
{
move_uploaded_file($file['tmp_name'], APP . 'outsidefiles' .DS. time().$file['name']);
//move_uploaded_file($file['tmp_name'], WWW_ROOT . 'img/uploads/posts/' . mktime().$file['name']);
$this->request->data['Driver']['document'.$i] = time().$file['name'];
}
}
}
if ($this->Driver->save($this->request->data))
{
$this->Session->setFlash('Your post has been saved.');
$this->redirect(array('action' => 'index'));
}
else
{
$this->Session->setFlash('Unable to add your post.');
}
}
}
view code
<h1>Add Post</h1><?php
echo $this->Form->create('Post', array('url' => array('action' => 'add'), 'enctype' => 'multipart/form-data'));
echo $this->Form->input('title');
echo $this->Form->input('body', array('rows' => '3'));
for($i=1; $i<4; $i++)
{
?>
<div id="attachment<?php echo $i;?>" <?php if($i !=1) echo "style='display:none;'";?> >
<div>
<?php echo $this->Form->input('image'.$i,array('type'=>'file','label' => false,'div' => false));?>
</div>
<div id="attachmentlink<?php echo $i;?>" <?php if($i==3) echo "style='display:none;'";?>>Add Another Attachment</div>
</div>
<?php } ?>
<?php
echo $this->Form->end('Save Post');
?>
<script>
function show(target){
document.getElementById(target).style.display = 'block';
}
function hide(target){
document.getElementById(target).style.display = 'none';
}
</script>
Below is my print_r data
echo "<pre>";print_r($this->request->data); exit();
if ($this->Driver->save($this->request->data))
Array
(
[Driver] => Array
(
[name] => raj
[mobile] => 9960181380
[email] => raj#gmail.com
[licenceno] => 512203615803
[address] => 452,nagpur
[document1] => Array
(
[name] => findmelogistics_Phase_III_Project Plan v1.2_8.xls
[type] => application/vnd.ms-excel
[tmp_name] => /tmp/phpXGkLvj
[error] => 0
[size] => 29184
)
[document2] => 1461815092FML Phase 3 Specification 2.docx
[document3] => 1461815092Phase 3 - SmartData questions 310316.docx
)
)

Related

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

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!

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.

Selecting a default value for a dropdown (key-value array) in cakePHP

Here is the dropdown in a form:
echo $this->Form->input('customer_id', array('id'=>'initials','label'=>'Customer', 'value'=>$customers));
The $customers is a key-value array like this:
array(
(int) 2 => 'Best customer',
(int) 5 => 'Good customer',
(int) 9 => 'Customer')
I need one value to be pre selected once the dropdown is created. I have tried to select a default value as the int id and as the customer name but none of them worked.
Here is the controller edit function:
function edit($id = null) {
$this->Project->id=$id;
$this->Project->recursive = 0;
$customers = $this->Customer->find('list', array('conditions'=>array('company_id'=>$this->Auth->user('company_id'))));
$this -> set('customers', $customers);
if(!$this->Project->exists()){
throw new NotFoundException('Invalid project');
}
if($this->request->is('post')|| $this->request->is('put')){
if($this->Project->save($this->request->data)){
$this->Session->setFlash('The project has been edited');
$this->redirect(array('controller'=>'projects', 'action'=>'view', $id));
} else{
$this->Session->setFlash('The project could not be edited. Please, try again');
}
}else{
$this->request->data = $this->Project->read();
$this->request->data['Project']['customer_id'] = 'New customer';
}
}
And here is the edit form:
<?php echo $this->Form->create('Project');?>
<fieldset>
<legend><?php __('Edit Project'); ?></legend>
<?php
echo $this->Form->input('customer_id', array('id'=>'initials','label'=>'Customer', 'value'=>$customers));
echo $this->Form->input('name');
echo $this->Form->input('project_nr', array('type'=>'text', 'label'=>'Case number'));
echo $this->Form->input('address');
echo $this->Form->input('post_nr');
echo $this->Form->input('city');
echo $this->Form->input('start_date', array('label'=>'Start Date', 'class'=>'datepicker', 'type'=>'text'));
echo $this->Form->input('finish_date', array('label'=>'End Date', 'class'=>'datepicker', 'type'=>'text'));
echo $this->Form->input('company_id', array('value' => $current_user['company_id'], 'type'=>'text', 'type'=>'hidden'));
?>
</fieldset>
<?php echo $this->Form->end(__('Submit', true));?>
The best approach is to leverage the controller for this
if ($this->request->is('post')) {
$this->Model->create();
if ($this->Model->save($this->request->data)) {
...
} else {
...
}
} else {
/* Now here you can put your default values */
$this->request->data['Model']['field'] = ...;
}
For details see http://www.dereuromark.de/2010/06/23/working-with-forms/

CakePHP find('neighbors') use [next] and [prev] from array

I am trying to get the neighbors Ids of the current Id.
What I have below works, but I cannot separate the [prev] from the [next] link.
The function in the controller looks as follows:
function prevNext() {
return $this->System->find('neighbors', array('fields' => 'name', 'value' => 3));
}
Which will output something like this:
Array
(
[prev] => Array
(
[System] => Array
(
[name] => Aegerter
[id] => 4004
)
)
[next] => Array
(
[System] => Array
(
[name] => Canonica
[id] => 4006
)
)
)
This gets passed as a requestAction -
<?php $systems = $this->requestAction('systems/prevNext'); ?>
<?php foreach($systems as $system): ?>
<?php echo $html->link($system['System']['id'],array('action'=>'view', $system['System']['id']));?>, <?php echo $system['System']['name'];?>
<?php endforeach; ?>
into the view as an element:
<?php echo $this->element('systems'); ?>
How do you call the [prev] and [next] link separately (not a foreach output)?
Tia
If i understand correctly:
<?php echo $html->link($systems['prev']['System']['id'],array('action'=>'view', $systems['prev']['System']['id']));?>, <?php echo $systems['next']['System']['name'];?>
<?php echo $html->link($systems['next']['System']['id'],array('action'=>'view', $systems['next']['System']['id']));?>, <?php echo $systems['next']['System']['name'];?>

WordPress: How to merge custom post type array?

i try to setup a yearly (grouped by month) archive for custom post types in WordPress. But my code did not work as aspected. Maybe it is obiviously for someone who is more familar with WordPress and PHP but i can't get it work.
The code below is grouping by month but each post type by itself. Maybe i need to merge booth. But how?
<?php query_posts (array ('post_type' => array('images', 'articles')));?>
<?php
if (have_posts()) : while (have_posts()) : the_post();
// save month to a variable
$month = the_date('M', '', '', FALSE);
// If not used before print it
if ($month != $m_check) {
echo "<h2>" . $month . "</h2>";
}
// save month to check variable
$m_check = $month;
?>
<?php the_title(); ?><br/>
<?php endwhile; ?>
<?php endif; ?>
<?php wp_reset_query();?>
Regards, Steve
You will need this: http://wordpress.org/extend/plugins/posts-to-posts/ to achieve what you want with custom posts.
Ok... after a cup of tea i got it with an other (probably better) approach.
Solution
<?php
$args = array(
'post_type' => array('images', 'articles'),
'numberposts' => -1,
'post_status' => null,
'post_parent' => null,
);
$posts = get_posts($args);
if ($posts) {
foreach ($posts as $post) {
setup_postdata($post);
$month = mysql2date('m', $post->post_date);
if ($month != $check) {
echo "<h2>" . $month . "</h2>";
}
// save month to check variable
$check = $month;
echo $post->post_title;
echo '<br/>';
}
}
?>
Output
07
Eagle creek
Lorem Ispum dolor
Vancouver Island
Ottawa
Vancouver
06
Losabim oxygenium
Now it needs just a bit beautifying and i am done. By the way #negatif, thank you for your suggestion.
Easy and correct way to merge our custom loop argument in default wordpress loop.
$argss = array(
'paged' => $paged,
'posts_per_page' => 9,
'meta_query' => array(
'relation' => 'OR',
array (
'key' => '_expiration-date',
'value' => $tode, // custom values
'compare' => '>='
),
array (
'key' => '_expiration-date',
'compare' => 'NOT EXISTS'
),
),
);
global $wp_query;
// Merge custom query with $wp_query
$merged_args = array_merge( $wp_query->query, $argss );
// Query posts using the modified arguments
query_posts( $merged_args );
if ( have_posts() ) : while (have_posts()) : the_post();
.
.
.
.
.
..
else : ?>
<p><?php _e('Apologies, but no entries were found.', 'tb'); ?></p>
<?php endif;
//wp_reset_query();
?>

Resources