Reputation: 2810
I'm trying to create a form like this to manage permissions.
twitter sms email readonwebsite
user0 yes no yes yes
user1 no yes no yes
user2 no no no yes
user3 yes yes yes yes
The current way I'm doing this is using a foreach loop for each subuser and adding this directly to the form
$form = $form->add($subUser->getId() . '_twitter', 'checkbox', array
(
'label' => 'twitter',
'required' => false,
'mapped' => false,
'data' => (bool)//original checkbox value derived from db value
));
and repeated code for sms
, email
, and read
permissions. This doesn't seem very elegant. In the form processing, I would have to deal with keys like 1337_twitter
and 69_sms
. Is there a way that I can process the form like $form[$subUser->getId()]['twitter']
?
Upvotes: 0
Views: 158
Reputation: 2893
I'm assuming you're using Doctrine because you haven't specified which ORM you're using.
Do you have a Permission
object? If you create a relationship between permissions and users that would be a lot cleaner. You could add permissions
to your user form and it would be easy to manage.
So your permissions table would contain a record for 'twitter', 'sms', 'email', 'readonwebsite'.
You could set up your entities and form like below:
e.g.
// src/PathTo/YourBundle/Entity/Permission.php
class Permission
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\Column(type="string", length=255, nullable=false)
*/
private $name; // e.g. 'twitter' or 'email'
/**
* @ORM\ManyToMany(targetEntity="User", mappedBy="permissions")
*/
private $users;
}
// src/PathTo/YourBundle/Entity/User.php
class User
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\ManyToMany(targetEntity="Permssion")
* @ORM\JoinTable(name="user_permission",
* joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="permission_id", referencedColumnName="id")}
* )
*/
private $permissions;
}
// src/PathTo/YourBundle/Form/Type/UserFormType.php
class UserFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
// Add more fields
->add('permissions', null, array(
'expanded' => true, // Creates checkboxes
))
;
}
// ...
}
Then in your controller
// src/PathTo/YourBundle/Controller/UserContoller.php
public function editAction($id, Request $request)
{
// ...
// Get your user object
$form = $this->createForm(new UserFormType(), $user);
$form->handleRequest($request);
if ($form->isValid())
$em->persist($user);
$em->flush();
// redirect back to some edit page
// ...
}
// render some form template
// ...
}
It's that simple :)
Upvotes: 1