silverstripe-framework/docs/en/02_Developer_Guides/11_Integration/How_Tos/Import_CSV_through_a_Controller.md

86 lines
2.2 KiB
Markdown
Raw Normal View History

---
title: Import CSV Data through a Controller
summary: Data importing through the frontend
icon: upload
---
# Import CSV Data through a Controller
You can have more customised logic and interface feedback through a custom controller. Let's create a simple upload
form (which is used for `MyDataObject` instances). You can access it through
`http://yoursite.com/MyController/?flush=all`.
```php
use SilverStripe\Forms\Form;
use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\FileField;
use SilverStripe\Forms\FormAction;
use SilverStripe\Forms\RequiredFields;
use SilverStripe\Dev\CsvBulkLoader;
use SilverStripe\Control\Controller;
2017-08-07 05:11:17 +02:00
class MyController extends Controller
{
2017-08-07 05:11:17 +02:00
private static $allowed_actions = [
'Form'
];
2017-08-07 05:11:17 +02:00
protected $template = "BlankPage";
2017-08-07 05:11:17 +02:00
public function Link($action = null)
{
return Controller::join_links('MyController', $action);
}
2017-08-07 05:11:17 +02:00
public function Form()
{
$form = new Form(
$this,
'Form',
new FieldList(
new FileField('CsvFile', false)
),
new FieldList(
new FormAction('doUpload', 'Upload')
),
new RequiredFields()
);
return $form;
}
2017-08-07 05:11:17 +02:00
public function doUpload($data, $form)
{
$loader = new CsvBulkLoader('MyDataObject');
$results = $loader->load($_FILES['CsvFile']['tmp_name']);
$messages = [];
2017-08-07 05:11:17 +02:00
if($results->CreatedCount()) {
$messages[] = sprintf('Imported %d items', $results->CreatedCount());
}
2017-08-07 05:11:17 +02:00
if($results->UpdatedCount()) {
$messages[] = sprintf('Updated %d items', $results->UpdatedCount());
}
2017-08-07 05:11:17 +02:00
if($results->DeletedCount()) {
$messages[] = sprintf('Deleted %d items', $results->DeletedCount());
}
2017-08-07 05:11:17 +02:00
if(!$messages) {
$messages[] = 'No changes';
2017-08-07 05:11:17 +02:00
}
2017-08-03 05:35:09 +02:00
$form->sessionMessage(implode(', ', $messages), 'good');
return $this->redirectBack();
}
}
```
[alert]
This interface is not secured, consider using [Permission::check()](api:SilverStripe\Security\Permission::check()) to limit the controller to users with certain
access rights.
[/alert]