How can I implement method that would return list of services depending on parameters provided in URL?
So if there are no parameters, all services are returned. If user and category provided, then filter by both params. If only user or only category provided, filter by one of the params.
/**
* #Route("/", name="api_services_search")
* #Method("GET")
* #ApiDoc(
* section = "Service",
* description="Search services",
* parameters={
* {"name"="category", "dataType"="int", "required"=true, "description"="Category ID"}
* {"name"="user", "dataType"="int", "required"=true, "description"="User ID"}
* },
* output="CoreBundle\Entity\Service"
* )
*/
public function searchAction(Request $request){
$categoryId = $request->query->get('category');
$userId = $request->query->get('user');
$result = new JsonResponse();
if($categoryId){
$category = $this->getDoctrine()->getRepository('CoreBundle:ServiceCategory')->find($categoryId);
if($category == null){
throw new ApiException('category not found');
}
$serviceList = $this->getDoctrine()
->getRepository('CoreBundle:Service')->findBy(array('serviceCategory' => $category));
}
else if($userId){
$user = $this->getDoctrine()->getRepository('CoreBundle:BasicUser')->find($userId);
if($user == null){
throw new ApiException('user not found');
}
$serviceList = $this->getDoctrine()
->getRepository('CoreBundle:Service')->findBy(array('basicUser' => $user));
} else{
$serviceList = $this->getDoctrine()
->getRepository('CoreBundle:Service')->findAll();
}
$serviceListJson = $this->serializeDataObjectToJson($serviceList);
$result->setContent($serviceListJson);
return $result;
}
Example URL:
http://127.0.0.1:8000/api/v1/services/?category=3&user=4
I have error:
Too many parameters: the query defines 1 parameters and you bound 2 (500 Internal Server Error)
Also I am looking for maintaible solution where I can easily add more parameters to URL in the future
I would go with something like this. I'm afraid you can't make it more generic and agnostic from query parameters adds/edits.
/**
* Controller action
*/
public function searchAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$serviceList = $em->getRepository('CoreBundle:Service')->fetchFromFilters([
'serviceCategory' => $request->query->get('category'),
'basicUser' => $request->query->get('user'),
]);
$serviceListJson = $this->serializeDataObjectToJson($serviceList);
$result = new JsonResponse();
$result->setContent($serviceListJson);
return $result;
}
/**
* Repository fetching method
*/
public function fetchFromFilter(array $filters)
{
$qb = $this->createQueryBuilder('s');
if (null !== $filters['serviceCategory']) {
$qb
->andWhere('s.serciceCategory = :serviceCategory')
->setParameter('serviceCategory', $filters['serviceCategory'])
;
}
if (null !== $filters['basicUser']) {
$qb
->andWhere('s.basicUser = :basicUser')
->setParameter('basicUser', $filters['basicUser'])
;
}
return $qb->getQuery()->getResult();
}
Related
Now i have code data like this:
my const
const CacheUserByUid = 'CacheUserByUid_';
const CacheUserByUsername = 'CacheUserByUsername_';
const CacheUserById = 'CacheUserByUsername_';
Get user data bu uid
/**
* Get user by uid , return user data for user profile
*
* #param $uid
* #return mixed
*/
public function getUserByUid($uid)
{
$result = Yii::$app->cache->getOrSet(self::CacheUserByUid . $uid, function () use ($uid) {
$result = self::find()
->select([
'id',
'username',
'email',
'city',
'country',
'name',
'avatar',
'about',
'uid',
])
->where(['uid' => trim($uid)])
->one();
if (!empty($result)) {
$result->id = (string)$result->id;
}
return $result;
});
return $result;
}
get user data by PK
/**
* #param $userId
* #return mixed
*/
public function getUserById($userId)
{
$user = Yii::$app->cache->getOrSet(self::CacheUserById . $userId, function () use ($userId) {
return self::findOne($userId);
});
return $user;
}
Get user by username
/**
* Get user by username. Return only for user front info
*
* #param $username
* #return array|\yii\db\ActiveRecord|null
*/
public function getUserByUsername($username)
{
$result = Yii::$app->cache->getOrSet(self::CacheUserByUsername . $username, function () use ($username) {
$result = self::find()->select([
'user.id',
'user.city',
'user.country',
'user.name',
'user.avatar',
'user.about',
'user.username'
])
->where(['username' => $username])
->one();
if (!empty($result)) {
$result->id = (string)$result->id;
}
});
return $result;
}
I cached this data. And where user was update i used:
/**
* #param $data
* #param $userId
* #return bool
* #throws \yii\db\Exception
*/
public function updateUser($data, $userId)
{
$user = $this->getUserById($userId);
if (!empty($user)) {
foreach ($data as $key => $name) {
if ($this->hasAttribute($key)) {
$user->$key = $name;
}
}
$user->updatedAt = time();
if ($user->save()) {
//чистимо кеш
FileCache::clearCacheByKey(self::CacheUserByUid . $user->uid);
FileCache::clearCacheByKey(self::CacheUserByUsername . $user->username);
FileCache::clearCacheByKey(self::CacheUserById . $user->id);
return true;
}
}
return false;
}
method clearCacheByKey
/**
* #param $key
*/
public static function clearCacheByKey($key)
{
if (Yii::$app->cache->exists($key)) {
Yii::$app->cache->delete($key);
}
}
Am I good at using a single-user cache that caches these requests in different keys? I don't see any other way out
Is it ok to cache user data in FileCache?
maybe it would be better to use something else for this?
In your case, such simple queries don't need to be cached explicitly. Yii already has a query cache and your requests definitely should be already stored in the cache. The key for data in cache would be a combination of your SQL's md5 with some connection metadata.
Just ensure that everything is configured correctly.
Also if you need to update cached data on some changes, make sure that you're making queries with the best for your case cache dependency. It can purge cached results by some auto condition or you can do it manually from your code(by using TagDependency)
What about FileCache it depends on traffic to your app and current infrastructure. Sometimes there is nothing criminal to store cache in files and you're always can switch to something like Redis/Memcache when your app grow big enough
This piece of code shows a smll part of the models post.php from October Rainlab Blog plugin. The AfterSave() function is modified, it sends an e-mail when a new blogPost in the backend is saved by the administrator, however, I would like to send it when it is actually Published and make sure it is not sending multiple times. How could I accomplish this?
public function filterFields($fields, $context = null)
{
if (!isset($fields->published, $fields->published_at)) {
return;
}
$user = BackendAuth::getUser();
if (!$user->hasAnyAccess(['rainlab.blog.access_publish'])) {
$fields->published->hidden = true;
$fields->published_at->hidden = true;
}
else {
$fields->published->hidden = false;
$fields->published_at->hidden = false;
}
}
public function afterValidate()
{
if ($this->published && !$this->published_at) {
throw new ValidationException([
'published_at' => Lang::get('rainlab.blog::lang.post.published_validation')
]);
}
}
public function beforeSave()
{
if (empty($this->user)) {
$user = BackendAuth::getUser();
if (!is_null($user)) {
$this->user = $user->id;
}
}
$this->content_html = self::formatHtml($this->content);
}
public function afterSave()
{
$user = BackendAuth::getUser();
if ($user && $user->hasAnyAccess(['rainlab.blog.access_publish'])) {
$susers = Db::select('select * from users where is_activated = ?', [1]);
foreach ($susers as $suser) {
$currentPath = $_SERVER['PHP_SELF'];
$pathInfo = pathinfo($currentPath);
$hostName = $_SERVER['HTTP_HOST'];
$protocol = strtolower(substr($_SERVER["SERVER_PROTOCOL"],0,5))=='https'?'https':'http';
$protocol.'://'.$hostName.$pathInfo['dirname']."/";
$spost_url = $protocol.'://'.$hostName.$pathInfo['dirname']."/"."nieuws/".$this->attributes['slug'] ;
$stitle = $this->attributes['title'] ;
$body = '<div> Hallo '.$suser->name.'</br> Er is zojuist een nieuws bericht gepubliceerd voor alle leden van mycompany.nl , je kunt hier het bericht lezen aangaande: '.$stitle.' </div>' ;
//$from = $user->email ;
$from = 'noreply#mycompany.nl';
$headers = "From: $from\r\n";
$headers .= "Content-type: text/html\r\n";
mail($suser->email,'Nieuws van mycompany', $body,$headers);
}
}
}
/**
* Sets the "url" attribute with a URL to this object.
* #param string $pageName
* #param Controller $controller
* #param array $params Override request URL parameters
*
* #return string
*/
public function setUrl($pageName, $controller, $params = [])
{
$params = array_merge([
'id' => $this->id,
'slug' => $this->slug,
], $params);
if (empty($params['category'])) {
$params['category'] = $this->categories->count() ? $this->categories->first()->slug : null;
}
// Expose published year, month and day as URL parameters.
if ($this->published) {
$params['year'] = $this->published_at->format('Y');
$params['month'] = $this->published_at->format('m');
$params['day'] = $this->published_at->format('d');
}
return $this->url = $controller->pageUrl($pageName, $params);
}
/**
* Used to test if a certain user has permission to edit post,
* returns TRUE if the user is the owner or has other posts access.
* #param User $user
* #return bool
*/
public function canEdit(User $user)
{
return ($this->user_id == $user->id) || $user->hasAnyAccess(['rainlab.blog.access_other_posts']);
}
public static function formatHtml($input, $preview = false)
{
$result = Markdown::parse(trim($input));
// Check to see if the HTML should be cleaned from potential XSS
$user = BackendAuth::getUser();
if (!$user || !$user->hasAccess('backend.allow_unsafe_markdown')) {
$result = Html::clean($result);
}
if ($preview) {
$result = str_replace('<pre>', '<pre class="prettyprint">', $result);
}
$result = TagProcessor::instance()->processTags($result, $preview);
return $result;
}
//
// Scopes
//
public function scopeIsPublished($query)
{
return $query
->whereNotNull('published')
->where('published', true)
->whereNotNull('published_at')
->where('published_at', '<', Carbon::now())
;
}
/**
* Lists posts for the frontend
*
* #param $query
* #param array $options Display options
* #return Post
*/
public function scopeListFrontEnd($query, $options)
{
/*
* Default options
*/
extract(array_merge([
'page' => 1,
'perPage' => 30,
'sort' => 'created_at',
'categories' => null,
'exceptCategories' => null,
'category' => null,
'search' => '',
'published' => true,
'exceptPost' => null
], $options));
$searchableFields = ['title', 'slug', 'excerpt', 'content'];
if ($published) {
$query->isPublished();
}
One way to accomplish this would be to extend the Post model.
As an example, you create a new plugin and model with an is_notified field.
You would then add something like this to the boot() method of your new plugin:
PostModel::extend(function ($model) {
$model->hasOne['your_model'] = ['Author\PluginName\Models\YourModel'];
});
PostsController::extendFormFields(function ($form, $model, $context) {
// Checking for Post instance
if (!$model instanceof PostModel) {
return;
}
// without this code you can get an error saying "Call to a member function hasRelation() on null"
if (!$model->your_model) {
$model->your_model = new YourModel;
}
}
You can then use that new model in the afterSave method
public function afterSave()
{
$user = BackendAuth::getUser();
if ($user && $user->hasAnyAccess(['rainlab.blog.access_publish'])) {
$susers = Db::select('select * from users where is_activated = ?', [1]);
foreach ($susers as $suser) {
...
if ($this->your_model->is_notified != true) {
mail($suser->email,'Nieuws van mycompany', $body,$headers);
$this->your_model->is_notified = true;
}
}
}
}
You should also consider using the extend method instead of modifying 3rd party plugin code. This will allow you to update the plugin without losing your edits. Something like this:
PostModel::extend(function ($model) {
$model->hasOne['your_model'] = ['Author\PluginName\Models\YourModel'];
// You can transfer your afterSave code here!
$model->bindEvent('model.afterSave', function () use ($model) {
$user = BackendAuth::getUser();
if ($user && $user->hasAnyAccess(['rainlab.blog.access_publish'])) {
..
}
});
});
Let me know if you have any questions!
I know, this is a complex case but maybe one of you might have an idea on how to do this.
Concept
I have the following process in my API:
Process query string parameters (FormRequest)
Replace key aliases by preferred keys
Map string parameters to arrays if an array ist expected
Set defaults (including Auth::user() for id-based parameters)
etc.
Check if the user is allowed to do the request (Middleware)
Using processed (validated and sanitized) query params
→ otherwise I had to do exceptions for every possible alias and mapping as well as checking if the paramter is checked and that doesn't seem reasonable to me.
Problem
Nevertheless, if you just assign the middleware via ->middleware('middlewareName') to the route and the FormRequest via dependency injection to the controller method, first the middleware is called and after that the FormRequest. As described above, that's not what I need.
Solution approach
I first tried dependency injection at the middleware but it didn't work.
My solution was to assign the middleware in the controller constructor. Dependency injection works here, but suddenly Auth::user() returns null.
Then, I came across the FormRequest::createFrom($request) method in \Illuminate\Foundation\Providers\FormRequestServiceProvider.php:34 and the possibility to pass the $request object to the middleware's handle() method. The result looks like this:
public function __construct(Request $request)
{
$middleware = new MyMiddleware();
$request = MyRequest::createFrom($request);
$middleware->handle($request, function() {})
}
But now the request is not validated yet. Just calling $request->validated() returns nothing. So I digged a little deeper and found that $resolved->validateResolved(); is done in \Illuminate\Foundation\Providers\FormRequestServiceProvider.php:30 but that doesn't seem to trigger the validation since it throws an exception saying that this method cannot be called on null but $request isn't null:
Call to a member function validated() on null
Now, I'm completely stumped. Does anyone know how to solve this or am I just doing it wrong?
Thanks in advance!
I guess, I figured out a better way to do this.
My misconception
While middleware is doing authentication, I was doing authorization there and therefore I have to use a Gate
Resulting code
Controller
...
public function getData(MyRequest $request)
{
$filters = $request->query();
// execute queries
}
...
FormRequest
class MyRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return Gate::allows('get-data', $this);
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
// ...
];
}
/**
* Prepare the data for validation.
*
* #return void
*/
protected function prepareForValidation()
{
$this->replace($this->cleanQueryParameters($this->query()));
}
private function cleanQueryParameters($queryParams): array
{
$queryParams = array_filter($queryParams, function($param) {
return is_array($param) ? count($param) : strlen($param);
});
$defaultStartDate = (new \DateTime())->modify('monday next week');
$defaultEndDate = (new \DateTime())->modify('friday next week');
$defaults = [
'article.created_by_id' => self::getDefaultEmployeeIds(),
'date_from' => $defaultStartDate->format('Y-m-d'),
'date_to' => $defaultEndDate->format('Y-m-d')
];
$aliases = [
// ...
];
$mapper = [
// ...
];
foreach($aliases as $alias => $key) {
if (array_key_exists($alias, $queryParams)) {
$queryParams[$key] = $queryParams[$alias];
unset($queryParams[$alias]);
}
}
foreach($mapper as $key => $fn) {
if (array_key_exists($key, $queryParams)) {
$fn($queryParams, $key);
}
}
$allowedFilters = array_merge(
Ticket::$allowedApiParameters,
array_map(function(string $param) {
return 'article.'.$param;
}, TicketArticle::$allowedApiParameters)
);
$arrayProps = [
// ..
];
foreach($queryParams as $param => $value) {
if (!in_array($param, $allowedFilters) && !in_array($param, ['date_from', 'date_to'])) {
abort(400, 'Filter "'.$param.'" not found');
}
if (in_array($param, $arrayProps)) {
$queryParams[$param] = guarantee('array', $value);
}
}
return array_merge($defaults, $queryParams);
}
}
Gate
class MyGate
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Auth\Access\Response|Void
* #throws \Symfony\Component\HttpKernel\Exception\HttpException
*/
public function authorizeGetDataCall(User $user, MyRequest $request): Response
{
Log::info('[MyGate] Checking permissions …');
if (in_array(LDAPGroups::Admin, session('PermissionGroups', []))) {
// no further checks needed
Log::info('[MyGate] User is administrator. No further checks needed');
return Response::allow();
}
if (
($request->has('group') && !in_array(Group::toLDAPGroup($request->get('group')), session('PermissionGroups', []))) ||
$request->has('owner.department') && !in_array(Department::toLDAPGroup($request->query('owner.department')), session('PermissionGroups', [])) ||
$request->has('creator.department') && !in_array(Department::toLDAPGroup($request->query('creator.department')), session('PermissionGroups', []))
) {
Log::warning('[MyGate] Access denied due to insufficient group/deparment membership', [ 'group/department' =>
$request->has('group') ?
Group::toLDAPGroup($request->get('group')) :
($request->has('owner.department') ?
Department::toLDAPGroup($request->query('owner.department')) :
($request->has('creator.department') ?
Department::toLDAPGroup($request->query('creator.department')) :
null))
]);
return Response::deny('Access denied');
}
if ($request->has('customer_id') || $request->has('article.created_by_id')) {
$ids = [];
if ($request->has('customer_id')) {
$ids = array_merge($ids, $request->query('customer_id'));
}
if ($request->has('article.created_by_id')) {
$ids = array_merge($ids, $request->query('article.created_by_id'));
}
$users = User::find($ids);
$hasOtherLDAPGroup = !$users->every(function($user) {
return in_array(Department::toLDAPGroup($user->department), session('PermissionGroups', []));
});
if ($hasOtherLDAPGroup) {
Log::warning('[MyGate] Access denied due to insufficient permissions to see specific other user\'s data', [ 'ids' => $ids ]);
return Response::deny('Access denied');;
}
}
if ($request->has('owner.login') || $request->has('creator.login')) {
$logins = [];
if ($request->has('owner.login')) {
$logins = array_merge(
$logins,
guarantee('array', $request->query('owner.login'))
);
}
if ($request->has('creator.login')) {
$logins = array_merge(
$logins,
guarantee('array', $request->query('creator.login'))
);
}
$users = User::where([ 'samaccountname' => $logins ])->get();
$hasOtherLDAPGroup = !$users->every(function($user) {
return in_array(Department::toLDAPGroup($user->department), session('PermissionGroups', []));
});
if ($hasOtherLDAPGroup) {
Log::warning('[MyGate] Access denied due to insufficient permissions to see specific other user\'s data', [ 'logins' => $logins ]);
return Response::deny('Access denied');
}
}
Log::info('[MyGate] Permission checks passed');
return Response::allow();
}
}
For a datatable I use in a page (webix datatable), I have to use a REST API.
My url is for example: http://localhost:8000/trial/1
In this page to make the api call I use the following:
save: "rest->{{ path('api_i_post') }}",
url: "rest->{{ path('erp_interventionapi_get', { trialid: trial.id })
With the GET method, I retrieve for a trial (/trial/1), many interventions which are loaded from a database and filled in the datatable.
With this datatable, I'm able to "add a new row". It uses the POST method (save: "rest->{{ path('api_i_post') }}")
When I add a new row, I'd like to be able to get the field trial_id filled in automatically, depending from where I add a new row in the datatable (for /trial/1, trial_id = 1) but I don't know how to retrieve this attribute (or the trial object id), in a POST and a PUT.
My postAction:
/**
* #Rest\Post("/api_i/", name="api_i_post")
*/
public function postAction(Request $request)
{
$data = new Intervention;
$id = $request->get('id');
$action = $request->get('action');
$daadala = $request->get('daadala');
$date = $request->get('date');
$week = $request->get('week');
$infopm = $request->get('info_pm');
$comment = $request->get('comment');
$location = $request->get('location');
$trial = $request->get('trialid');
$data->setAction($action);
$data->setDaadala($daadala);
$data->setDate($date);
$data->setWeek($week);
$data->setWho($infopm);
$data->setInfoPm($comment);
$data->setComment($location);
$data->setTrial($trial);
$em = $this->getDoctrine()->getManager();
$em->persist($data);
$em->flush();
$lastid = $data->getId();
$response=array("id" => $id, "status" => "success", "newid" => $lastid);
return new JsonResponse($response);
$view = View::create(array("newid" => $lastid, "id" => $id, "status" => "success"));
return $this->handleView($view);
}
And my putAction
/**
* #Rest\Put("/api_i/{id}")
*/
public function putAction(Request $request)
{
$data = new Intervention;
$id = $request->get('id');
$action = $request->get('action');
$daadala = $request->get('daadala');
$date = $request->get('date');
$week = $request->get('week');
$infopm = $request->get('info_pm');
$comment = $request->get('comment');
$location = $request->get('location');
$sn = $this->getDoctrine()->getManager();
$intervention = $this->getDoctrine()->getRepository('ErpBundle:Sponsor')->find($id);
if (empty($intervention)) {
return new View("Sponsor not found", Response::HTTP_NOT_FOUND);
}
$intervention->setAction($action);
$intervention->setDaadala($daadala);
$intervention->setDate($date);
$intervention->setWeek($week);
$intervention->setWho($infopm);
$intervention->setInfoPm($comment);
$intervention->setComment($location);
$sn->flush();
$response=array("id" => $id, "status" => "success");
return new JsonResponse($response);
}
Can you help me with this issue?
Thank you very much
Update of my code after the replys:
I have update this in my twig template:
save: "rest->{{ path('api_i_post', { trialid: trial.id }) }}",
If I look in the profiler of the ajax request, I see it is here:
Key Value
trialid "1"
But I still don't figure how to get it in my post request (the trial_id is still null right now)
I've tried the following:
/**
* #Rest\Post("/api_i/", name="api_i_post")
* #Rest\RequestParam(name="trialid")
*
* #param ParamFetcher $paramFetcher
* #param Request $request
*/
public function postAction(Request $request, ParamFetcher $paramFetcher)
{
$data = new Intervention;
$id = $request->get('id');
$action = $request->get('action');
$daadala = $request->get('daadala');
$date = $request->get('date');
$week = $request->get('week');
$infopm = $request->get('info_pm');
$comment = $request->get('comment');
$location = $request->get('location');
$trial = $paramFetcher->get('trialid');
$data->setAction($action);
$data->setDaadala($daadala);
$data->setDate($date);
$data->setWeek($week);
$data->setWho($infopm);
$data->setInfoPm($comment);
$data->setComment($location);
$data->setTrial($trial);
$em = $this->getDoctrine()->getManager();
$em->persist($data);
$em->flush();
$lastid = $data->getId();
$response=array("id" => $id, "status" => "success", "newid" => $lastid);
return new JsonResponse($response);
$view = View::create(array("newid" => $lastid, "id" => $id, "status" => "success"));
return $this->handleView($view);
}
I guess you are using the FosRestBundle, if so, you can use annotations to retrieve your url parameters :
/**
* #Rest\Put("/api_i/{id}", requirements={"id" = "\d+"})
*/
public function putAction($id)
{
// you now have access to $id
...
}
If you want to allow additionnal parameters for your route but not in the uri, you can use RequestParam with annotations :
/**
* #Rest\Put("/my-route/{id}", requirements={"id" = "\d+"})
*
* #Rest\RequestParam(name="param1")
* #Rest\RequestParam(name="param2")
*
* #param ParamFetcher $paramFetcher
* #param int $id
*/
public function putAction(ParamFetcher $paramFetcher, $id)
{
$param1 = $paramFetcher->get('param1');
....
}
Be sure to check the fosRestBundle documentation to see everything you can do (such as typing the params, making them mandatory or not, etc...)
To get post value you need to do this inside your post action:
public function postAction(Request $request)
{
$postData = $request->request->all();
Then you have an array of value like:
$id = $postData['id'];
For the PUT you need this:
public function putAction(int $id, Request $request)
{
$putData = json_decode($request->getContent(), true);
And then to treieve a value like this:
$id = $putData['id'];
The action included at the end of this post is called from an ajax call via jQuery. When I try to delete more than one record, just the first is deleted but the flash messages are printed for every request.
I checked the input data and it is correct. No exception are throwed.
Any idea? Thanks!
/**
* #Route("/cancella", name="training_plan_activity_edition_final_delete")
* #Method({"POST"})
*
* #param Request $request
* #return \Symfony\Component\HttpFoundation\Response
*/
public function deleteAction(Request $request)
{
if (!$request->isXmlHttpRequest()) {
throw new \Exception('this controller allows only ajax requests');
}
$ids = json_decode($request->get('ids'), true);
$em = $this->getDoctrine()->getManager();
foreach ($ids as $id) {
if($id <> 'on') {
$trainingPlanActionEditionFinal = $this->getDoctrine()
->getRepository('TrainingPlanBundle:TrainingPlanActionEditionFinal')
->find($id);
if (!$trainingPlanActionEditionFinal) {
throw $this->createNotFoundException(
'Training plan action edition final with id ' . $id . ' not found'
);
}
$trainingPlanSlug = $trainingPlanActionEditionFinal->getSlug();
try {
$em->remove($trainingPlanActionEditionFinal);
$em->flush();
$this->get('session')->getFlashbag()->add('success', 'Cancellazione dell\'edizione avvenuta con successo');
} catch (\Exception $e) {
$this->get('session')->getFlashbag()->add('error', 'Impossibile cancellare l\'edizione');
}
}
}
return new Response($this->generateUrl('training_plan_action_edition_final_list', array(
'trainingPlanSlug' => $trainingPlanSlug
)
));
}