具有集合FormType的OneToMany原则列

时间:2018-09-27 23:03:35

标签: php symfony collections orm doctrine

我有一个CollectionType,我试图将其用于将多个字符串插入实体MotorsAdsFile(图像实体)中,并通过id使它们与当前实体相关。我使用Blueimp,每次上传图片时都创建一个像这样的新小部件

scripts.js

$('.file-uploader').bind('fileuploaddone', function(e, data) {
  $.each(data.files, function(index, file) {
    $('.file-uploader').addAnotherWidget(file.name);
  });
});

// $('.add-another-collection-widget').click(function(e) {
$.fn.addAnotherWidget = function(fileName) {
  // var list = $($(this).attr('data-list'));
  var list = $(this);
  // Try to find the counter of the list
  var counter = list.data('widget-counter') | list.children().length;
  // If the counter does not exist, use the length of the list
  if (!counter) {
    counter = list.children().length;
  }

  // grab the prototype template
  var newWidget = list.attr('data-prototype');
  // replace the "__name__" used in the id and name of the prototype
  // with a number that's unique to your emails
  // end name attribute looks like name="contact[emails][2]"
  newWidget = newWidget.replace(/__name__/g, counter);
  // Increase the counter
  counter++;
  // And store it, the length cannot be used if deleting widgets is allowed
  list.data(' widget-counter', counter);

  // create a new list element and add it to the list
  var newElem = $(list.attr('data-widget-tags')).html(newWidget);
  newElem.appendTo(list);
  // $('.file-uploader').find('#listing_images_'+counter).attr('value', 'asdf');
  var input = counter-1;
  $('#listing_images_'+input).val(fileName);
};

因此,我创建了新的小部件并将其值设为文件名。 ListingType格式内的我的CollectionType(应该附加图像的主要实体看起来像这样

ListingType.php

    ->add('images', CollectionType::class, [
        'label' => 'Drop files here',
        // 'existingFiles' => $options['existingFiles'],
        // 'editId' => $options['editId'],
        'entry_type' => BlueimpType::class,
        'prototype' => true,
        'allow_add' => true,
        'attr' => [
          'class' => 'file-uploader',
          'data-widget-tags' => '<li></li>',
        ],
        'allow_delete' => true,
        'entry_options' => [
          'attr' => ['class' => ''],
        ],
    ])

Blueimp,我创建的自定义类型是

BlueimpType.php

<?php
namespace DirectoryPlatform\FrontBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use AdamQuaile\Bundle\FieldsetBundle\Form\FieldsetType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;

class BlueimpType extends AbstractType
{
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
        // default form options
        'existingFiles' => '',
        'listing_id' => '',
        'editId' => '',
        'data_class' => 'DirectoryPlatform\AppBundle\Entity\MotorsAdsFile',
        ));
    }
    /**
     * {@inheritdoc}
     */
    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        $view->vars['existingFiles'] = $options['existingFiles'] ?? [];
        $view->vars['editId'] = $options['editId'] ?? [];
    }
    public function getParent()
    {
        return TextType::class;
    }
}

OneToMany和相应的方法位于Listing.php实体

Listing.php

/**
 * @ORM\OneToMany(targetEntity="MotorsAdsFile", mappedBy="listing", cascade={"persist"}, orphanRemoval=true)
 */
private $images;
/**
 * @param mixed $images
 */
public function setImages($images)
{
  $this->images = $images;
}
/**
 * @return mixed
 */
public function getImages()
{
    return $this->images;
}

MotorsAdsFile.php(图像实体)中,我有一个ManyToOne用于图像

MotorsAdsFile.php(图像实体)

<?php

namespace DirectoryPlatform\AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="DirectoryPlatform\AppBundle\Repository\MotorsAdsFileRepository")
 * @ORM\Table(name="motorsadsfile")
 */
class MotorsAdsFile
{

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    public $id;

    /**
       * @ORM\ManyToOne(targetEntity="Listing", inversedBy="images")
       * @ORM\JoinColumn(name="listing_id", referencedColumnName="id", onDelete="CASCADE")
     */
    protected $listing;

    /**
     * @ORM\Column(type="string", length=255, name="images")
     */
    protected $image;

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

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


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

    /**
     * @param Listing $listing
     */
    public function setListing(Listing $listing)
    {
        $this->listing = $listing;
    }
}

我尝试过使用数据类,例如,不在BlueimpType.php中使用数据类,而是将其作为CollectionType的一部分,但是我得到了Cannot read index "1" from object of type "Directory Platform\AppBundle\Entity\MotorsAdFile" because it doesn't implement \ArrayAccess.并使用TextType徒劳无功。我不确定应该在data_class还是CollectionType中实现BlueimpType的确切位置。如果在BlueimpType中将其设置为默认选项,则会得到The object could not be created的错误,但是如果在CollectionType中将其设置为错误,则会出现关于ArrayAccess的错误。

0 个答案:

没有答案