Иногда требуется иметь возможность прикрепить файл к объекту в форме ExtJS.
Для этого нужно у формы указать параметры (не забываем, что форм 2 - создание и редактирование):
customExtra.window.CreateItem = function (config) {
// ...
Ext.applyIf(config, {
title: _('customextra_item_create'),
// ...
fileUpload: true,
enctype : 'multipart/form-data',
// ....
});
customExtra.window.CreateItem.superclass.constructor.call(this, config);
// Закрываем окно при скрытии
this.on('hide', function() {
var w = this;
window.setTimeout(function() {
w.close()
}, 300);
})
};
Теперь вместо текстового поля вставим поле для загрузки файла и, для красоты, кнопку загрузки:
if (i == 1) {
fields.push({
layout:'column'
,border: false
,anchor: '100%'
,items: [{
columnWidth: .4
,layout: 'form'
,defaults: { msgTarget: 'under' }
,border:false
,items: [{
xtype: 'fileuploadfield'
,name: 'string1_loader'
,allowBlank:true
,anchor: '100%'
,id: 'customextra-items-string1_loader'
,hidden: true
,listeners: {
change: function() {
}
}
},{
xtype: 'button'
,fieldLabel: _('customextra_item_string' + i)
,text: 'Загрузить файл'
,allowBlank:true
,anchor: '100%'
,listeners: {
click: {fn: function(){
document.getElementById('customextra-items-string1_loader-file').click();
document.getElementById('customextra-items-string1_loader-file').addEventListener('change', function() {
document.getElementById('customextra-items-string1-holder').innerHTML = document.getElementById('customextra-items-string1_loader-file').files[0].name;
}, false);
}, scope: this}
}
}]
},{
columnWidth: .6
,layout: 'form'
,defaults: { msgTarget: 'under' }
,border:false
,items: [{
id: 'customextra-items-string1-holder'
,anchor: '100%'
,style: {margin: '34px 15px 0 0', overflow: 'hidden', display: 'inline-block', padding: '10px', 'vertical-align': 'top'}
,listeners: {
afterrender: function() {
var val = Ext.getCmp('customextra-items-string1').getValue();
if (val) {
var tmp, filename, ext;
tmp = val.split('/');
filename = tmp[tmp.length - 1];
tmp = filename.split('.');
ext = tmp[tmp.length - 1];
filename = filename.replace('.' + ext, '');
tmp = filename.split('-uid');
filename = tmp[0] + '.' + ext;
this.update('<a href="'+val+'" target="_blank">'+filename+'</a>');
}
}
}
}]
}]
},{
xtype: 'textfield',
name: 'string' + i,
id: 'customextra-items-string1',
anchor: '99%',
allowBlank: true,
labelStyle: 'display: none;',
style: {height: '1px', 'min-height': '1px', 'font-size': '1px', color: '#fff', padding: 0, border: 'none'}
});
} else {
fields.push({
xtype: 'textfield',
fieldLabel: _('customextra_item_string' + i),
name: 'string' + i,
id: 'customextra-items-string1',
anchor: '99%',
allowBlank: true,
});
}
И добавляем загрузку файла в процессорах:
/**
* @return bool
*/
public function beforeSet() {
// добавляем загрузку файла
if ($_FILES['string1_loader']['tmp_name']) {
$source = $this->modx->getObject('sources.modMediaSource', 1);
$source->initialize();
$file_dir = 'files/' . date('Y-m') . '/' . date('d') . '/';
$dirs = explode('/', $file_dir);
$path = $this->modx->getOption('base_path') . trim($this->modx->getOption('assets_url'), '/');
foreach ($dirs as $dir) {
$path = $path . '/' . trim($dir, '/');
if (!file_exists($path)) {
mkdir($path);
}
}
foreach ($_FILES as $key => $file) {
$tmp = explode('.', $file['name']);
$ext = array_pop($tmp);
$filename = str_replace(' ', '-', implode('.', $tmp)) . '-uid' . md5(time()) . '.' . $ext;
$_FILES[$key]['name'] = $filename;
$size = $_FILES[$key]['size'];
}
$this->setProperty('string1', str_replace($this->modx->getOption('base_path'), '/', $path) . $filename);
if (!$source->uploadObjectsToContainer($this->modx->getOption('assets_url') . $file_dir, $_FILES)) {
foreach ($source->errors as $error) {
$this->modx->lexicon->load('core:file');
$this->addFieldError('string1', $this->modx->lexicon($error, array(
'ext' => $ext,
'size' => $size,
'allowed' => $this->modx->getOption('upload_maxsize')
)));
}
}
}
// конец
$name = trim($this->getProperty('name'));
if (empty($name)) {
$this->modx->error->addField('name', $this->modx->lexicon('customextra_item_err_name'));
}
elseif ($this->modx->getCount($this->classKey, array('name' => $name))) {
$this->modx->error->addField('name', $this->modx->lexicon('customextra_item_err_ae'));
}
return parent::beforeSet();
}
Чтобы в таблице тоже отображалась ссылка на файл, поправим getlist-процессор:
public function prepareRow(xPDOObject $object) {
$array = $object->toArray();
// Выводим ссылку на файл
if ($array['string1']) {
$array['string1'] = '<a href="' . $array['string1'] . '" target="_blank">Скачать файл</a>';
}
// конец
// ...
}
Теперь к объектам можно прикреплять файлы:

Кроме того, можно сделать специализированный загрузчик для картинок:
Прикрепление картинки к объекту на ExtJS

и еще хотел спросить, если через FormIt залить файл, он зальется в customExtra?
Спасибо заранее