How can I display the name of all services with specific tag in symfony2 form - forms

I have several services tagged with the same tag. I wonder how to proceed to retrieve the list of all thoses services and to inject it in a form ?
Here is an exemple of what I want at the end:
$builder->add('days', 'choice', array(
'choices' => $SERVICES,
'multiple' => false,
'expanded' => false,
))

The main idea is to define a service that will handle all tagged services of a certain type, and then within the compiler pass add tagged services to this service.
Taking example from the documentation on Working with Tagged Services, you may add a method that returns all services :
<?php
// ...
class TransportChain
{
// ...
/**
* #return array
*/
public function getTransports()
{
return $this->transports;
}
}
And then from anywhere you have access to the DIC, simply use :
// Get access to all services tagged with "acme_mailer.transport"
$transports = $this
->getContainer()
->get('acme_mailer.transport_chain')
->getTransports()
;
Of course you will have to tweak all this a bit in order to, perhaps, return strings instead of objects.

Related

Symfony Form Type - add options

In my project I have 3 entities; User, Module, and UserModule.
User has properties such as id, username, email along with a UserModules property that is a collection of UserModules.
Module has properties id, name and description.
Each UserModule object has properties User(reference to corresponding User), Module (reference to corresponding module) and Access (boolean for whether or not access is permitted)
My issue is I do not know how to use Symfony's Form types to show all the modules when creating a User.
I have a number of modules made already (i.e. 'admin', 'ticket', 'help'). In my UserType class my buildForm method looks like:
{
$builder
->add('username')
->add('email')
->add('modules', CollectionType::class, [
'entry_type' => UserModuleType::class,
'entry_options' => [
'label' => false
],
]);
}
my UserModuleType class is
{
$builder
->add('access', ChoiceType::class, [
'choices' => [
'No Access' => false,
'Full Access' => true,
]
]);
}
This shows the UserModules assigned to the User, but when creating a User, I want it to already have UserModules already added for each module.
How can I set this up so that the form will use all possible modules to create default UserModules?
I hope you will find some help here :
https://symfony.com/doc/current/form/form_collections.html
in the example : use tags as your modules
In this case, as you are only using true and false for defining if the user has access to a module, I would use the EntityType with the multiple attribute instead of the CollectionType.
This way you only set which modules have access.
Link to documentation

How to get choice options from another entity in Symfony

I want to load two choice list, the second one load only some values based on the first choice. But my problem comes first... how to load the EntityType values in the first list from a class that is not directly related to the current class (the form type class).
->add(
'cliente',
EntityType::class,
array(
'class' => 'AppBundle:Cliente',
'choice_label' => 'nombre',
)
)
But there is no one 'cliente' field in this entity, so it throws the message you know...
Neither the property "cliente" nor one of the methods "getCliente()",
"cliente()", "isCliente()", "hasCliente()", "__get()" exist and have
public access in class "AppBundle\Entity\Envio".
Please, do you know how to solve this issue? Any help is welcome!
According to your error your form is for the entity Envio. If you want to create an EntityType choicelist based on the Cliente entity, you'll need a doctrine relation in your Envio class:
class Envio
{
/*
* #ORM\ManyToOne(targetEntity="Cliente")
*/
protected $cliente;
The error has no relation to your question about having 2 choicelists and changing the choices of your second list based on the first choice. You're probably best off using javascript for that and you'll have many choices from AJAX to limiting the choices on the fly depending on the value or innerText of the .
For that error you need to make the field as 'mapped' => false, so:
->add(
'cliente',
EntityType::class,
array(
'class' => 'AppBundle:Cliente',
'choice_label' => 'nombre',
'mapped' => false
)
)
Then for getting the property in the controller you must do:
$cliente = $form->get('cliente')->getData();
Hope this help you.

multiple instances of view helper plugin?

How do I instantiate multiple instances of a view helper plugin in Zend 2?
I want to return a new instance every time I call $this->pluginName(); from the view.
How do I return a new instance of the view plugin?
Add the service name to the getViewHelperConfig() shared configuration key in Module.php and set this value to false
Module.php
function getViewHelperConfig()
{
return array(
'shared' => array(
'MyViewHelper' => false,
),
'factories' => array(
'MyViewHelper' => 'App\View\Helper\MyViewHelperFactory',
)
);
}
By adding 'MyViewHelper' => false, the service manager (or View Helper plugin manager) will create a new instance of that service each time it is used.
The documentation states
shared An array of service name/boolean pairs, indicating whether or not a service should be shared. By default, the ServiceManager assumes all services are shared, but you may specify a boolean false value here to indicate a new instance should be returned.

zf2 restful not reach update method

I made a restful controller that if I send the id the get method receives it. But when I update a form I expect the update method to process but I cant get to the right config for this and after 1 day with this issue I decided to right it down here.
Here the code involved
route in module config:
'activities' => array(
'type' => 'segment',
'options' => array(
'route' => '/activities[/:id][/:action][.:formatter]',
'defaults' => array(
'controller' => 'activities'
),
'constraints' => array(
'formatter' => '[a-zA-Z0-9_-]*',
'id' => '[0-9_-]*'
),
),
),
Head of controller:
namespace Clock\Controller;
use Zend\Mvc\Controller\AbstractRestfulController;
use Zend\Mvc\MvcEvent;
use Zend\View\Model\ViewModel;
use Zend\Form\Annotation\AnnotationBuilder;
use Zend\Form;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityRepository;
use Clock\Entity\Activity;
use \Clock\Entity\Project;
Wich contains the get method:
public function get($id)
{
$entity = $this->getRepository()->find($id);
$form = $this->buildForm(new Activity());
#$form->setAttribute('action', $this->url()->fromRoute("activities", array('action' => 'update')));
$form->setAttribute('action', "/activities/$id/update");
$form->bind($entity);
return array(
"activities" => $entity,
"form" => $form
);
}
That feeds this view:
<h3>Edit activity</h3>
<div>
<?php echo $this->form()->openTag($form);?>
<?php echo $this->formSelect($form->get("project"));?><br>
<?php echo $this->formInput($form->get("duration"));?><br>
<?php echo $this->formInput($form->get("description"));?><br>
<input type="submit" value="save changes" />
<?php echo $this->form()->closeTag($form);?>
</div>
After sending it, I expect update method in activities to take control, but I get:
A 404 error occurred
Page not found.
The requested controller was unable to dispatch the request.
Controller:
activities
EDIT:#DrBeza
This is what i get, that i think (not a master in routes) is right:
Zend\Mvc\Router\Http\RouteMatch Object
(
[length:protected] => 21
[params:protected] => Array
(
[controller] => activities
[id] => 30
[action] => update
)
[matchedRouteName:protected] => activities
)
--
That's it.
Any help?
Quick Fix
The RouteMatch object tries to dispatch ActivitiesController::updateAction but you have defined ActivitiesController::update
That's due to you using a Restful Controller. the Controller::update-Method is specifically tied to PUT-Requests. You need to define an extra method to handle updates via POST-Requests.
I suggest you define ActivitiesController::updateAction, make clear in the docblock it is meant to handle POST-Update requests and refactor both ::updateAction and ::update to share as much common helper-methods as possible for a fast solution.
Common URI Structur information
As a nice information to have when you start developing RESTful applications/APIs:
The ruby community suggests the following url-structure for your resources:
# These are restful
/resource GET (lists) | POST (creates)
/resource/:id PUT (updates) | DELETE (deletes)
# these are just helpers, not restful, and may accept POST too.
/resource/new GET (shows the create-form), POST
/resource/:id/edit GET (shows the update-form), POST
Detailed Problem Analysis
A restful update will be sent by an consumer via PUT, but browsers sending HTML-forms may only send GET or POST requests. You should never use GET to create something. So you have to use POST in a forms-context.
Looking at the problem from an architectural perspective a multitude of possibilities emerge, depending on how big your application is.
For a small application, tight integration (formhandling and API handling in the controller) apply best.
Getting bigger you may want to split up API-Controllers (only restful actions) from Helper-Controllers (form, website handling) which talk to your API-Controllers
Being big (multitude of API-Users) you will want to have dedicated API Servers and dedicated Website Servers (independent applications!). In this case your website will consume the API serverside (thats what twitter is doing). API Servers and Website Servers still may share libraries (for filtering, utilities).
Code Sample
As an educational example I made an gist to show how such a controller could look like in principle. This controller is a) untested b) not production ready and c) only marginally configurable.
For your special interest here two excerpts about updating:
/* the restful method, defined in AbstractRestfulController */
public function update($id, $data)
{
$response = $this->getResponse();
if ( ! $this->getService()->has($id) )
{
return $this->notFoundAction();
}
$form = $this->getEditForm();
$form->setData($data);
if ( ! $form->isValid() )
{
$response->setStatusCode(self::FORM_INVALID_STATUSCODE);
return [ 'errors' => $form->getMessages() ];
}
$data = $form->getData(); // you want the filtered & validated data from the form, not the raw data from the request.
$status = $this->getService()->update($id, $data);
if ( ! $status )
{
$response->setStatusCode(self::SERVERSIDE_ERROR_STATUSCODE);
return [ 'errors' => [self::SERVERSIDE_ERROR_MESSAGE] ];
}
// if everything went smooth, we just return the new representation of the entity.
return $this->get($id);
}
and the editAction which satisfies browser-requests:
public function editAction()
{
/*
* basically the same as the newAction
* differences:
* - first fetch the data from the service
* - prepopulate the form
*/
$id = $this->params('id', false);
$dataExists = $this->getService()->has($id);
if ( ! $dataExists )
{
$this->flashMessenger()->addErrorMessage("No entity with {$id} is known");
return $this->notFoundAction();
}
$request = $this->getRequest();
$form = $this->getEditForm();
$data = $this->getService()->get($id);
if ( ! $request->isPost() )
{
$form->populateValues($data);
return ['form' => $form];
}
$this->update($id, $request->getPost()->toArray());
$response = $this->getResponse();
if ( ! $response->isSuccess() )
{
return [ 'form' => $form ];
}
$this->flashMessenger()->addSuccessMessage('Entity changed successfully');
return $this->redirect()->toRoute($this->routeIdentifiers['entity-changed']);
}
That error message suggests the dispatch process is unable to find the requested controller action and therefore using notFoundAction().
I would check the route matched and make sure the values are as expected. You can do this by adding the following into your module's onBootstrap() method:
$e->getApplication()->getEventManager()->attach('route', function($event) {
var_dump($event->getRouteMatch());
exit;
});

Symfony2 Doctrine2 Many To Many Form not Saving Entities

I am having some trouble with a many to many relationship. I have Users and Assets. I would like to be able to assign users to an asset on the asset page.
The code below displays a list of users when creating/editing an asset, however changes made to the user checkboxes do not save, while the rest of the data is persisted.
If I add an entry to users_assets through the mysql client, these changes are shown in the asset list.
User
class User extends BaseUser
{
/**
* #ORM\ManyToMany(targetEntity="Asset", inversedBy="users")
*/
private $assets;
}
Asset
class Asset
{
/**
* #ORM\ManyToMany(targetEntity="User", mappedBy="assets")
*/
private $users;
}
AssetType
public function buildForm(FormBuilderInterface $builder, array $options)
{
$form = $builder
->add('users', null, array(
'expanded' => true,
'multiple' => true
))
->getForm();
return $form;
}
For some reason I had to switch the doctrine mappings to get this to work:
Asset:
/**
* #ORM\ManyToMany(targetEntity="Adaptive\UserBundle\Entity\User", inversedBy="assets")
* #ORM\JoinTable(name="user_assets")
*/
private $users;
User:
/**
* #ORM\ManyToMany(targetEntity="Splash\SiteBundle\Entity\Asset", mappedBy="users")
*/
private $assets;
Now when I save the asset it saves the users associated. I did not need to define builder->add as an entity or collection. I simply pass it null and it uses the mapping info to fill in the entity info:
AssetType:
->add('users', null, array('expanded' => "true", "multiple" => "true"))
Not exactly sure why I needed to have the inversedBy and JoinTable info on the Asset vs The User but it seems to be working now!
Thanks For The Suggestions!!!
Weird enough I faced the same problem in 2016 and still had hard time finding the solution. I will share it for future googlers:
The problem is that what symfony essentially does when you save the form is this:
$asset->getUsers()->add($user)
And because you're on the inverse side of the relation it won't persist your changes.
What you really need is to make so that it calls this:
$asset->addUser($user)
Where addUser() is defined the following way on the Asset entity:
public function addUser(User $user)
{
//add to the inverse side
$this->users->add($user);
//add on the owning side (only this is persisted)
$user->addAsset($this); //$user->assets->add($asset);
}
So in order to make symfony use that $asset->addUser() method, you should set
'by_reference' => false
on your users field for AssetType form.
More about this setting here http://symfony.com/doc/current/reference/forms/types/form.html#by-reference
Remember you also need to define removeUser() method in the same way (so that it removes entity from the owning relation)
Not exactly sure why I needed to have the inversedBy and
JoinTable info on the Asset vs The User but it
seems to be working now!
The reason why your changes has been ignored is that doctrine persists only changes by the owning side of a relation (like #Florian said).
This is the link to Doctrine's documentation where this behaviour is explained: http://docs.doctrine-project.org/en/latest/reference/unitofwork-associations.html
At first you should drop backslash prefix in annotations (see notice here).
And you need to use entity field type:
$builder->add('users', 'entity', array(
'class' => 'AdaptiveUserBundle:User',
'expanded' => true,
'multiple' => true,
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('u')
->orderBy('u.username', 'ASC');
},
));
You need to use 'collection' field type in your form.
$builder->add('users', 'collection', array(
'type' => new UserType(),
'prototype' => true,
'allow_add' => true,
'allow_delete' => true
));
You need to create the UserType() form first obviously.
Here is all the info you will need, including code samples:
http://symfony.com/doc/current/cookbook/form/form_collections.html
http://symfony.com/doc/current/reference/forms/types/collection.html