Symfony несколько загрузок файлов сбрасывает предыдущие поля

Или иначе, вопрос в том, как не обновлять существующие поля, если FileTypes пусты.

я использовал Эта статья для загрузки файла в двух полях (Eaudit и Tspec) в объекте Household с использованием Doctrine Listener.
Только я не использовал Uploader Service, так как в этом примере upload () существует в одном классе, а в полевом файле хранятся пути каталогов, передаваемые в качестве аргументов службы.

Проблема в том, что если я снова отправлю форму, она очищает предыдущие поля данных
(например, я уже отправил Eaudit после перезагрузки страницы, пытаясь передать Tspecification, и заметил, что Eaudit имеет значение null, и в противном случае).

Несмотря на функцию postLoad (), форма показывает пустые типы файлов. Также я использую поля eauditName / tspecificationName для хранения оригинальных имен UploadedFile.

РЕДАКТИРОВАТЬ:
Заметил, что если удалить поля, содержащие данные с

$builder->addEventListener(FormEvents::PRE_SET_DATA, function(FormEvent $event) {
$household = $event->getData();
$form = $event->getForm();
if (null !== $household->getEaudit()) {
$form->remove('eaudit');
}
if (null !== $household->getTspecification()) {
$form->remove('tspecification');
}
});

Форма не показывает form_rest (), и после отправки все то же поле с обновлениями данных в БД, но с моим реальным путем, например. C: \ Users \ Admin \ file.doc.

Symfony 2.8.19, помогите пожалуйста в моей проблеме, спасибо за внимание.

class DocumentsUploadListener {
private $eaudit;
private $tspec;

public function __construct($eaudit, $tspec) {
$this->eaudit = $eaudit;
$this->tspec = $tspec;
}

public function prePersist(LifecycleEventArgs $args) {
$entity = $args->getEntity();
$this->uploadFile($entity);
}

public function preUpdate(PreUpdateEventArgs $args) {
$entity = $args->getEntity();
$this->uploadFile($entity);
}

private function uploadFile($entity) {
if (!$entity instanceof Household) {
return;
}
$file1 = $entity->getEaudit();
// only upload new files
if ($file1 instanceof UploadedFile) {
$fileName1 = $this->upload($this->eaudit, $file1);
$entity->setEaudit($fileName1);
$entity->setEauditName($file1->getClientOriginalName());
}

$file2 = $entity->getTspecification();
if ($file2 instanceof UploadedFile) {
$fileName2 = $this->upload($this->tspec, $file2);
$entity->setTspecification($fileName2);
$entity->setTspecificationName($file2->getClientOriginalName());
}
}

public function postLoad(LifecycleEventArgs $args) {
$entity = $args->getEntity();
if (!$entity instanceof Household) {
return;
}
if ($fileName1 = $entity->getEaudit()) {
$entity->setEaudit(new File($this->eaudit.'/'.$fileName1));
}

if ($fileName2 = $entity->getTspecification()) {
$entity->setTspecification(new File($this->tspec.'/'.$fileName2));
}
}

public function upload($dest, UploadedFile $file) {
$fileName = md5(uniqid()).'.'.$file->guessExtension();
$file->move($dest, $fileName);
return $fileName;
}
}

Форма класса:

class HouseholdDocumentsType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('eaudit', FileType::class, [
'required' => false,
])
->add('tspecification', FileType::class, [
'required' => false,
])
->add('save', SubmitType::class)
;
}

public function configureOptions(OptionsResolver $resolver) {
$resolver
->setDefaults([
'data_class' => Household::class
]);
}

public function getBlockPrefix() {
return 'app_bundle_household_documents_type';
}
}

Класс сущности:

/**
* Household
*
* @ORM\Table(name="households")
* @ORM\Entity(repositoryClass="AppBundle\Repository\HouseholdRepository")
*/
class Household {
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;

/**
* @ORM\Column(type="string", nullable=true)
* @Assert\File(mimeTypes={"application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"})
*/
protected $eaudit;

/**
* @ORM\Column(type="string", nullable=true)
*/
protected $eauditName;

/**
* @ORM\Column(type="string", nullable=true)
* @Assert\File(mimeTypes={"application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"})
*/
protected $tspecification;

/**
* @ORM\Column(type="string", nullable=true)
*/
protected $tspecificationName;
/**
* Get id
*
* @return int
*/
public function getId() {
return $this->id;
}

/**
* @return mixed
*/
public function getEaudit() {
return $this->eaudit;
}

/**
* @param mixed $eaudit
*/
public function setEaudit($eaudit) {
$this->eaudit = $eaudit;
}

/**
* @param string $tspecification
* @return Household
*/
public function setTspecification($tspecification) {
$this->tspecification = $tspecification;
return $this;
}

/**
* @return string
*/
public function getTspecification() {
return $this->tspecification;
}

/**
* @param string $eauditName
* @return Household
*/
public function setEauditName($eauditName) {
$this->eauditName = $eauditName;
return $this;
}

/**
* @return string
*/
public function getEauditName() {
return $this->eauditName;
}

/**
* @param string $tspecificationName
* @return Household
*/
public function setTspecificationName($tspecificationName) {
$this->tspecificationName = $tspecificationName;
return $this;
}

/**
* @return string
*/
public function getTspecificationName() {
return $this->tspecificationName;
}
}

1

Решение

Задача ещё не решена.

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector