I have a problem with kartik file-input and the delete button... i have it working when i use one file. But for the multi files - i can't make the trash button working.. Here is my form and my controller action (delete-files).
As my function deleteFiles is the same for another form/controller and works, i think i have a problem with the form here, more than the action...
Any help would be very much appreciated 🙂
Here is my form code
<?php
$allfiles = [];
$initialPreviewConfigAward = [];
if (!$model->isNewRecord)
{
$filesData = ArrayHelper::map(MakerFiles::find()->where(['maker_id' => $model->id,'type'=>$model->gs_type])->all(),'id','file_url');
foreach($filesData as $iKey=>$iVal)
{
$allfiles[] = '/backend/web/'.$iVal;
$initialPreviewConfigAward = [
'caption' => '/backend/web/'.$iVal,
'url' => Url::to(['greensocial/delete-files','id' => $iKey])];
];
}
}
?>
<?= $form->field($upload, 'file_url[]')->widget(FileInput::classname(),
['options' => ['id'=>'award-file','multiple' => true],
'pluginOptions'=>[
'previewFileType' => 'any',
'overwriteInitial'=>false,
'initialPreview'=>$allfiles,
'initialPreviewAsData'=> true,
'initialPreviewConfig' => $initialPreviewConfigAward,
//'showPreview' => true,
// 'deleteUrl'=> Url::to(['maker/delete-files', 'id' => $initialPreviewConfigAward->id]),
'showCaption' => false,
'showRemove' => false,
'showUpload' => false,
],
])->label(false); ?>
Here is my function (in my controller)
public function actionDeleteFiles($id){
$file = MakerFiles::find()->where(['id'=>$id])->one();
$filetodelete = Url::to('#backend/web/').$file->file_url;
if( file_exists ( $filetodelete )) {
unlink( $filetodelete );
if($file->save(false)){
echo json_encode('Fichier supprimé');
};
//return 'fichier supprimé';
}
else { echo json_encode('Unable to delete'); }
}
So, Thank you very much #MichalHynčica, it was the missing [] i forgot... i can now move on the next problem haha
i post the code modified here:
<?php
$allfiles = [];
$initialPreviewConfigAward = [];
if (!$model->isNewRecord)
{
$filesData = ArrayHelper::map(MakerFiles::find()->where(['maker_id' => $model->id,'type'=>$model->gs_type])->all(),'id','file_url');
foreach($filesData as $iKey=>$iVal)
{
$allfiles[] = '/backend/web/'.$iVal;
$initialPreviewConfigAward = [
'caption' => '/backend/web/'.$iVal,
'url' => Url::to(['greensocial/delete-files','id' => $iKey])];
];
}
}
?>
<?= $form->field($upload, 'file_url[]')->widget(FileInput::classname(),
['options' => ['id'=>'award-file','multiple' => true],
'pluginOptions'=>[
'previewFileType' => 'any',
'overwriteInitial'=>false,
'initialPreview'=>$allfiles,
'initialPreviewAsData'=> true,
'initialPreviewConfig' => $initialPreviewConfigAward,
//'showPreview' => true,
// 'deleteUrl'=> Url::to(['maker/delete-files', 'id' => $initialPreviewConfigAward->id]),
'showCaption' => false,
'showRemove' => false,
'showUpload' => false,
],
])->label(false); ?>
Related
I try to validate file, befor upload, but I doing something wrong.
This is my file in form type:
->add('file', 'file', array(
'constraints' => [
new File([
'maxSize' => '5M',
'mimeTypes' => [
'image/*'
],
'mimeTypesMessage' => 'Only images allowed!'
])
],
'multiple' => 'multiple',
'data_class' => null,
'required' => false,
'mapped' => false,
'attr' => array(
'maxSize' => '1024k',
'accept' => 'image/*',
)
))
If I select .txt, .php, ... to upload, so it's normally uploaded, without errors.
How to make it work?
Thanks
EDIT:
My Upload Function:
private function uploadImg($files)
{
$path = array();
foreach ($files as $file) {
$extension = $file->guessExtension();
if (!$extension) {
$extension = 'bin';
}
$randomName = 'image' . date('Y-m-d-H-i-s') . uniqid() . '.' . $extension;
$file->move('uploads/images/', $randomName);
$path[] = $randomName;
}
return $path;
}
and in controller:
$ads->setPath(implode(',', $this->uploadImg($form['file']->getData())));
Im am trying to create a controller that uploads a file for me but I always get the same result. The file isn't valid so he doesn't upload.
The function in my controller is:
$upload = new \Zend\File\Transfer\Transfer();
$upload->setDestination('./data/images/uploads/');
$rtn = array('success' => null);
if ($this->getRequest()->isPost()) {
$files = $upload->getFileInfo();
foreach ($files as $file => $info) {
if (!$upload->isUploaded($file)) {
print "<h3>Not Uploaded</h3>";
\Zend\Debug\Debug::dump($file);
continue;
}
if (!$upload->isValid($file)) {
print "<h4>Not Valid</h4>";
\Zend\Debug\Debug::dump($file);
continue;
}
}
$rtn['success'] = $upload->receive();
}
return new \Zend\View\Model\JsonModel($rtn);
The result is:
<h4>Not Valid</h4><pre>string(8) "files_0_"
</pre>{"success":false}
When I look at $files (print_r()) I get:
Array
(
[files_0_] => Array
(
[name] => logo_welcome.gif
[type] => image/gif
[tmp_name] => /private/var/tmp/phpiufvIc
[error] => 0
[size] => 62935
[options] => Array
(
[ignoreNoFile] =>
[useByteString] => 1
[magicFile] =>
[detectInfos] => 1
)
[validated] =>
[received] =>
[filtered] =>
[validators] => Array
(
[0] => Zend\Validator\File\Upload
)
[destination] => ./data/images/uploads
)
)
As you can see in ZF2 docs, file uploading with Zend\File\Transfer has been deprecated in favor of using the standard ZF2 Zend\Form and Zend\InputFilter features.
Having said that, you should use Zend\Filter\File\RenameUpload to move the uploaded file. You just need to attach the Zend\Filter\File\RenameUpload filter to your InputFilter specification, like that:
$this->add([
'name' => 'file',
'type' => 'Zend\InputFilter\FileInput',
'filters' => [
[
'name' => 'FileRenameUpload',
'options' => [
'target' => realpath('./data/uploads/'),
'randomize' => true,
'use_upload_extension' => true,
],
],
],
]);
And in your controller action:
if ($this->request->isPost()) {
$post = array_merge_recursive(
$this->request->getPost()->toArray(),
$this->request->getFiles()->toArray()
);
$form->setData($post);
if ($form->isValid()) {
// File uploaded and moved to data/uploads folder
}
}
Take a look in official documentation for a complete example.
i wish select an element of dropdownlist (choose a Project) and with JSHELPER (ajax) update the GRAPH that show statistics of this Project.
I can choose the Project and through the 'POST' I can generate the array graph, but i cannot show the GRAPH. I tested without JSHELPER and show my Graph.
MY VIEW CODE:
<b>ESCOLHA O PROJETO: </b>
<?php
echo $this->Form->select('projects', array($projects), array('multiple' => false,
'class' => 'span2',
'id' => 'projectsTest'));
?>
</br>
<div id="chart_div" >
</div>
<?php
$this->Js->get('#projectsTest')->event('change', $this->Js->request(array(
'controller' => 'Registos',
'action' => 'timePerProjectIssueTypeChart'
), array(
'update' => '#chart_div',
'async' => true,
'method' => 'post',
'dataExpression' => true,
'data' => $this->Js->serializeForm(array(
'isForm' => true,
'inline' => true
))
)));
?>
MY VIEW TIME_PER_PROJECT_ISSUE_TYPE_CHART
<div id="chart_div" >
<?php
echo $this->GoogleChart->createJsChart($timePerProjectIssueTypeChart);
?>
</div>
CONTROLLER
function timePerProjectIssueTypeChart() {
if (!empty($this->request->data['projects'])) {
$id_project = $this->request->data['projects'];
$totalProject = $this->timeSpentPerProjectSpecific(10001, 'Registo.issuetype');
$timeSpent = $this->totalTimeSpentPerProject(10001);
//Setup data for chart
$timePerProjectIssueTypeChart = new GoogleChart();
$timePerProjectIssueTypeChart->type("PieChart");
$timePerProjectIssueTypeChart->options(array('title' => "Percentagem de Tempo (horas) investido em cada Tarefa",
'height' => 300, 'width' => 500));
$timePerProjectIssueTypeChart->columns(array(
//Each column key should correspond to a field in your data array
'issuetype' => array(
'type' => 'string',
'label' => 'Tipo Tarefa'
),
'tempoGasto' => array(
'type' => 'time',
'label' => '% horas'
)
));
//You can also use this way to loop through data and creates data rows:
foreach ($totalProject as $row) {
if ($timeSpent[0][0]['tempogasto'] != 0) {
$percentagemTempoGasto = ($this->timeToHour($row[0]['tempogasto']) / $timeSpent[0][0]['tempogasto']) * 100;
} else {
$percentagemTempoGasto = 0;
}
if (!empty($row['IssueType'])) {
$timePerProjectIssueTypeChart->addRow(array('tempoGasto' => $percentagemTempoGasto, 'issuetype' => $row['IssueType']['pname']));
} else {
$timePerProjectIssueTypeChart->addRow(array('tempoGasto' => $percentagemTempoGasto, 'issuetype' => 'Sem tarefa'));
}
}
//Set the chart for your view
$this->set('totalProject', $totalProject);
$this->set('timeSpent', $timeSpent);
$this->set(compact('timePerProjectIssueTypeChart'));
}
}
I do not put the code of the controllers, because individually tested and are working.
Thanks
Teste com ajax, sem o JS helper:
$(document).ready(function() {
$("#projectsTest").change(function(){
$.ajax({
type: 'POST',
data: { projects: $('#projectsTest').val()},
url: 'timePerProjectIssueTypeChart',
success: funcion() {
$("chart_div").load('timePerProjectIssueTypeChart');
}
})
})
});
E não esqueça de colocar $this->layout = false no controller
I am using JS Helper submit in my cakephp 2.x version.
My code is fine as function is called.
<?php echo $this->Js->submit("Apply", array(
'div' => false,
'class' => 'general_button',
'style' => array('float:none;', 'margin: 10px;'),
'url' => array('controller' => 'poets', 'action' => 'index', 'field' => $search_term, 'value' => $search_value),
'update' => '#listID',
'confirm' => 'Are you sure you want to apply action to selected records ??',
'before' => "return isAnySelect(this.form);",
'success' => 'myShowMessage();')); ?>
Though function isAnySelect(this.form) is called but my function this.form returns undefined wats the issue with this code .. Please explain.
My function
function isAnySelect(frmObject) {
console.log(frmObject);
return false;
varAllId = "";
for (i = 1; i < frmObject.chkRecordId.length; i++) {
alert('Hiii');
alert(varAllId + "xs");
if (frmObject.chkRecordId[i].checked == true) {
if (varAllId == "") {
varAllId = frmObject.chkRecordId[i].value;
} else {
varAllId += "," + frmObject.chkRecordId[i].value;
}
}
}
if (varAllId == "") {
alert("Please select atleast one record !!");
return false;
} else {
document.getElementById('idList').value = varAllId;
return true;
}
}
Though function is called but it output undefined on console.
help me to fix isPut or isPost for save logic, in the following code i can view the data in the from, but when i am trying to save it its not working, i have tried ispost and isput logic both are not working. i think problem is with controller sections not with view
here is view of my form,
<?php
echo $this->Form->create('Role',array('url'=>array('controller'=>'Organisations','action' => 'edit_profile'),'id' => 'role'));
echo $this->Form->input('RoleLanguage.rolename',array('label'=>'Profile Name:','id'=>'rolename'));
$options = array('A' => 'Approve', 'P' => 'Pending', 'D' => 'Delete');
echo $this->Form->input('Role.status', array(
'options'=>$options,
'empty' => false,
'label'=>'Status',
'style'=>'width:100px',
'id'=>'status'
));
$id= array('value' => $id);
//print_r($id);die();
echo $this->Form->hidden('rle_id', $id);
echo "<br>";
$options = array('R' => 'Role', 'P' => 'Position', 'T' => 'Team','C'=>'Core Strategic Profile');
echo $this->Form->input('Role.type', array(
'options'=>$options,
'empty' => false,
'label'=>'Type of Job Profile:',
'style'=>'width:100px',
'id'=>'type'
));
echo "<br>";
echo $this->Form->input('RoleLanguage.external_document_URL',array('label'=>'External Document URL:','id'=>'external_document_URL','type'=>'text'));
echo "<br>";
echo $this->Form->input('RoleLanguage.description', array('style'=>'width:420px','rows' => '5', 'cols' => '5','label'=>'Description','id'=>'description'));
?>
here is controller logic
function edit_profile($id=NULL)
{
$this->layout='Ajax';
//print_r($id);die();
$this->set('id',$id);
$this->Role->recursive = 0;
$this->Role->id = $id;
$language = $this->getLanguage('content');
$this->Role->unBindModel(array("hasMany" => array('RoleLanguage')));
$this->Role->bindModel(array("hasOne" => array('RoleLanguage'=> array('foreignKey' => 'rle_id', 'className' => 'RoleLanguage', 'type' => 'INNER', 'conditions' => array('RoleLanguage.language' => $language)))));
$this->data = $this->Role->read();
//print_r($this->data);die();
if ($this->RequestHandler->isPut())
{
$this->data=array(null);
$this->autoRender = false;
$acc_id = $this->activeUser['User']['acc_id'];
$this->data['Role']['acc_id'] = $acc_id;
unset($this->Role->RoleLanguage->validate['rle_id']);
print_r($this->data);die();
$this->Role->saveAll($this->data);
}
}
i am serializing data in another view from where i am calling the qbove view code for that is
$.ajax({
type: 'Put',
url: $('#role').attr('action'),
data: $('#role').serialize()
It could be that the data is failing the model validation test that occurs when you call saveAll.
Have you tried printing $this->Role->invalidFields() to see if there is anything there?