Select an related entity manually - forms

I have an entity that can have an image. This is done using a OneToMany relationship. Now I want the user to choose an image. I can of course use a form field like this:
$builder->add('image', 'entity', array(
'label' => 'Image',
'class' => 'VendorNameBundle:Image',
'property' => 'id',
) );
It renders as expected a dropdown with all the ids. But what I actually want is only a single field that is hidden and that stores the id of the selected image.
This would work but it seems not like a good thing …
In the type:
$builder->add('_image', 'text', array(
'data' => $object->getImage()->getId(),
'property_path' => false
));
In the controller:
$_image = $form["_image"]->getData();
if ($_image) {
$image = $this->getDoctrine()->getRepository('VendorNameBundle:Image')->find($_image);
if ($image) {
$object->setImage($image);
}
}
My question is: How can I get a hidden text field that contains the ID of the related object and stores the new selected one?

Related

Provide default data in collection child form

I have a nested form with prototype feature in Symfony 2. Here is the parent form which contains the collection:
$builder
->add('rooms', 'collection', array(
'type' => new RoomForm(),
'allow_add' => true,
'allow_delete' => true,
'data' => array(new RoomForm()),
))
As you can see, no data_class is defined. After the form submission $form->getData() correctly return associative array.
RoomForm is a simple form class composed by two fields:
$builder
->add(
$builder->create('dateAvailabilityStart', 'text', array(
'label' => 'label.from'
)))
->add(
$builder->create('dateAvailabilityEnd', 'text', array(
'label' => 'label.until'
)))
I would like find a way to populate my collection with existing RoomForm (for edit mode) and associate data in correct fields.
Any ideas?
You could do it from within your controller. Given that above form type is named as RoomFormCollection you could do something like this:
// This should be an array
$rooms = ... // Either from database or...
$form = $this->createForm(new RoomFormCollection(), array(
'rooms' => rooms
));
Another thing, 'data' => array(new RoomForm()), is not valid. RoomForm as its name suggests is a form type, not data struct. You should remove it...
Hope this helps...

Creating collection of read-only entities in Symfony2

My question is about creating collection of entities. I know about "How To Embed Collection Forms" and successfully used it. But in this case I have:
Simple class
class Thing
{
/**
* #ORM\ManyToMany(targetEntity="DicStyle", mappedBy="things")
* ....
*/
protected $styles;
public function __construct()
{
$this->styles = new ArrayCollection();
}
}
Dictionary of styles
class DicStyle
{
.....
}
I don't need to create form for DicStyle objects, because this is read only objects = dictionary (unchangeable). So, I want to create a form with something like this:
$builder->add('styles', 'collection', array(
'type' => 'entity', 'options' => array(
'class' => 'MyEntityBundle:DicStyle'
)
))
Of course it's pseudo-code. I can not imagine how to implement it.
The result
Suppose, I have:
Table "Thing" with one row (id = 1).
Table "DicStyle" with 6 rows (id = from 1 to 6).
Table "mtm_thing_dicstyle" (many-to-many table)
In the form, I choose two DicStyle (id=3, id=5) for the Thing. So, the mtm_thing_dicstyle contains:
thing_id dicstyle_id
-------- ------------
1 3
1 5
Try this form:
$builder->add('styles', 'entity', array(
'class' => 'MyEntityBundle:DicStyle'
'property'=>'name' //what property do you want to see when you select,
'multiple" => true //you'll be able to select many DicStyle
'expanded' => false //it'll shown on a multiple choice select tag
)
);
To select one or more objects in a form to relate them to your result you can use the form field type "entity". (See form-types)
$builder->add('styles', 'entity', array(
'class' => 'MyEntityBundle:DicStyle',
'property' => 'name', // property you want to be displayed
'expanded' => true,
'multiple' => true
)
);
This would render checkboxes and therefore the possibility to select multiple entities to be referenced.
Keep in mind, if you use multiple => true there are two options:
expanded => false: renders a multiselect field
expanded => true: renders checkboxes
See form-entity-type-options

magento custom module which uploads multiple images

I want to create custom module which can upload multiple images like product.I have created one custom module but it uploads only one image.
form.php
$fieldset->addField('filename', 'image', array(
'label' => Mage::helper('footertop')->__('File'),
'name' => 'filename',
));
I think you need to create your custom renderer for the image field. For this create this class in your module:
class [YOURNamespace]_[YOURModule]_Block_Adminhtml_[YOUREntity]_Helper_Image extends Varien_Data_Form_Element_Image{
//make your renderer allow "multiple" attribute
public function getHtmlAttributes(){
return array_merge(parent::getHtmlAttributes(), array('multiple'));
}
}
Now at the top of your _prepareForm (where you add your fields) add this line before adding any field:
$fieldset->addType('image', '[YOURNamespace]_[YOURModule]_Block_Adminhtml_[YOUREntity]_Helper_Image');
Or if you want to be "politically correct" add it this way:
$fieldset->addType('image', Mage::getConfig()->getBlockClassName('[YOURmodule]/adminhtml_[YOURentity]_helper_image'));
This will tell Magento that in your current fieldset, all the fields with type image should be rendered by your own class.
Now you can add your field like similar to how you did it:
$fieldset->addField('image', 'image', array(
'name' => 'image[]', //declare this as array. Otherwise only one image will be uploaded
'multiple' => 'multiple', //declare input as 'multiple'
'label' => Mage::helper('YOURmodule')->__('Select Image'),
'title' => Mage::helper('YOURmodule')->__('Can select multiple images'),
'required' => true,
'disabled' => $isElementDisabled
));
That's it.
Don't forget to replace the placeholders ([YOURModule] and others) with your values.

Example of Zend Form with Collection Element using Forms not Fieldsets in Zend Framework2

I need a straight forward working example how I can include a collection element in Zend Form, I have seen some examples from Zend Framework 2 site and from previous posts in StackOverflow where most of them pointed to this link. But right now I am not using Fieldsets and staying with Forms, so in case if someone can direct me in the right way, how I can include a simple collection element when the user gets a page where the user can choose multiple choices from the shown collection form. Much better would be populating the collection form from database.
I have searched in the internet for quite a sometime now and thought I would post here, so that Zend profis can give their suggestions.
Just For Information:
Normally one can include a static dropdownbox in Zend Form in this fashion
$this->add(
array(
'name' => "countr",
'type' => 'Zend\Form\Element\Select',
'options' => array(
'label' => "Countries",
'options' => array(
'country1' => 'Brazil',
'country2' => 'USA',
'country3' => 'Mexico',
'country4' => 'France',
)
)
)
);
So I am expecting a simple example which could give me a basic idea how this can be done.
To be honest, I don't see your problem here. Since form collections extend Fieldset which extends Element, you can just add it to the form as a regular element. The view helpers will take care of the rendering recursively.
Step 1: Create a form collection (create an instance of Zend\Form\Element\Collection). If the elements have to be added dynamically in some way, I'd create a factory class for this purpose.
Step 2: Add it to the form. (For example using $form->add($myCollectionInstance).)
Step 3: Render it. Zend\Form\View\Helper\Collection is a pretty good view helper to render the whole form without any pain.
You can also create a new class extending Zend\Form\Element\Collection and use the constructor to add the fields you need. Thus, you can add it to the form using the array you've pasted in your question. Also, you could directly use it in annotations.
Hope this helps.
If you just want to fill in a select list with option values you can add the array to the select list in a controller:
$form = new MyForm();
$form->get('countr')->setOptions(array('value_options'=>array(
'country1' => 'Brazil',
'country2' => 'USA',
'country3' => 'Mexico',
'country4' => 'France',
));
the array can be fetched from db.
this is a different example for using form collections in the simplest way.
In this example it creates input text elements in a collection and fills them in. The number of elements depends on the array:
class MyForm extends \Zend\Form\Form
{
$this->add(array(
'type' => '\Zend\Form\Element\Collection',
'name' => 'myCollection',
'options' => array(
'label' => 'My collection',
'allow_add' => true,
)
));
}
class IndexController extends AbstractActionController
{
public function indexAction
{
$form = new MyForm();
$this->addElementsFromArray($form, array(
'country1' => 'Brazil',
'country2' => 'USA',
'country3' => 'Mexico',
'country4' => 'France',
));
//the above line can be replaced if fetching the array from a db table:
//$arrayFromDb = getArrayFromDb();
//$this->addElementsFromArray($form, $arrayFromDb);
return array(
'form' => $form
);
}
private function addElementsFromArray($form, $array)
{
foreach ($array as $key=>$value)
{
$form->get('myCollection')->add(array(
//'type' => '\Zend\Form\Element\SomeElement',
'name' => $key,
'options' => array(
'label' => $key,
),
'attributes' => array(
'value' => $value,
)
));
}
}
}
index.phtml:
$form->setAttribute('action', $this->url('home'))
->prepare();
echo $this->form()->openTag($form);
echo $this->formCollection($form->get('myCollection'));
echo $this->form()->closeTag();

Add Entity field type to form with event subscriber class

I am doing something very similar to this cookbook example http://symfony.com/doc/current/cookbook/form/dynamic_form_generation.html#adding-an-event-subscriber-to-a-form-class
The main difference is that my field type is an entity and not a text type.
So my field subscriber preSetData method looks like this:
public function preSetData(DataEvent $event)
{
$data = $event->getData();
$form = $event->getForm();
if (null === $data) {
return;
}
if(!$data->getIsCategorized()){
$form->add(
$this->factory->createNamed('categories', 'entity', array(
'class' => 'My\PostBundle\Entity\Category',
'property' => 'name',
'multiple' => true,
'label' => 'Category'
)
)
);
}
}
This is giving the following error
Class does not exist
500 Internal Server Error - ReflectionException
If I add the entity directly in my form type with $builder->add('categories, 'entity', array(... it works fine
Is it possible to attach an entity field type to a form using a field event subscriber in this fashion?
I ran into the same problem, and actually it's because the factory->createNamed() method has more argument than the builder->add
The third argument isn't the options array, but a "data" argument.
So here's what you should do :
$form->add(
$this->factory->createNamed('categories', 'entity', null, array(
'class' => 'My\PostBundle\Entity\Category',
'property' => 'name',
'multiple' => true,
'label' => 'Category'
)
)
);
(add null before the options array)
Whether you attach a field in the type or by means of an event listener/subscriber should make no difference. Either you have a small mistake somewhere (likely), or that's a bug, in which case you should submit it to the issue tracker.