2016-09-26 4 views
1

뒤로 손으로 대부분의 코드를 수행 할 때 제출할 때 게시물을 통해 배열로 처리하는 div 요소의 가변 개수로 구성된 양식이 있었지만, 하지만 저는 Symfony에서 비슷한 일을하는 법을 알기가 어렵습니다. 정말 좌절하기 시작합니다. 여기에 (내 자신의 간단한 템플릿 엔진) 객체에 대한 템플릿 클래스의 내 원래의 구현입니다 :Symfony 양식의 객체 배열을 만들고 렌더링하는 방법

<div class="img_transfer"> 
    <img class="toggle" src="{{src}}"> 
    <input class="title" type="text" name="title[{{i}}]" placeholder="Title"><br> 
    Upload to Sta.sh: 
    <input type="radio" name="stash[{{i}}]" value="0" checked="checked"> No 
    <input type="radio" name="stash[{{i}}]" value="1"> Yes<br> 
    Showcase: 
    <input type="radio" name="showcase[{{i}}]" value="0" checked="checked"> No 
    <input type="radio" name="showcase[{{i}}]" value="1"> Yes<br> 
    <input class="save" type="hidden" name="save[{{i}}]" value="0"> 
    <input type="hidden" name="old_path[{{i}}]" value="{{old_path}}"> 
</div> 

{{i}}는 루프 반복을위한 자리였다, 그리고이 잘 작동했지만, 여기에 내가 봤는데 방법

$img_tmp = glob('img_tmp/*.*'); 
$data = array(); 
foreach ($img_tmp as $src) { 
    //$inter = end(); 
    $parts = explode('/', $src); 
    $file = end($parts); 
    //$name = explode($inter)[0]; 
    $name = explode('.', $file)[0]; 
    $data[$name] = new Art(); 
} 

$builder = $this->createFormBuilder($data); 
foreach ($data as $key => $value) { 
    //$builder->add($key, (new ArtType())->setSrc($key)); 
    $builder->add($key, ArtType::class, array('img_src' => $key)); 
} 

$form = $builder->getForm(); 

return $this->render('img_transfer.html.twig', array('form' => $form->createView())); 

이 주로 SO 객체의 형태를 가지고하는 방법에 대한 다른 제안을 기반으로하지만 그대로가 건설 될 날 폼에 사용자 지정 옵션을 보낼 수 없습니다 : 심포니에서 일을하려고 이것은 내가 손으로 쉽게 구현 한 것을이 일로 이끄는 데있어서 나의 마지막 장벽이 될 것이라고 생각합니다. 나는 제안을 전적으로 환영하며, 이것을하기보다 덜 해킹하는 방법을 선호 할 것이며, 또한 내가 이것을하는 간단한 방법을 간과하고 있는지 또는 내가 인식하는 것처럼 끔찍하게 직관적이지 않은지를 알고 싶어 할 것이다. 그럴거야. 나는 시간이있을 때 이것을 편집하고 구조 조정하여 더 좋은 질문이 될 것입니다.

편집 : 포맷 및 추가 정보 : 응용 프로그램이 특정 부분은 "웹/img_tmp"디렉토리에 버려진 임의의 이름과 확장자의 이미지를 가지고 가고, "웹로 이동하도록되어 /img "디렉토리를 PHP의 uniqid()로 이름을 변경하고 데이터베이스에 입력 할 수 있습니다. 나는 각 "/ img_tmp/"에 대한 그룹화 된 집합을 생성하는 무언가가 필요합니다. DB에 저장하기 전에 각 속성을 설정할 수 있습니다. 한 번에 여러 객체를 제출하는 방법에 관해서는 아직 알지 못했던 모든 자료가 불완전하거나 과도하게 복잡해졌습니다.

답변

1

밝혀 졌 듯이 필자는 더 이상 사용되지 않는 코드, 즉 내 사용자 정의 형식의 메서드를 찾고있었습니다.이 메서드는 분명히 Symfony 3.0에서 제거되었습니다.

컨트롤러 코드

public function someAction() 
{ 
    $vals = array('customVal1', 'customVal2', 'customVal3'); 
    foreach ($vals as $v) { 
     $data[$v] = new YourObject(); 
    } 

    $builder = $this->createFormBuilder($data); 
    //I put this here so I don't have to scroll all the way to the bottom to submit; 
    //this will render it at the top by default (at least on mine) 
    $builder->add('submit', SubmitType::class, array('label' => 'Submit')); 

    foreach ($vals as $v) { 
     $builder->add($v, YourObjectType::class, array(
      'custom_val' => $v 
     )); 
    } 

    $form = $builder->getForm(); 

    return $this->render('the_page.html.twig', array('form' => $form->createView())); 
} 

사용자 양식 서식

{% block yourobject_widget %} 
    <div> 
     <img src="{{ custom_val }}"> //This is set by the call to setAttribute() in YourObjectType 
     {% for child in form %} 
      {{ form_row(child) }} 
     {% endfor %} 
    </div> 
{% endblock %} 

응용 프로그램 : 참고로, 여기 당신이 그들에게 양식을 패스 사용자 지정 옵션을 여러 개체를 제출하는 방법의 전체 코드는 /config/config.yml

twig: 
    debug:   "%kernel.debug%" 
    strict_variables: "%kernel.debug%" 
    form_themes: 
     - 'form/fields.html.twig' 

마지막으로 YourObjectType

namespace AppBundle\Form\Type; 

use Symfony\Component\Form\AbstractType; 

use Symfony\Component\Form\Extension\Core\Type\TextType; 
use Symfony\Component\Form\Extension\Core\Type\ChoiceType; 
use Symfony\Component\Form\Extension\Core\Type\CollectionType; 
use Symfony\Component\Form\Extension\Core\Type\HiddenType; 
use Symfony\Component\Form\Extension\Core\Type\SubmitType; 

use Symfony\Component\Form\FormView; 
use Symfony\Component\Form\FormInterface; 
use Symfony\Component\Form\FormBuilderInterface; 
use Symfony\Component\OptionsResolver\OptionsResolver; 

class YourObjectType extends AbstractType 
{ 
    public function configureOptions(OptionsResolver $resolver) 
    { 
     parent::configureOptions($resolver); 

     $resolver->setDefaults(array(
      'data_class' => 'AppBundle\Entity\YourObject', 
      'custom_val' => '' //This is important. You have to set defaults for 
           //options for Symfony to allow you to pass them 
     )); 
    } 

    public function buildView(FormView $view, FormInterface $form, array $options) 
    { 
     $view->vars['custom_val'] = $options['custom_val']; 
    } 

    public function buildForm(FormBuilderInterface $builder, array $options) 
    { 
     $builder->add('some_text_field', TextType::class) 
      ->add('some_choice_field', ChoiceType::class, array(
       'choices' => array('Yes' => true, 'No' => false), 
       'expanded' => true 
      )) 
      ->add('some_hidden_field', HiddenType::class, array('mapped' => false)) 
      ->setAttribute('custom_val', $options['custom_val']); 
    } 
}