ExpressionEngine® 3 User Guide

Legacy Documentation

You are using the documentation for version 3.5.17. Go here for the latest version or check here for your available upgrades to the latest version.

CP/FilePicker Service

Simple Example

Controlling user uploads can be tricky. To help ease the process, the file picker service can be used to create simple file upload UIs:

$picker = ee('CP/FilePicker')->make();

This creates a file picker object for all upload directories that the user has access to. It creates up the required modal html and injects the correct javascript into the output of the page.

Now we need to create a link to actually pop the file picker modal:

$link = $filepicker->getLink('Click me!')->render();

And we need to show this link to the user:

<php echo $link; ?>

That’s all there is to it! Clicking this link will pop open a file picker and allow the user to choose an existing file or upload a new file. Of course, this is not helpful unless that choice is populated somewhere.

Usually, the information we need is the file id that they chose. We can automatically populate this in a hidden form element. First we need to create that input, we’ll put it near the link:

<input name="my-file" id="my-file" type="hidden">
<?php echo $link?>

And then we need to tell the link what the form element id is:

$link->withValueTarget('my-file');

You can also control this behavior more carefully by using a callback.

JavaScript Callbacks

The default javascript callbacks do not work for all cases. You can add your own using the $(...).FilePicker jQuery plugin. For this plugin to work you must still load the filepicker library in your controller. Then, simply call the plugin on your newly created link:

$('#my-upload').FilePicker({
  callback: function(data, references) {
    // Close the modal
    references.modal.find('.m-close').click();

    // do work with data
  }
});

The references will contain jQuery objects of the modal and the image tags and bound inputs, if any were specified. The data will contain a json representation of the selected file.