ZendFramework2 AbstractTableGateway getSql - zend-framework2

I got a ZF2 project with 2 Models PosTable/TopTable which extend AbstractTableGateway.
I want to Paginate results from those Tables so i have a Pagination function in both of them.
this is what the PosTable Model looks like:
...
class PosTable extends AbstractTableGateway {
public function __construct($adapter) {
$this->table = 'pos';
$this->adapter = $adapter;
}
...
public function getPosPaginator($tid) {
$sql = $this->getSql();
$select = $sql->select();
$select->where('tid = '.$tid)->where('deleted = 0')->order('crdate ASC');
$adapter = new \Zend\Paginator\Adapter\DbSelect($select, $sql);
$paginator = new \Zend\Paginator\Paginator($adapter);
return $paginator;
}
...
which works perfectly.
but in my TopTable it looks the same like this:
...
class TopTable extends AbstractTableGateway {
public function __construct($adapter) {
$this->table = 'top';
$this->adapter = $adapter;
}
public function getTopPaginator($fid) {
$sql = $this->getSql();
$select = $sql->select();
$select->where('fid = '.$fid)->where('deleted = 0');
$adapter = new \Zend\Paginator\Adapter\DbSelect($select, $sql);
$paginator = new \Zend\Paginator\Paginator($adapter);
return $paginator;
}
...
my controller looks like this for PosTable:
...
public function posAction(){
...
$pos = $this->getPosTable()->getPosPaginator($tid);
$pos->setCurrentPageNumber($pageid)->setItemCountPerPage(19);
... return $pos etc...
same controller topAction:
...
public function topAction(){
...
$top = $this->getTopTable()->getTopPaginator($fid);
$top->setCurrentPageNumber($pageid)->setItemCountPerPage(20);
...return $top etc..
in that controller i got also these functions:
public function getTopTable(){
return $this->getServiceLocator()->get('Application\Model\TopTable');
}
public function getPosTable(){
return $this->getServiceLocator()->get('Application\Model\PosTable');
}
PosTable Pagination works perfectly, but the TopTable Pagination doesnt work.
i get this error:
Fatal error: Call to a member function select() on a non-object in ....
seems like
$sql = $this->getSql();
doesnt return the object.
how can i solve this problem?
one works one doesnt for no obvious reason.
my module.php looks like this:
namespace Application;
class Module
{
public function getAutoloaderConfig()
{
return array('Zend\Loader\StandardAutoloader' =>
array('namespaces' =>
array(__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,),
),
);
}
public function getConfig()
{
return include __DIR__ . '/config/module.config.php';
}
public function getServiceConfig()
{
return array(
'factories' => array(
'Application\Model\TopTable' => function($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$table = new \Application\Model\TopTable($dbAdapter);
return $table;
},
'Application\Model\ForTable' => function($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$table = new \Application\Model\ForTable($dbAdapter);
return $table;
},
'Application\Model\PosTable' => function($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$table = new \Application\Model\PosTable($dbAdapter);
return $table;
},
),
);
}
}

Ok, after going through TableGateway Code and your extended class, I found the your implementation is not calling initialize which setup the sql object try to call the parent table gateway, below is the modified constructor for your PosTable and TopTable
/* for PosTable */
class PosTable extends TableGateway {
public function __construct($adapter) {
parent::__construct('pos', $adapter);
}
...
/* for TopTable */
class TopTable extends TableGateway {
public function __construct($adapter) {
parent::__construct('top', $adapter);
}
...

Related

How to include EntityManager in ZendFramework 2 AbstractValidator

I have a custom validator, extending Zend AbstractValidator. The thing is, i want to include Doctrine EntityManager, but i keep failing! I tried to make a Factory for my Validator, but it doesn't seem to work. Help!! What am I doing wrong?
Validator:
$this->objectRepository stays empty, while i expect content.
namespace Rentals\Validator;
use Rentals\Response;
use Zend\Validator\AbstractValidator;
use Zend\Stdlib\ArrayUtils;
class ExistentialQuantification extends AbstractValidator
{
const NO_ENTITY_ID = 'noEntityId';
const ENTITY_NOT_FOUND = 'entityNotFound';
const INVALID_ID = 'invalidId';
protected $messageTemplates = [
self::NO_ENTITY_ID => 'The input does not contain an entity id.',
self::ENTITY_NOT_FOUND => 'The entity could not be found.',
self::INVALID_ID => 'The input does not contain an entity id.',
];
protected $objectRepository;
public function __construct(array $options)
{
$this->objectRepository = $options['object_repository'];
parent::__construct($options);
}
public function isValid($value)
{
if ($value === null) {
return true;
}
if (! isset($value->id)) {
$this->error(self::NO_ENTITY_ID);
return false;
}
$entityClass = $this->getOption('entity_class');
$controller = new Controller();
$entity = (new FactoryInterface)(EntityManager::class)->find($entityClass, $entity->id);
if (! $entity instanceof $entityClass) {
$this->error(self::ENTITY_NOT_FOUND);
return false;
}
if (! $entity->getId()) {
$this->error(self::NO_ENTITY_ID);
return false;
}
return true;
}
}
Factory:
namespace Rentals\Validator;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\MutableCreationOptionsInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\Stdlib\ArrayUtils;
class ExistentialQuantificationFactory implements FactoryInterface, MutableCreationOptionsInterface
{
protected $options = [];
public function setCreationOptions(array $options)
{
$this->options = $options;
}
public function createService(ServiceLocatorInterface $serviceLocator)
{
if (! isset($this->options['object_manager'])) {
$this->options['object_manager'] = 'doctrine.entitymanager.orm_default';
}
$objectManager = $serviceLocator->get($this->options['object_manager']);
$objectRepository = $objectManager->getRepository($this->options['entity_class']);
return new ExistentialQuantification(ArrayUtils::merge(
$this->options, [
'objectManager' => $objectManager,
'objectRepository' => $objectRepository
]
));
}
}
Module config:
<?php
return [
'service_manager' => [
'factories' => [
'Rentals\\Validator\\ExistentialQuantification' => 'Rentals\\Validator\\ExistentialQuantificationFactory'
]
]
];
?>
What if you change your config entry like the following example?
return [
'validators' => [
'factories' => [
ExistentialQuantification::class => ExistentialQuantificationFactory::class,
],
],
];
This change will result in further changes for your factory, because the service locator for the entity manager differs from the one you injected.
namespace Application\Validator\Factory;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\MutableCreationOptionsInterface;
use Zend\ServiceManager\MutableCreationOptionsTrait;
use Zend\ServiceManager\ServiceLocatorInterface;
class ExistentialQuantificationFactory implements FactoryInterface, MutableCreationOptionsInterface
{
use MutableCreatinOptionsTrait;
public function createService(ServiceLocatorInterface $serviceLocator)
{
$parentLocator = $serviceLocator->getServiceLocator();
if (! isset($this->creationOptions['object_manager'])) {
$this->creationOptions['object_manager'] = 'doctrine.entitymanager.orm_default';
}
$objectManager = $parentLocator->get($this->creationOptions['object_manager']);
$objectRepository = $objectManager->getRepository($this->creationOptions['entity_class']);
return new ExistentialQuantification(ArrayUtils::merge(
$this->options, [
'objectManager' => $objectManager,
'objectRepository' => $objectRepository
]
));
}
}
What I 've done here? First I implemented the MutableCreationOptionsTrait class. This trait implements the needed functions for working with creation options. But this is just a little hint for avoiding unnecessary work.
Because of setting the validator class as validator in the config, we have to use the parent service locator for getting the entity manager. The inherited service locator just provides access to validators.
Now you can try to access your validator in your controller like in the following examaple.
$validator = $this->getServiceLocator()
->get('ValidatorManager')
->get(ExistentialQuantification::class, [
'entity_class' => YourEntityClass::class,
]);
\Zend\Debug\Debug::dump($validator, __METHOD__);
The validator manager should return your validator so that you can test it.

How to implement acl and authorization in Module.php in zf3

I am working on Album Application in zf3.I added acl functionality to the application like this:
AlbumController.php
class AlbumController extends AbstractActionController
{
protected $role;
public function onDispatch(\Zend\Mvc\MvcEvent $e)
{
$userSession = new Container('user');
if (!isset($userSession->email)) {
return $this->redirect()->toRoute('login');
}
else {
$this->role = $userSession->role;
parent::onDispatch($e);
}
}
public function checkPermission($role,$action)
{
if($role == 'admin'){
$acl = new Acl();
if ($acl->isAllowed('admin', 'AlbumController', $action)) {
return true;
}
}
return false;
}
public function editAction()
{
$action = 'edit';
$permission = $this->checkPermission($this->role,$action);
if (!$permission) {
$this->flashMessenger()->addMessage('<div class="alert alert- danger" role="alert"><b>You dont have the privilege to edit!!</b></div>');
return $this->redirect()->toRoute('album');
}
$id = (int) $this->params()->fromRoute('id', 0);
if (0 === $id) {
return $this->redirect()->toRoute('album', ['action' => 'add']);
}
try {
$album = $this->table->getAlbum($id);
} catch (\Exception $e) {
return $this->redirect()->toRoute('album', ['action' => 'index']);
}
$form = new AlbumForm();
$form->bind($album);
$form->get('submit')->setAttribute('value', 'Edit');
$request = $this->getRequest();
$viewData = ['id' => $id, 'form' => $form];
if (! $request->isPost()) {
return $viewData;
}
$form->setInputFilter($album->getInputFilter());
$form->setData($request->getPost());
$edit = $request->getPost('submit', 'Cancel');
if($edit == 'Cancel'){
$this->flashMessenger()->addMessage('<div class="alert alert-danger" role="alert"><b>Cancelled by User...!!</b></div>');
return $this->redirect()->toRoute('album');
}
if (! $form->isValid()) {
$this->flashMessenger()->addMessage('<div class="alert alert-danger" role="alert"><b>Failed to Update...!!</b></div>');
return $viewData;
}else{
$this->table->saveAlbum($album);
$this->flashMessenger()->addMessage('<div class="alert alert-success" role="alert"><b>Record Updated Successfully...!!</b></div>');
}
// Redirect to album list
return $this->redirect()->toRoute('album', ['action' => 'index']);
}
}
This is working perfectly fine,now i want to move the onDispatch function to Module.php but don't know how to implement it.Can someone please help me
Module.php
<?php
namespace Album;
use Album\Controller\AlbumController;
use Album\Model\Album;
use Album\Model\AlbumTable;
use Zend\Db\Adapter\AdapterInterface;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
use Zend\ModuleManager\Feature\ConfigProviderInterface;
use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
use Album\Model\LoginTable;
class Module implements ConfigProviderInterface
{
public function getConfig()
{
return include __DIR__ . '/../config/module.config.php';
}
public function getServiceConfig()
{
return [
'factories' => [
AlbumTable::class => function($container) {
$tableGateway = $container->get(Model\AlbumTableGateway::class);
return new AlbumTable($tableGateway);
},
Model\AlbumTableGateway::class => function ($container) {
$dbAdapter = $container->get(AdapterInterface::class);
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Album());
return new TableGateway('album', $dbAdapter, null, $resultSetPrototype);
},
Model\LoginTable::class => function($container) {
$tableGateway = $container->get(Model\LoginTableGateway::class);
$table = new LoginTable($tableGateway);
return $table;
},
Model\LoginTableGateway::class => function ($container){
$dbAdapter = $container->get(AdapterInterface::class);
$resultSetPrototype = new ResultSet();
return new TableGateway('login', $dbAdapter, null, $resultSetPrototype);
}
],
];
}
public function getControllerConfig()
{
return [
'factories' => [
Controller\AlbumController::class => function($container) {
return new Controller\AlbumController($container->get(Model\AlbumTable::class));
},
Controller\LoginController::class => function($container) {
return new Controller\LoginController($container->get(Model\LoginTable::class));
},
Controller\LogoutController::class => function($container){
return new Controller\LogoutController($container->get(Model\LoginTable::class));
},
],
];
}
}
This is how I implemented it. In your Module.php, add a listener on EVENT_DISPATCH, with a closure as callback that will call your middleware class authorization :
class Module implements ConfigProviderInterface
{
public function getConfig()
{
return include __DIR__ . '/../config/module.config.php';
}
public function onBootstrap(MvcEvent $e)
{
$app = $e->getApplication();
$eventManager = $app->getEventManager();
$serviceManager = $app->getServiceManager();
// Register closure on event DISPATCH, call your checkProtectedRoutes() method
$eventManager->attach(MvcEvent::EVENT_DISPATCH, function (MvcEvent $e) use ($serviceManager) {
$match = $e->getRouteMatch();
$auth = $serviceManager->get(Middleware\AuthorizationMiddleware::class);
$res = $auth->checkProtectedRoutes($match);
if ($res instanceof Response) {
return $res;
}
}, 1);
// Init ACL : could be improved
$this->initAcl($e);
}
You should have an AuthorizationMiddlewareFactory (call it as you want):
<?php
namespace MyModule\Factory;
use Interop\Container\ContainerInterface;
use MyModule\Middleware\AuthorizationMiddleware;
use Zend\Authentication\AuthenticationService;
use Zend\ServiceManager\Factory\FactoryInterface;
class AuthorizationMiddlewareFactory implements FactoryInterface
{
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
$authService = $container->get(AuthenticationService::class);
$acl = $container->get('Acl'); // II init it in bootstrap(), could be improved
$response = $container->get('Response');
$baseUrl = $container->get('Request')->getBaseUrl();
$authorization = new AuthorizationMiddleware($authService, $acl, $response, $baseUrl);
return $authorization ;
}
}
And your AuthorizationMiddleware class:
<?php
namespace MyModule\Middleware;
use Symfony\Component\VarDumper\VarDumper;
use Zend\Authentication\AuthenticationService;
use Zend\Http\PhpEnvironment\Response;
use Zend\Permissions\Acl\Acl;
use Zend\Router\RouteMatch;
class AuthorizationMiddleware
{
private $authService ;
private $acl;
private $response;
private $baseUrl;
/**
* AuthorizationMiddleware constructor.
* #param AuthenticationService $authService
* #param Acl $acl
* #param Response $response
* #param $baseUrl
*/
public function __construct(AuthenticationService $authService, Acl $acl, Response $response, $baseUrl)
{
$this->authService = $authService;
$this->acl = $acl;
$this->response = $response;
$this->baseUrl = $baseUrl;
}
public function checkProtectedRoutes(RouteMatch $match)
{
if (! $match) {
// Nothing without a route
return null ;
}
// Do your checks...
}
It can be improved, but you have the idea... See also this Question and the answers: ZF3 redirection after ACL authorization failed

Can't get bind() to work

I want my form fields to contain the previous data contained in database when the form page opens. I went through lots of queries here and came to know using populate() or bind() method is the way to do it. But when I try to use it, I get an undefined method error.
Is there any other way to do it?
I am unable to use bind() as well. I am getting a fresh form with default values after I submit.
Sorry if this is a stupid question. Its been only 4-5 days since I started learning Zend framework. Also, most of the methods I get online are for older frameworks. I am using Zend Framework2.
This is Controller Code
<?php
class ChatController extends AbstractActionController
{
protected $chatTable;
public function indexAction()
{
$form = new ChatForm();
$model= new Chat();
$form->bind($model);
$form->get('submit')->setValue('Save');
$request = $this->getRequest();
if ($request->isPost()) {
$gen_set = new Chat();
$form->setInputFilter($gen_set->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$gen_set->exchangeArray($form->getData());
$this->getChatTable()->saveChat($gen_set);
// Redirect to list of albums
return $this->redirect()->toRoute('chat');
}
}
return array('form' => $form);
}
public function getChatTable()
{
if (!$this->chatTable) {
$sm = $this->getServiceLocator();
$this->chatTable = $sm->get('Chat\Model\ChatTable');
}
return $this->chatTable;
}
}
My Entity Class, Here api_key and anon_prefix are rows of the column 'settings' and there is one more column with value.
<?php
class Chat implements InputFilterAwareInterface
{
protected $inputFilter;
public function exchangeArray($data)
{
$this->api_key=(isset($data['api_key'])) ? $data['api_key'] : null;
$this->anon_prefix = (isset($data['anon_prefix'])) ? $data['anon_prefix'] : null;
}
// Add content to these methods:
public function setInputFilter(InputFilterInterface $inputFilter)
{
throw new \Exception("Not used");
}
public function getInputFilter()
{
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
$inputFilter->add(array(
'name' => 'iflychat_external_api_key',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
));
$inputFilter->add(array(
'name' => 'iflychat_show_admin_list',
'required' => true,
'validators' => array(
array(
'name' => 'InArray',
'options' => array(
'haystack' => array(1,2),
),
),
),
));
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
public function getArrayCopy()
{
return get_object_vars($this);
}
}
This is used to enter values into db
<?php
class ChatTable
{
protected $tableGateway;
public function __construct(TableGateway $tableGateway)
{
$this->tableGateway = $tableGateway;
}
public function fetchAll()
{
$resultSet = $this->tableGateway->select();
return $resultSet;
}
public function saveChat(Chat $gen_set)
{
$data = array(
'value' => $gen_set->api_key,
);
$id='iflychat_external_api_key';
$this->tableGateway->update($data,array('settings' => $id));
$data = array(
'value' => $gen_set->anon_prefix,
);
$id='anon_prefix';
$this->tableGateway->update($data,array('settings' => $id));
}
}
I am getting this error, 'Cannot use object of type Chat\Model\Chat as array'
Your action doesn't make much sense as it is, you instantiate a Chat instance as $model and later another instance as $gen_set. What you should be doing is binding the first one, and using the form class getData method to later return the instance you bound to it, along with the values you gave it in the setData method. There's no need for any transformations from object to array and back again.
Here's how it should look ...
public function indexAction()
{
$form = new ChatForm();
// bind the model
$model= new Chat();
$form->bind($model);
$form->get('submit')->setValue('Save');
$request = $this->getRequest();
if ($request->isPost()) {
$form->setInputFilter($gen_set->getInputFilter());
// set data from POST as properties of the bound model ...
$form->setData($request->getPost());
if ($form->isValid()) {
// get the bound model instance with the POSTed values
// ($gen_set is now the original $model object instance bound above)
$gen_set = $form->getData();
// and save it
$this->getChatTable()->saveChat($gen_set);
// Redirect to list of albums
return $this->redirect()->toRoute('chat');
}
}
return array('form' => $form);
}
Controller Code -
<?php
class ChatController extends AbstractActionController {
protected $chatTable;
public function indexAction() {
$model = $this->getChatTable()->fetchLastChat();
if($model === null || $model->count() == 0)
$model = new Chat();
//Now if no record exists in the database then $model will be empty
//Else $model will contain data of last record.
$form = new ChatForm();
$form->bind($model);
$form->get('submit')->setValue('Save');
$request = $this->getRequest();
if ($request->isPost()) {
$gen_set = new Chat();
$form->setInputFilter($gen_set->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$gen_set->exchangeArray($form->getData());
$this->getChatTable()->saveChat($gen_set);
}
}
return array('form' => $form);
}
public function getChatTable() {
if (!$this->chatTable) {
$sm = $this->getServiceLocator();
$this->chatTable = $sm->get('Chat\Model\ChatTable');
}
return $this->chatTable;
}
}
ChatTable Class Code -
<?php
//Other use statements
use Zend\Db\Sql\Select;
class ChatTable {
protected $tableGateway;
public function __construct(TableGateway $tableGateway) {
$this->tableGateway = $tableGateway;
}
public function fetchAll() {
$resultSet = $this->tableGateway->select();
return $resultSet;
}
public function fetchLastChat() {
$select = new Select('TABLE_NAME'); //Change the tablename accordingly
$select->order('PRIMARY_KEY DESC'); //Set the Primary Key of the table
$select->limit(1);
$resultSet = $this->tableGateway->selectWith($select);
return $resultSet->current();
}
//Rest of the Code ....
Please take the idea from the above code.

ZF2 TableGateway doesn't works when insert a row

I've got a fatal error when I intent insert a row in DB. I don't understand what's happening, I readed some blogs but there is not a solution, my code is the same like an example publicated by Evan in his blog.
My model class
class CommentTable
{
protected $_commentTableGateway;
protected $_hydratator;
protected $_resultSet;
public function __construct($adapter)
{
$this->_hydratator = new \Zend\Stdlib\Hydrator\ClassMethods;
$rowObjectPrototype = new Comment();
$this->_resultSet = new \Zend\Db\ResultSet\HydratingResultSet($this->_hydratator, $rowObjectPrototype);
$this->_commentTableGateway = new TableGateway('comments', $adapter, null, $this->_resultSet );
}
public function fetchAll()
{
return $this->_commentTableGateway->select();
}
public function saveComment(Comment $comment)
{
$id = (int)$comment->getId();
if ($id == 0) {
$this->_commentTableGateway->insert($this->_hydratator->extract($comment));//this fails
} else {
if ($this->getComment($id)) {
$this->_commentTableGateway->update($data, array('id' => $id));
} else {
throw new \Exception('El comentario que queire editar no exite');
}
}
}
public function getComment($id)
{
$id = (int) $id;
$rowset = $this->_commentTableGateway->select(array('id' => $id));
$row = $rowset->current();
if (!$row) {
throw new \Exception("Could not find row $id");
}
return $row;
}
}
</code>
<code>
In module class:
//a factory in service manager
'Comment\Model\CommentTable' => function($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$table = new CommentTable($dbAdapter);
return $table;
},
</code>
<code>
My controller:
public function getCommentTable()
{
if (!$this->_commentTable) {
$sm = $this->getServiceLocator();
$this->_commentTable = $sm->get('Comment\Model\CommentTable');
}
return $this->_commentTable;
}
</code>
And I get this error:
Catchable fatal error: Object of class stdClass could not be converted to string in D:\xampp\htdocs\haystack\vendor\zendframework\zendframework\library\Zend\Db\Adapter\Driver\Pdo\Statement.php on line 258
I know the type of the error('stdClass could not be converted to string'), but I don't understand what's happening...
Any help is appreciated
Kind regards.
Hopefully this will help you out. Here is my TableGateway
class Domains extends AbstractTableGateway
{
public function __construct($adapter)
{
$this->table = 'domains';
$this->adapter = $adapter;
$this->initialize();
}
}
And here is how I insert data:
$this->getTableDomains()->insert(array(
'companyid' => $params['companyid'],
'domain_id' => $result->id,
'name' => $name,
'type' => strtoupper($params['type']),
'content' => strtolower($params['content']),
'ttl' => $ttl,
'prio' => $prio
));

Symfony form collection read-only for first entry

How can I set the read-only option only for the first item in the collection when rendering a form?
My simple models:
class Main
{
public $others;
}
class Other
{
public $field1;
public $field2;
}
Simple Form Type for my models:
class MainType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('others', 'collection', array(
'type' => new OtherType(),
'allow_delete' => true,
'allow_add' => true,
'by_reference' => false,
))
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'App\MyBundle\Entity\Main',
));
}
public function getName()
{
return 'maintype';
}
}
class OtherType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('field1')
->add('field2')
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'App\MyBundle\Entity\Other',
));
}
public function getName()
{
return 'othertype';
}
}
And simple action method my controller
//...
public function indexAction($id)
{
$main = new Main();
$other1 = new Other();
$other1->field1 = 'a';
$other1->field2 = 'b';
$main->others[] = $other;
$other2 = new Other();
$other2->field1 = 'c';
$other2->field1 = 'd';
$main->others[] = $other;
$form = $this->createForm(new MainType(), $main);
//...isValid, persist, flush...
}
//...
I can make a condition when manually render the form, but I want to know if possible at the form code to enter such a restriction.
Currently it is not possible to have the rows of a collection have different options. I invite you to create a feature request on the issue tracker if you feel that this would be a valuable addition.

Resources