How to do form-based file uploads in CakePHP? - cakephp

I have been looking into this for a while and can't figure it out. Basically I have an add page for my model which you can add a map from a URL or from a file upload. I have got all the fields and validation in but how and where do I manage the uploaded file?? There must be some easy way to do this. Thanks!

Firstly your form needs to be set up to allow file uploads.
<?php echo $form->create(Model, array('type' => 'file')); ?>
This will allow any file inputs to actually upload the file to your server with $form->file(field) or $form->input(field, array('type' => 'file')).
Once the file has been uploaded you should handle everything else from within the Model:
function beforeSave($created) {
extract($this->data[Model][field]);
if ($size && !$error) {
move_uploaded_file($tmp_name, destination);
$this->data[Model][field] = destination;
}
return true;
}
These are only the basics, so be sure to have a play around to find the solution that best fits your needs.

You can use Zend Components to handle the file upload. There is a good example here on my website:
CakePHP file upload using Zend Components

NOTE: MeioUploadBehavior has been deprecated. Instead jrbasso suggests the Upload Plugin.
In addition to the fine answers already given I want to hint about MeioUploadBehavior, currently maintained by jrbasso at github, which has been a great help for me in my own CakePHP project.
You simply add the behavior to your model using the $actsAs field and at the same time specifying any custom preferences. Then create necessary fields (described by supplied docs in detail) in your database, or configure the model to not use any database table. Finally setup the form in your add page, also described in the supplied documentation. The behavior will then take care of the rest for you.

Related

What is the purpose of the '.' in a CakePHP file upload form element?

long time reader, with a small question on my hands.
I have been working on adding multiple file upload support to a CakePHP 2.x project, I've implemented as such in a view here;
<label>Supporting Document(s):</label>
<?php
echo $this->Form->file('files.', ['type' => 'file', 'multiple' => ($allowMultipleSetting ? 'multiple' : false)]);
?>
But I'm a little confused, what is the purpose of the '.' in 'files.' here? I can see what it can do, it gives me an array of file objects in my controller when I do a $this->data['files'], which is desired, and without it, I just have the one file object, even with multiple set to true from option parameters passed to this view.
Does anyone know what 'magic' or Cake 'thing' happens here so that, when a dot/full stop is added to the end of the key name, Cake shows all the images selected?
Thanks!
In Cake typically the first parameter of the FormHelper you are using is for the column name it is using in the database. So it could be Model.column_name for an example, or just coulmn_name as the parameter.
As long as you make sure the column name matches up there you are good. Cake will take care of the rest and output the <input type="file" /> with the correct name attributes.
The "." you are referencing is because that is setup for multiple file uploads, and if it is giving you problems you can remove it and specify the columns in the options. Such as: "'name' => 'data[Model][fieldname][]'
The output Cake needs to create is:
<input type="file" name="filename[Model][col][]" /> so that's why there is no column specified.
Check out this blog post from 2012 about multiple file uploads.
Here is a reference from their documentation specifically about the file input in the form helper as well.

How can I download a PDF file from a form using UI designer?? Bonita

The thing is I have found how upload a document and after that downolad it. But I just want to download it. I want to do it using the UI designer but I dont know how to do it.
Thanks :)
I dont know which tool are you using to design your UI, anyway this is concerning functionality, not design. In that point, i need to know wich language do you want (or can) use. For example, in PHP, it's very simple, you can make something like:
(create php file) downloadpdf.php
1st: (if you want to generate pdf "on the fly":
<?php
function download($foo){
content headers (type, force-download, etc)
database select to get data or harcode it.
echo data
}
?>
and call this function with some id to select from database or something (ignore if you want to hardcode it)
Other option to download a file, if it's stored on server is making a link to this file (statically or dyamically). If you wanna take control to file downloads, check this post:
http://www.media-division.com/the-right-way-to-handle-file-downloads-in-php/
I don't mean that it can be done with UI designer tools, and it's not concerned if it's from a form or not.
Cheers!
You should create link and variable which type is javascript expression. On Variable value write
return "/bonita/portal/" + $data.context.mainDoc_ref.url;
On link URL write your variable and to text
Download: {{context.mainDoc_ref.fileName}}
Here you can find excellent example for this case

Cakephp Upload Plugin - Saving Custom Path in DIR Field

I am using the https://github.com/josegonzalez/cakephp-upload
'pathMethod' => 'primaryKey'.
And the below path
'path' => '{ROOT}webroot{DS}files{DS}upload{DS}{model}{DS}{field}{DS}',
So, I am stuck at a point where in I want to save the DIR with a more elaborate information than just the primaryKey ID in DIR field
eg DIR field to be saved as "upload/organization/logo/1", currently its just saves "1"
I have gone though the documentation several times, but unable to understand about how to solve the above situation. Please help through with this.
Why want this feature, when everything is happening auto-magically, using only dir field in the view helps a lot, to link the file.
Thanks.
With the current code base, I believe the only solution you have at your disposal is to use the pathMethod of 'flat', use the 'handleUploadedFileCallback' property and manage the handling of directory creation and file movement (from TMP to 'path') on your own...and then also save the 'dir' property of your model (if you're saving that) within that callback (or afterSave) as well. Using 'pathMethod' => 'flat' removes the automatic saving of the file's location.
According to GitHub tickets, it seems that Jose might have plans to implement this feature in the future, but it's a "WIP" (Work in Progress).

CakePHP - Security - Image and Link Helpers

I just read this quite interesting post about security for CakePHP: Cakephp Security
It says that whenever a helper is used, CakePHP basically takes care security risks unless I turn of escape. I believe I only turn off escape when I want my links to be images, so nesting an image helper line inside a link helper line. For example:
echo $this->Html->link($this->Html->image('logo.png'), "/" , array('id'=>'logo', 'escape' => false));
Is that bad practise? Does that leave me vulnerable? Should I be doing it some other way?
Additionally, is it correct that whenever I output database data on dynamic pages, it needs to be enclosed in htmlspecialchars($myvariable)? I don't understand why I need to do that if I know that my database is clean from "bad stuff" and all of my forms for input into my database uses FormHelper.
In the example code shown you have all static values, no content coming from user so there's no risk.
Similarly for your content coming from database if for eg. all content is managed by site admin and no content from users is saved to database its reasonably safe to echo the content without escaping.

Embed a Cakephp form into Wordpress

I have a Wordpress blog and I'm developing a backend application using Cakephp.
I want to develop the blog's contact form using cake (since the entered information will be available from the backend app).
Right now, I tried including the cake view into wp using ajax. The problem with this approach is that I either use a Js->submit, which makes attaching files to the form quite complicated, or I use a Form->submit, which makes displaying validation errors problematic. Also, it creates problems with the recaptcha plugin not showing up.
Is there a way of integrating the form using php? I don't need authentication (it is a public form), but I need to be able to show validation errors on the form and upload files on the form.
Actually, you can load any website into a string using CURL, if you load en empty page with a placeholder from your wordpress, you can then use it as your layout
<?php
$url = "http://www.yourdomain.com/emptypage";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$output = curl_exec($curl);
curl_close($curl)
$placeholder = "{{CONTENT}}"
$placeholderPos = strpos($output,$placeholder);
$beginning = substr($output,0,$placeholderPos);
$end = substr($output,$placeholderPos+strlen($placeholder));
echo $beginning;
////// your form //////
echo $end;
?>
You may have to deal with relative path after that, but this should get you started.
So, I finally found a way I think is the best since it uses cake classes.
I created a file new_file.php on webroot that is basically a copy of index.php but instead of using a generic request it requests the specific page I'm looking for:
$Dispatcher = new Dispatcher();
$Dispatcher->dispatch(new CakeRequest('CONTROLLER/ACTION'), new CakeResponse(array('charset' => Configure::read('App.encoding'))));
Of course, you'll have to change 'CONTROLLER/ACTION' to whatever your controller is.
After that, you only have to include the file in a WordPress plugin.
There is only one more change. There are some methods that conflict with WP declarations. PHP will complain when you include the above file. You have to find those method and wrap them into an if to make sure the method is not redeclared. This can break some functionality like localization (function __()) but it is ok if what you are including is not a very complex cake application.
if (!function_exists('methodName')) {
Hopefully the last issue will be solved once Cake 3 is out with namespaces support.

Resources