ZF2 Radio Input Display in Column - forms

Is it possible for to display in a column instead of side by each?
The Radio options are selected in FormElement
namespace Main\Form\Element;
use Doctrine\ORM\EntityManager;
use Zend\Form\Element\Radio;
/**
* Class SurveyAnswerRadio
*
* #package Main\Form\Element
*/
class SurveyAnswerRadio extends Radio
{
/**
* #var EntityManager $entityManager
*/
protected $entityManager;
/**
* #param EntityManager $entityManager
*/
public function __construct(EntityManager $entityManager)
{
$this->entityManager = $entityManager;
}
/**
* Get Value Options
*
* #return array
*
* #throws \Exception
*/
public function getValueOptions()
{
$array = [];
$survey_question_reference = 1;
$result = $this->entityManager
->getRepository('AMDatabase\Entity\TheVerse\SA')
->findBy(
[
'sqReference' => $survey_question_reference
],
[
'surveyAnswer' => 'ASC'
]
);
if (is_array($result) && count($result) > '0') {
/**
* #var \AMDatabase\Entity\TheVerse\SA $val
*/
foreach ($result as $val) {
$array[$val->getReference()] = $val->getSurveyAnswer();
}
}
return $array;
}
}
This is added to the Form
/**
* Survey Answer
*/
$this->add(
[
'type' => 'Main\Form\Element\SurveyAnswerRadio',
'name' => 'survey_answer',
'options' => [
'label' => 'survey_answer'
],
'attributes' => [
'id' => 'survey_answer'
]
]
);
}
Then it is displayed within a view Twig
<div class="field">
<span>{{ formLabel(form.get('survey_answer')) }}</span>
{{ formRadio(form.get('survey_answer')) }}
</div>
The output encloses each within a . I am wanting the output to be displayed in this fashion:
<ul>
<li><label><input type="radio" name="survey_answer" id="survey_answer" value="1">option 1</label><li>
<li><label><input type="radio" name="survey_answer" id="survey_answer" value="2">option 2</label></li>
<li><label><input type="radio" name="survey_answer" id="survey_answer" value="3">option 3</label></li>
</ul>

use this command in view
$this->formRadio()->setSeparator('</li><li class="yourclass">');
this command set separator between your radio options.
then you show your element like this
<li class="yourclass" >
<?php echo $this->formRadio($form->get('survey_answer')); ?>
</li>

Related

Symfony Form never returns a value

I try to make a search bar but my form dont return value.
I am starting, I have already made symfony forms but there I really do not see :(
I use Symfony 4.12.10.
I always have the result in symfony profiler:
App \ Entity \ PropertySearch {# 707 ▼
-searchbar: null
}
html :
<form class="form-inline mr-auto">
{{ form_start(searchForm) }}
{{ form_errors(searchForm) }}
{{ form_row(searchForm.searchbar) }}
<button type="submit" class="btn btn-secondary my-4 ml-1 my-sm-0">🔍</button>
{{ form_end((searchForm)) }}
</form>
repository :
class TextesRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Textes::class);
}
/**
* #return Query
*/
public function findAllVisible(PropertySearch $search)
{
$query = $this->createQueryBuilder('p');
if ($search->getSearchbar()) { //Si l'utilisateur recherche
$query = $query->andwhere('p.title = :searchbar');
$query->setParameter('searchbar', $search->getSearchbar());
}
return $query->getQuery()->getResult();
}
form:
class SearchType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('searchbar', TextType::class, [
'label' => false,
'required' => false,
'attr' => [
'placeholder' => 'recherche...',
'style' => 'width: 50vw',
],]);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => PropertySearch::class,
'csrf_protection' => false,
]);
}
}
entity for the form:
class PropertySearch{
private $searchbar;
/**
* #return mixed
*/
public function getSearchbar()
{
return $this->searchbar;
}
/**
* #param mixed $searchbar
* #return PropertySearch
*/
public function setSearchbar($searchbar)
{
$this->searchbar = $searchbar;
return $this;
}
}
controller :
class TextController extends AbstractController
{
/**
* #Route("/liste", name="list")
*/
public function index(TextesRepository $repo, Request $request)
{
$search = new PropertySearch();
$searchform=$this->createForm(SearchType::class, $search);
$searchform->handleRequest($request);
return $this->render('text/index.html.twig', [
'controller_name' => 'TextController.php',
'articles' => $repo->findAllVisible($search),
'searchForm' => $searchform->createView()
]);
}
You don't need to use the form tag beacuse using form_start and form_end already creates this tag.
Due to this you have a form inside a form, what may cause some troubles in html forms.
{{ form_start(searchForm) }}
{{ form_errors(searchForm) }}
{{ form_row(searchForm.searchbar) }}
<button type="submit" class="btn btn-secondary my-4 ml-1 my-sm-0">🔍</button>
{{ form_end((searchForm)) }}
Documentation
Also I recommend you to add the submit button to the form. Link

TYPO3 add image upload field to feuser

TYPO3 version 7.6.18. I need to extend fe_user with new field for uploading image ? How to do it? I need add this field to front-end and back-end
ext_tables.php
CREATE TABLE fe_users (
backgroundimage int(11) unsigned NOT NULL default '0'
);
User.php
class User extends \In2code\Femanager\Domain\Model\User
{
/**
* #var string
*/
protected $backgroundimage = null;
/**
* Returns the background value
*
* #return string
* #api
*/
public function getBackgroundimage()
{
return $this->backgroundimage;
}
/**
* Sets the image backgroundimage
*
* #param $backgroundimage
*/
public function setBackgroundimage(\TYPO3\CMS\Extbase\Domain\Model\FileReference
$backgroundimage)
{
$this->backgroundimage = $backgroundimage;
}
/**
* __construct
*/
public function __construct()
{
//Do not remove the next line: It would break the functionality
$this->initStorageObjects();
}
/**
* Initializes all ObjectStorage properties
* Do not modify this method!
* It will be rewritten on each save in the extension builder
* You may modify the constructor of this class instead
*
* #return void
*/
protected function initStorageObjects()
{
}
}
setup.txt
config.tx_extbase{
persistence{
classes{
In2code\Femanager\Domain\Model\User {
subclasses {
0 = Fhk\Feusersplus\Domain\Model\User
}
}
Fhk\Feusersplus\Domain\Model\User {
mapping {
tableName = fe_users
recordType = 0
}
}
}
}
objects {
In2code\Femanager\Controller\NewController.className = Fhk\Feusersplus\Controller\NewController
In2code\Femanager\Controller\EditController.className = Fhk\Feusersplus\Controller\EditController
In2code\Femanager\Controller\UserController.className = Fhk\Feusersplus\Controller\UserController
#Kennziffer\KeQuestionnaire\Domain\Repository\ResultRepository.className = Fhk\Feusersplus\Domain\Repository\ResultRepository
}
}
There are my files. What is wrong ?
it is my Backgroundimage.html
{namespace femanager=Istar\Fefiles\ViewHelpers}
<f:render section="default" arguments="{_all}" />
<f:section name="default">
<div class="femanager_fieldset femanager_backgroundimage control-group">
<label for="femanager_field_backgroundimage" class="control-label">
<f:translate key="tx_feusersplus_domain_model_user.backgroundimage" default="Profile background image"/>
</label>
<femanager:form.upload property="backgroundimage" >
<f:if condition="{resource}">
<f:image image="{resource}" alt="" width="50"/>
</f:if>
</femanager:form.upload><br />
</div>
</div>
</f:section>
my set method
public function setBackgroundimage(\TYPO3\CMS\Extbase\Persistence\ObjectStorage $backgroundimage)
{
$this->backgroundimage = $backgroundimage;
}
All right? I still have the same error((
Now I have follow error:
Exception while property mapping at property path "backgroundimage": The identity property "2.jpg" is no UID.
Please try model like this User.php
<?php
namespace VendorName\ExtensionName\Domain\Model;
/**
* Users
*/
class User extends \In2code\Femanager\Domain\Model\User {
/**
* image
*
* #var \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\TYPO3\CMS\Extbase\Domain\Model\FileReference>
*/
protected $image = null;
/**
* Returns the image
*
* #return \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\TYPO3\CMS\Extbase\Domain\Model\FileReference> $image
*/
public function getImage()
{
return $this->image;
}
/**
* Sets the image
*
* #param \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\TYPO3\CMS\Extbase\Domain\Model\FileReference> $image image
*
* #return void
*/
public function setImage(\TYPO3\CMS\Extbase\Persistence\ObjectStorage $image)
{
$this->image = $image;
}
}
Your ext_typoscript_setup.txt like this:
config.tx_extbase{
persistence{
classes{
In2code\Femanager\Domain\Model\User {
subclasses {
0 = vendorname\extname\Domain\Model\User
}
}
vendorname\extname\Domain\Model\User {
mapping {
tableName = fe_users
recordType = 0
}
}
}
}
}
Follow below steps for Extend FE USERS.
Updated answers
Just Update your model file User.php Like below
/**
* #var \TYPO3\CMS\Extbase\Domain\Model\FileReference
*/
protected $backgroundimage = null;
Create ext_tables.sql
CREATE TABLE fe_users (
imsge int(11) unsigned NOT NULL default '0',
);
Add TCA Configuration for image fields in ext_tables.php file
$tempColumns = Array (
'image' => array(
'exclude' => 1,
'label' => 'Add image Lables',
'config' => \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::getFileFieldTCAConfig(
'image',
array(
'appearance' => array(
'createNewRelationLinkTitle' => 'LLL:EXT:cms/locallang_ttc.xlf:images.addFileReference'
),
'foreign_types' => array(
'0' => array(
'showitem' => '
--palette--;LLL:EXT:lang/locallang_tca.xlf:sys_file_reference.imageoverlayPalette;imageoverlayPalette,
--palette--;;filePalette'
),
\TYPO3\CMS\Core\Resource\File::FILETYPE_TEXT => array(
'showitem' => '
--palette--;LLL:EXT:lang/locallang_tca.xlf:sys_file_reference.imageoverlayPalette;imageoverlayPalette,
--palette--;;filePalette'
),
\TYPO3\CMS\Core\Resource\File::FILETYPE_IMAGE => array(
'showitem' => '
--palette--;LLL:EXT:lang/locallang_tca.xlf:sys_file_reference.imageoverlayPalette;imageoverlayPalette,
--palette--;;filePalette'
),
\TYPO3\CMS\Core\Resource\File::FILETYPE_AUDIO => array(
'showitem' => '
--palette--;LLL:EXT:lang/locallang_tca.xlf:sys_file_reference.imageoverlayPalette;imageoverlayPalette,
--palette--;;filePalette'
),
\TYPO3\CMS\Core\Resource\File::FILETYPE_VIDEO => array(
'showitem' => '
--palette--;LLL:EXT:lang/locallang_tca.xlf:sys_file_reference.imageoverlayPalette;imageoverlayPalette,
--palette--;;filePalette'
),
\TYPO3\CMS\Core\Resource\File::FILETYPE_APPLICATION => array(
'showitem' => '
--palette--;LLL:EXT:lang/locallang_tca.xlf:sys_file_reference.imageoverlayPalette;imageoverlayPalette,
--palette--;;filePalette'
)
),
'maxitems' => 1
),
$GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext']
),
'pdf,doc,docx'
),
),
);
\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addTCAcolumns("fe_users",$tempColumns,1);
\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addToAllTCAtypes("fe_users","image");
Mapping image fields with fe_user tables. ext_typoscript_setup.txt
config.tx_extbase{
persistence{
classes{
TYPO3\CMS\Extbase\Domain\Model\FrontendUser {
subclasses {
Tx_Extendfeuser_User = VendorName\ExtensionName\Domain\Model\User
}
}
VendorName\ExtensionName\Domain\Model\User {
mapping {
tableName = fe_users
recordType = 0
}
}
}
}
}
Create Model fiel User.php
<?php
namespace VendorName\ExtensionName\Domain\Model;
/***************************************************************
*
* Copyright notice
*
* (c) 2015
*
* All rights reserved
*
* This script is part of the TYPO3 project. The TYPO3 project is
* free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* The GNU General Public License can be found at
* http://www.gnu.org/copyleft/gpl.html.
*
* This script is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/
/**
* Users
*/
class User extends \TYPO3\CMS\Extbase\DomainObject\AbstractEntity {
/**
* image
*
* #var \TYPO3\CMS\Extbase\Domain\Model\FileReference
*/
protected $image = null;
/**
* Returns the image
*
* #return \TYPO3\CMS\Extbase\Domain\Model\FileReference $image
*/
public function getImage()
{
return $this->image;
}
/**
* Sets the image
*
* #param \TYPO3\CMS\Extbase\Domain\Model\FileReference $image image
*
* #return void
*/
public function setImage(\TYPO3\CMS\Extbase\Domain\Model\FileReference $image)
{
$this->image = $image;
}
}
Also If you want extend Fe user With FE Manager extension then follow the link Extend Fe Users

Adding custom column to customer_entity

I am trying to add an custom column to customer_entity, which should be editable in customer form in backend.
I am able to add the column to the database table via an UpdateSchema Script in my Module.
But how can I populate it in the customer form and in the grid?
What I tried so far:
I added an attribute with the same name (=column name) with UpdateDataScript, $customerSetup->addAttribute()...
Customer_grid_flat is updated correctly on saving the user, but the value in the table customer_entity didn't get changed. It is saving its values inside the attribute table (customer_entity_varchar).
How can I set up the custom column correctly, so that its value is saved inside 'customer_entity' and not in 'customer_entity_varchar'?
Solution:
My custom attribute now gets properly saved inside customer_entity table.
UpgradeSchema.php
<?php
namespace Custom\MyModule\Setup;
use Magento\Framework\Setup\UpgradeSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
class UpgradeSchema implements UpgradeSchemaInterface
{
const CUSTOM_ATTRIBUTE_ID = 'custom_attribute';
/**
* #param SchemaSetupInterface $setup
* #param ModuleContextInterface $context
*/
public function upgrade(SchemaSetupInterface $setup, ModuleContextInterface $context)
{
$setup->startSetup();
if (version_compare($context->getVersion(), '0.0.3', '<')) {
$setup->getConnection()->addColumn(
$setup->getTable('customer_entity'),
self::CUSTOM_ATTRIBUTE_ID,
[
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'nullable' => true,
'default' => null,
'comment' => 'Custom Attribute'
]
);
}
$setup->endSetup();
}
}
UpgradeData.php
<?php
namespace Custom\MyModule\Setup;
use Magento\Customer\Model\Customer;
use Magento\Customer\Setup\CustomerSetupFactory;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Indexer\IndexerRegistry;
use Magento\Framework\Setup\UpgradeDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\TestFramework\Helper\Eav;
class UpgradeData implements UpgradeDataInterface
{
/**
* #var CustomerSetupFactory
*/
private $customerSetupFactory;
/**
* #var IndexerRegistry
*/
protected $indexerRegistry;
/**
* #var \Magento\Eav\Model\Config
*/
protected $eavConfig;
/**
* #var \Magento\Eav\Model\Setup
*/
protected $eavSetupFactory;
/**
* #param CustomerSetupFactory $customerSetupFactory
* #param IndexerRegistry $indexerRegistry
* #param \Magento\Eav\Model\Config $eavConfig
*/
public function __construct(
CustomerSetupFactory $customerSetupFactory,
IndexerRegistry $indexerRegistry,
\Magento\Eav\Model\Config $eavConfig,
EavSetupFactory $eavSetupFactory
)
{
$this->customerSetupFactory = $customerSetupFactory;
$this->indexerRegistry = $indexerRegistry;
$this->eavConfig = $eavConfig;
$this->eavSetupFactory = $eavSetupFactory;
}
/**
* Upgrades data for a module
*
* #param ModuleDataSetupInterface $setup
* #param ModuleContextInterface $context
* #return void
*/
public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
$dbVersion = $context->getVersion();
if (version_compare($dbVersion, '0.0.3', '<')) {
$customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);
$customerSetup->addAttribute(
'customer',
UpgradeSchema::CUSTOM_ATTRIBUTE_CODE,
[
'label' => 'Custom Attribute',
'required' => 0,
'visible' => 1, //<-- important, to display the attribute in customer edit
'input' => 'text',
'type' => 'static',
'system' => 0, // <-- important, to have the value be saved
'position' => 40,
'sort_order' => 40
]
);
/** #var EavSetupFactory $eavSetup */
$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
$typeId = $eavSetup->getEntityTypeId('customer');
$attribute = $eavSetup->getAttribute($typeId, UpgradeSchema::CUSTOM_ATTRIBUTE_ID);
$customerSetup->getSetup()->getConnection()->insertMultiple(
$customerSetup->getSetup()->getTable('customer_form_attribute'),
array('form_code' => 'adminhtml_customer', 'attribute_id' => $attribute['attribute_id'])
);
$setup->endSetup();
}
}
}

ZF2 How to set <input type='radio' CHECKED> with a custom Form Element

How do I set checked within a form input radio field? This form field is added using a custom Form Element. The value of this field isn't consistent.
My custom Form Element returns 1 element. It is a radio input field. I need this checked each and every time the form is submitted. The reason I am using this instead of a "hidden" field is for the user to see this settings.
This is the custom Form Element
namespace Member\Form\Element;
use Doctrine\ORM\EntityManager;
use Zend\Form\Element\Radio;
/**
* Class OriginalLanguageIsoRadio
*
* #package Member\Form\Element
*/
class OriginalLanguageIsoRadio extends Radio
{
/**
* #var EntityManager $entityManager
*/
protected $entityManager;
/**
* #var string $translationKey
*/
protected $translationKey;
/**
* #var string $textDomain
*/
protected $textDomain;
/**
* #param EntityManager $entityManager
* #param string $translationKey
* #param string $textDomain
*/
public function __construct(
EntityManager $entityManager,
$translationKey,
$textDomain
)
{
$this->entityManager = $entityManager;
$this->translationKey = $translationKey;
$this->textDomain = $textDomain;
}
/**
* Get Value Options
*
* #return array
*
* #throws \Exception
*/
public function getValueOptions()
{
$array = [];
$query = $this->entityManager
->createQueryBuilder()
->from(
'AMDatabase\Entity\TheVerse\TranslationsMasters',
't'
)
->select('t.languageIso')
->setMaxResults(1);
$result = $query->getQuery()
->getArrayResult();
if (is_array($result) && count($result) > '0') {
foreach ($result AS $value) {
if ( $value['languageIso'] == '' ) {
$array['Global'] = $value['Global'];
} else {
$array[$value['languageIso']] = $value['languageIso'];
}
}
}
return $array;
}
}
Then I call the custom Form Element:
/**
* Original Language Iso
*/
$this->add(
[
'type' => 'Member\Form\Element\OriginalLanguageIsoRadio',
'name' => 'original_language_iso',
'options' => [
'label' => 'original_language_iso'
],
'attributes' => [
'id' => 'original_language_iso',
]
]
);
This adds the following to my form:
<input type="radio" name="original_language_iso" id="original_language_iso" value="en-US">
My desired output is
<input type="radio" name="original_language_iso" id="original_language_iso" value="en-US" **checked**>
You have two options:
a) Backend:
The attributes array must contain a 'value' set to the only element of the values available, that's the way to auto-check the radio input. With your example, it would be:
$this->add(
[
'type' => 'Member\Form\Element\OriginalLanguageIsoRadio',
'name' => 'original_language_iso',
'options' => [
'label' => 'original_language_iso'
],
'attributes' => [
'id' => 'original_language_iso',
'value'=>'something_here'
]
]
);
b) Front:
Use jQuery to check the radio input. You may do it with:
jQuery('#original_language_iso').attr('checked','checked');

Symfony 2 GenemuFormBundle how to create a jQuery Select2 with Ajax

I'm trying to add a Select2 input using the GenemuFormBundle as described in the "Use jQuery Select2 with Ajax" doc. Adding a jQuery Select2 Field following the jQuery Select2 Field documentation works just fine.
But the documentation on how to implement an Ajax-loading Select2 form is very inconclusive. If I unterstand the doc correctly, it aims to create the same as mentioned in the Select2 documentation. This is exactly the thing I'd like to create. I added hidden field as well as the required JavaScript, but the only thing that I get is a Variable "id" does not exist in xBundle:x:new.html.twig at line x.
Form builder (taken directly form the mentioned doc):
...
->add('field_name', 'genemu_jqueryselect2_hidden', array(
'configs' => array(
'multiple' => true // Wether or not multiple values are allowed (default to false)
)
))
->add('field_name', 'genemu_jqueryselect2_entity', array(
'class' => 'xBundle:Entity',
'property' => 'foo',
))
View (also taken directly form the doc):
{% block stylesheets %}
{{ form_stylesheet(form) }}
{% endblock %}
{% block javascript %}
{{ form_javascript(form) }}
{% endblock %}
{% block genemu_jqueryselect2_javascript %}
<script type="text/javascript">
$field = $('#{{ id }}');
var $configs = {{ configs|json_encode|raw }};
// custom configs
$configs = $.extend($configs, {
query: function (query) {
var data = {results: []}, i, j, s;
for (i = 1; i < 5; i++) {
s = "";
for (j = 0; j < i; j++) {s = s + query.term;}
data.results.push({id: query.term + i, text: s});
}
query.callback(data);
}
});
// end of custom configs
$field.select2($configs);
</script>
{% endblock %}
I just struggled with this exact issue and thought I would throw in my own findings for anyone that happens to stumble across this. I did find a solution, but I would probably still recommend just going with the ZenStruckFormBundle recommended by Doug because it seems to actually be designed to work as a solution for a select2 field type that loads via ajax and relates back to an entity.
The real reason this doesn't work is that the the genemu_jqueryselect2_* types for the GenemuFormBundle do not implement a data transformer that will work with an entity when you need an ajax-loading select2 field. It doesn't seem like it was ever designed to work this way. When you use the genemu_jqueryselect2_hidden type and have the “multiple’ config option set to true, then it adds an ArrayToStringTransformer. This will not work with an entity.
To fix this you need to make a new form field type and define that its parent is genemu_jqueryselect2_hidden then make a few customizations. It would look something like this…
namespace Acme\DemoBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Acme\DemoBundle\Form\DataTransformer\EntityCollectionToIdTransformer;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class EntityCollectionSelectorType extends AbstractType
{
/**
* #var ObjectManager
*/
protected $om;
/**
* #param ObjectManager $om
*/
public function __construct(ObjectManager $om)
{
$this->om = $om;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$transformer = new EntityCollectionToIdTransformer($this->om, $options['configs']['entity']);
$builder->resetViewTransformers();
$builder->addModelTransformer($transformer);
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'invalid_message' => 'The selected entity does not exist',
'required' => true,
'auto_initialize' => false,
'configs' => array('multiple' => true),
'error_bubbling' => false,
));
}
public function getParent()
{
return 'genemu_jqueryselect2_hidden';
}
public function getName()
{
return 'entity_collection_selector';
}
}
Then you will also need to add the new data transformer used in the above form field type, so that it can translate the values between the form field and the entity…
namespace Acme\DemoBundle\Form\DataTransformer;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;
use Doctrine\ORM\PersistentCollection;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\Collections\ArrayCollection;
class EntityCollectionToIdTransformer implements DataTransformerInterface
{
/**
* #var ObjectManager
*/
private $om;
/**
* #var string The Doctrine entity type to use
*/
private $entityType;
/**
* #param ObjectManager $om
*/
public function __construct(ObjectManager $om, $entityType)
{
$this->om = $om;
$this->entityType = $entityType;
}
/**
* Transforms a collection of entities to a comma separated string
*
* #param ArrayCollection $entities
* #return string
*/
public function transform($entities)
{
if (null == $entities || empty($entities)) {
return '';
}
$results = '';
foreach ($entities as $entity) {
$results .= $entity->getId() . ',';
}
$results = trim($results, ' ,');
return $results;
}
/**
* Transforms a string of comma separated IDs to a PersistentCollection for Doctrine
*
* #param string $values
* #return PersistentCollection|ArrayCollection
* #throws TransformationFailedException if entity is not found.
*/
public function reverseTransform($values)
{
if (!$values) {
return new ArrayCollection();
}
$values = explode(',', $values);
$collection = array();
foreach ($values as $id) {
$item = $this->om->getRepository($this->entityType)->findOneById($id);
if (!is_null($item)) {
$collection[] = $item;
}
else {
throw new TransformationFailedException(sprintf(
'An entity with ID "%s" does not exist!',
$value
));
}
}
return new PersistentCollection($this->om, $this->entityType, new ArrayCollection($collection));
}
}
Now make sure you define your new field type in your config for your services…
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
<parameters>
...
<parameter key="acme_demo.form.type.entity_collection_selector.class">Acme\DemoBundle\Form\Type\EntityCollectionSelectorType</parameter>
...
</parameters>
<services>
...
<service id="acme_demo.form.type.entity_collection_selector"
class="%acme_demo.form.type.entity_collection_selector.class%">
<argument type="service" id="doctrine.orm.default_entity_manager" />
<tag name="form.type" alias="entity_collection_selector" />
</service>
...
</services>
</container>
Now you can use it as such…
$builder->add('customers', 'entity_collection_selector', array(
'configs' => array('entity' => 'AcmeDemoBundle:Customer')
));