Рабочие formit2file и formit2resource

Всем привет.

Задача: создание ресурса во фронте, а также загрузка файла с помощью формы отправки заявки/объявления.

Форма:
[[!FormIt?
    &hooks=`formit2file,formit2resource,spam,email,redirect`
    &redirectTo=`1`
]]

<form action="[[~[[*id]]]]" method="post" class="form-horizontal" enctype="multipart/form-data">
    <input type="hidden" name="nospam:blank" value="[[+fi.nospam]]" />
    
	<input name="resource_id" type="hidden" value="[[!+fi.id]]">
	<input id="parent" name="parent" type="hidden" value="32"> <!-- ID контейнера для модерации. У меня это Коллекция -->
	<input id="template" name="template" type="hidden" value="2"> <!-- ID шаблона для новых ресурсов -->
	<input id="published" name="published" type="hidden" value="0"> <!-- Статус: не опубликован -->
	<input id="hidemenu" name="hidemenu" type="hidden" value="1">
	<input id="cacheable" name="cacheable" type="hidden" value="1">
	<input name="show_in_tree" type="hidden" value="0"> <!-- Не показывать в дереве ресурсов в админке -->
    
	<div class="form-group">
		<label for="Rubriek" class="col-sm-2 control-label">Rubriek</label>
		<div class="col-sm-10">
    		<select class="form-control" name="rubriek" value="[[!+fi.rubriek]]">
                <option value="Rubriek 1">Rubriek 1</option>
                <option value="Rubriek 2">Rubriek 2</option>
                <option value="Rubriek 3">Rubriek 3</option>
    		</select>
    	</div>
	</div>
	<div class="form-group">
		<label for="geocomplete" class="col-sm-2 control-label">Город (Google Maps input)</label>
		<div class="col-sm-10">
			<input id="geocomplete" type="text" class="form-control" placeholder="Plaats" name="plaats" value="[[!+fi.plaats]]">
			<div class="map_canvas"></div>
		</div>
	</div>
	<div class="form-group">
		<label for="#" class="col-sm-2 control-label">Naam</label>
		<div class="col-sm-10">
			<input type="text" class="form-control" id="#" placeholder="Naam" name="naam" value="[[!+fi.naam]]">
		</div>
	</div>
	<div class="form-group">
		<label for="#" class="col-sm-2 control-label">GSM</label>
		<div class="col-sm-10">
			<input type="tel" class="form-control" id="#" placeholder="GSM" name="gsm" value="[[!+fi.gsm]]">
		</div>
	</div>
	<div class="form-group">
		<label for="afb1" class="col-sm-2 control-label">Foto</label>
		<div class="col-sm-10">
		    <input id="afb1" type="file" maxlength="300000" name="afb_1" value=[[!+fi.afb_1]]>
		</div>
	</div>
	<div class="form-group">
		<label for="#" class="col-sm-2 control-label">Titel</label>
		<div class="col-sm-10">
			<input type="text" class="form-control" id="#" placeholder="Titel" name="pagetitle" value="[[!+fi.pagetitle]]">
		</div>
	</div>
	<div class="form-group">
		<label for="#" class="col-sm-2 control-label">Content</label>
		<div class="col-sm-10">
			<textarea class="form-control" rows="5" placeholder="Content" name="content" value="[[!+fi.content]]"></textarea>
		</div>
	</div>
	<div class="form-group">
		<label for="inputEmail3" class="col-sm-2 control-label">Email</label>
		<div class="col-sm-10">
			<input type="email" class="form-control" id="inputEmail3" placeholder="Email" name="email" value="[[!+fi.email]]">
		</div>
	</div>
	<div class="form-group">
		<div class="col-sm-offset-2 col-sm-10">
			<button type="submit" class="btn btn-default">Verzenden</button>
		</div>
	</div>
</form>
Сниппет formit2file:
<?php
// initialize output;
$output = true;
$counter = 1;
 
// valid extensions
$ext_array = array('jpg', 'png', 'gif', 'JPG');
 
// create unique path for this form submission
$uploadpath = 'assets/uploads/user_images/'.date('Y-m-d').'';
 
// get full path to unique folder
$target_path = $modx->config['base_path'] . $uploadpath;
 
// get uploaded file names:
$submittedfiles = array_keys($_FILES);
 
// loop through files
foreach ($submittedfiles as $sf) {
 
    // Get Filename and make sure its good.
    $filename = basename( $_FILES[$sf]['name'] );
 
    // Get file's extension
    $ext = pathinfo($filename, PATHINFO_EXTENSION);
    $ext = mb_strtolower($ext); // case insensitive
 
    // is the file name empty (no file uploaded)
    if($filename != '') {
         
        // is this the right type of file?
        if(in_array($ext, $ext_array)) {
     
            // clean up file name and make unique
            $filename = $counter . '.' . $ext; 
            $filename = str_replace(' ', '_', $filename); // spaces to underscores
            $filename = date("G-i-s_") . $filename; // add date & time
             
            // full path to new file
            $myTarget = $target_path . $filename;
             
            // create directory to move file into if it doesn't exist
            mkdir($target_path, 0755, true);
             
            // is the file moved to the proper folder successfully?
            if(move_uploaded_file($_FILES[$sf]['tmp_name'], $myTarget)) {
                // set a new placeholder with the new full path (if you need it in subsequent hooks)
                $myFile = $uploadpath . $filename;
                $hook->setValue($sf,$myFile);
                // set the permissions on the file
                if (!chmod($myTarget, 0644)) { /*some debug function*/ }
                 
            } else {
                // File not uploaded
                $errorMsg = 'There was a problem uploading the file.';
                $hook->addError($sf, $errorMsg);
                $output = false; // generate submission error
            }
         
        } else {
            // File type not allowed
            $errorMsg = 'Type of file not allowed.';
            $hook->addError($sf, $errorMsg);
            $output = false; // generate submission error
        }
     
    // if no file, don't error, but return blank
    } else {
        $hook->setValue($sf, '');
    }
$counter = $counter + 1;
}
return $output;
Спиппет formit2resource:
<?php
$doc = $modx->getObject('modResource',array('id'=>$hook->getValue('resource_id')));
   
if (empty($doc)){
    $doc = $modx->newObject('modResource');
    $doc->set('createdby', $modx->user->get('id'));
}
else{
    $doc->set('editedby', $modx->user->get('id'));
}
   
$allFormFields = $hook->getValues(); 
foreach ($allFormFields as $field=>$value)
{
   
   if ($field !== 'spam' && $field !== 'resource_id'){
         $doc->set($field, $value);
    }
  
   //we need to parse the title into the alias
   if($field == 'pagetitle'){
      //replace spaces with -
      $alias = preg_replace('/[\' \']/' , '-' , $value);
  
      //remove non alpha and a common injection string 
      $alias = preg_replace('/[^a-z0-9\.\x0B\-]/i' , '' , $alias);
  
                                   //this is the standard revo regexp
                                   // \0\x0B\t\n\r\f\a&=+%#<>"~:`@\?\[\]\{\}\|\^'\
   }
}
 // now set the alias
 $doc->set('alias', $alias);
   
$doc->set('template', $template);
$isnew = $doc->isNew();
  
if ($doc->save()) {
    if ($isnew) {
        $doc->set('alias', $doc->get('alias' . '-' . $doc->get('id')));
        $doc->save();
    }
}
 
foreach ($allFormFields as $field=>$value)
{
    if ($tv = $modx->getObject('modTemplateVar', array ('name'=>$field)))
    {
        /* handles checkboxes & multiple selects elements */
        if (is_array($value)) {
            $featureInsert = array();
            while (list($featureValue, $featureItem) = each($value)) {
                $featureInsert[count($featureInsert)] = $featureItem;
            }
            $value = implode('||',$featureInsert);
        }   
        $tv->setValue($doc->get('id'), $value);
        $tv->save();
    }
}

$modx->cacheManager->refresh();
return true;
TV-параметр с названием afb_1, тип Изображение.

Замечания (мои исправленные ошибки):
  1. При вызове &hooks=`formit2file,formit2resource,spam,email,redirect` на первом месте должен стоять хук formit2file, а на втором месте стоят formit2resource. Лично я потратил много времени на это, пока не догадался
  2. Источник файлов для TV должен быть Filesystem, а не самостоятельно созданный
Anton
09 января 2017, 12:00
modx.pro
3
2 835
+1

Комментарии: 6

Артём
17 мая 2017, 09:22
1
0
Здравствуйте! Пробую настроить форму добавления новостей по Вашему принципу, и не получается… При попытке отправить форму, выскакивает ошибка в файловом импате: «There was a problem uploading the file.». В Modx в логах появляется ошибка
/core/cache/includes/elements/modsnippet/55.include.cache.php : 44) PHP warning: mkdir(): Файл существует
, «где /core/cache/includes/elements/modsnippet/55.include.cache.php» — кешируемый сниппет formit2file. Почему возникает ошибка «mkdir(): Файл существует» в 44 строке, и как ее исправить?
44 строка:
mkdir($target_path, 0755, true);
При том получается так, что папка создается, а файл не загружается. Помогите пожалуйста.
    Андрей
    25 июля 2017, 11:30
    0
    Здравствуйте. Как решили проблему?
      Артём
      25 июля 2017, 12:53
      1
      +1
      День добрый. Я уже особо и не помню, но вроде проблема была в версии formit. В formit 3 не работает данный скрипт, если вернуть на старую, 2.11, вроде, то скрипт начинает работу.
        Андрей
        25 июля 2017, 16:50
        0
        Спасибо, получилось.
          Артём
          25 июля 2017, 17:03
          0
          Получилось, как я сказал я на 2ой версии или на 3ей?
            Андрей
            25 июля 2017, 17:06
            0
            я откатился на 2 версию
    Авторизуйтесь или зарегистрируйтесь, чтобы оставлять комментарии.
    6