symfony2,fosuserbundle,roles , Change role of one user no working with Symfony2

Change role of one user no working with Symfony2


Tag: symfony2,fosuserbundle,roles

Sorry if this question has been asked many times but I didn't found any solution on the Web. So, I just have installed FOSUserBundle and I've created 2 users on my application with the console. The problem is they don't have any role. So in on controller, I get the user Entity and y set his role but when I try to access to a page restricted for admin, it says access denied. Moreover, the roles has no changed on the databse. My code in the controller :

$user = $this->container->get('security.context')->getToken()->getUser();
if (!$this->get('security.context')->isGranted('ROLE_ADMIN')){
    throw new AccessDniedException('Access Denied !');

Anyone have an idea ? Thanks in advance !


It is a very bad practice to set a user role in your controller if you want to keep them away from the controller in the first place. I hope you use this line of code for testing only.

The FOSUserBundle provides a number of command line utilities to help manage your application's users.

The one you need is:

$ php app/console fos:user:promote testuser ROLE_ADMIN

Replace testuser with your username.

Did you also define your roles in your firewall?


Symfony2/Twig - iterate over select options

Usual way of displaying select field is to call {{ form_row(form.doctor_service_id, {'attr':{'class':'form-control'}}) }} I would like to perform two things: Check if this field is actually a select field Iterate over every option (value, name). I know how twig iterator works, I just don't know how to access select options...

Symfony2 Catchable Fatal Error: Argument 1 passed to entity Catchable Fatal Error: Argument 1 passed to entity

I got this error and I'm stuck since many hours Catchable Fatal Error: Argument 1 passed to Thinking\ThinkBundle\Entity\InYourMind::setThinkFriend() must be an instance of Thinking\ThinkBundle\Entity\InYourMindFriend, array given, called in /var/www/html/thinkroulette/vars/vendor/symfony/symfony/src/Symfony/Component/PropertyAccess/PropertyAccessor.php on line 410 and defined I searched for this issue and lots of results came up but I wasn't capable to...

Symfony2 creating and persisting entity relationships

I have two entities Skin and Email. I want Email to be a part of the Skin entity, however I can't use the console to update schema automatically right now, and that is probably why I can't get the relationship to work. So I want to store all the Emails...

Symfony2 service unable to find template

I've just pulled an all-nighter trying to get this to work, and I'm probably missing something foolish, but help me out. I have a symfony2 service which sends emails. I have injected the @templating service into my service's constructor like so: services.yml order_service: class: AppBundle\Services\OrderService arguments: [ "@doctrine.orm.entity_manager", "@mailer", "@templating"...

Symfony files which are included in CSS are not found when using assetic

I'm using Symfony with Twig and I use assetic. The problem is that my CSS file includes other CSS files like that: @import url(ie8.css); @import url(blocks.css); @import url(plugins.css); @import url(app.css); And these files are not found when webpage is displayed. Same happens with fonts and images. How do I solve...

Symfony\Component\Config\Exception\FileLoaderLoadException] error

Hi I stumble upon this error everytime I want to run my Symfony application from console. Therefore I am unable to use this symphony app at all. Please help me with your knowledge. [Symfony\Component\Config\Exception\FileLoaderLoadException] Unable to parse at line 9 (near "mailer_transport="gmail"") in /opt/lampp/htdocs/ (which is being imported from "/opt/lampp/htdocs/")....

Setup VPS with a Symfony2 project from git repository

I have a: - VPS with LAMP stack - local symfony2 project (git) - bitbucket repository What do I need to do to properly setup my project in the production evironment? Folder structure/permissions? Can I simply clone the repository in the public folder? (I don't think so) P.s. I've already...

Adding own action to SonataAdminBundle dropdown menu

We use the SonataAdminBundle with our Symfony2 application. When editing an entity I want to add an own action to the dropdown menu which is located in the top right corner, but I have no idea how this works. I know I can add own routes via configureRoutes(RouteCollection $collection) and...

comparison operator is not working in twig

problem in comparing dates in twig. case if event is ongoing or is about to begin within 7 days. twig code {% set|date("d-m-Y")%} {% set|date("d-m-Y") %} {% set upcoming_days =daysdiff(event_startdate)|date('d-m-y') %} {% set stdate= "now"|date('d-m-y') %} {% if event_startdate >stdate and event_startdate < upcoming_days %} // condition...

Symfony2: changing the request class and updating the test environment

I have modified the base Request class of my application as explained in the accepted answer of this question. It works very well, except when launching my functional tests, I get the following error: Controller "My\Bundle\AppBundle\Controller\MyController::searchAction()" requires that you provide a value for the "$request" argument (because there is no...

Redirecting all ip to maintenance page except some ips

When releasing new versions of my Symfony project, I need to redirect all external ip addresses to a maintenance.html page (which lives into symfony web directory) using apache. Here is the virtualhost file configuration I've created for this purpose but: When I go from an external ip I get 403...

Unable to configure Symfony (3rd party) bundle

I am faily new to Symfony and I am trying to setup a third party bundle that reads RSS feeds and then insert them into database. The third party bundle I am trying to use is called rss-atom-bundle After reading the instructions I can get the RSS feeds however I...

Symfony Entity query builder that checks for free spots

First off all: I know the title isn't helping, but it's the best I can think of. So I've got two entities in Symfony one is called Team and the other one Slot the Slot entity has a name, a start and end date and all that stuff. Besides that...

Update session in symfony2 for shoppingg cart

I have the following code : public function addAction(Request $request){ //Get submited data // Get Value from session $sessionVal = $this->get('session')->get('aBasket'); // Append value to retrieved array. $aBasket = $request->request->all(); if(count($sessionVal) > 0) { foreach ($sessionVal as $key=>$value) { if($aBasket['product_id'] == $sessionVal[$key]['product_id']) { $sessionVal[$key]['product_quantity'] = $sessionVal[$key]['product_quantity'] + $aBasket['product_quantity'];...

Symfony/Twig radio style formbuilder

I need to style each of radio button using Symfony form builder. This is my part of my createFormBuilder: ->add('categoryId', 'entity', array( 'class' => 'MyBundle:Category', 'property' => 'name', 'required' => false, 'expanded' => true )) And in my twig template: {% for child in form.categoryId %} <div class="radio i-checks col-md-3">...

Symfony2 relationship between two entities

I want to make a relationship between two entities but for some reason I am getting NULL on one of the values... So in my skin entity I have an email_registration_id field with the relationship : /** * @ORM\ManyToOne(targetEntity="Project\UserBundle\Entity\Email") * @ORM\JoinColumn(name="email_registration_id", referencedColumnName="id") */ protected $email_registration_id; /** * Set email_registration_id *...

How adapt the path to the previous and next article

I am looking for a solution to access in the current article to the previous(<<) or the next article(>>) at the end of the page of an article. I thought to get the current paramater of the url with this : {{ dump(app.request.attributes.get('_route_params')) }} and inject in the path with...

Setting cookie for AngularJS translate locale using PHP

My app uses Symfony and AngularJS. I have translations some with Symfony itself and some with AngularJS angular-translate. How do I set a cookie or session variable to change language for AngularJS from PHP?

How to write and use Monolog handlers and channels

I have read some docs here but still not clear to me how to write and use a custom Monolog handler and channel. Let me explain a bit what I want to achieve. I have a custom function and I want that log to be logged into a file called...

Force Uppercase on Symfony2 form text field

I've inherited a Symfony2 project that has a form built as such: $builder ->add('Status', 'choice', array( 'choices' => array('' => '', 'PASS' => 'PASS', 'FAIL' => 'FAIL', 'INCOMPLETE' => 'INCOMPLETE', 'DROPPED' => 'DROPPED',), 'required' => FALSE, )) ->add('First_Name', 'text', array('label'=>'First Name', 'required' => FALSE)) ->add('Last_Name', 'text', array('label'=>'Last Name', 'required' =>...

Symfony one-to-one, unidirectional relation

I have two entities. User and Contact. User and contact have the same property phone_number. I would like to get all contacts with user object if its exists. It is also possible that the same phone number exists in contact table but it doesn't exist in user table. Below is...

Unique Entity Error message

I have a user entity which have some unique fields. The code bellow shows you how I defined it. /** * @UniqueEntity(fields={"login"}, message="UNIQUE ERROR MESSAGE") */ ...... /** * @var string * * @ORM\Column(name="login", type="string", length=255, unique=true) */ private $login; Developping an API, I would like to be able to...

With a OneToMany relation between entities, how create the right queryBuilder with Doctrine (on the Inversed Side entity)

I have these 3 entities in my symfony2.6 project: Compteurs.php class Compteurs { /** * @var \PointsComptage * * @ORM\ManyToOne(targetEntity="PointsComptage", inversedBy="compteurs") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="pointscomptage_id", referencedColumnName="id") * }) */ private $pointsComptage; /** * @var \Doctrine\Common\Collections\Collection * * @ORM\OneToMany(targetEntity="ParametresMesure", mappedBy="compteurs") */ private $parametresMesure; ParametresMesure.php: class ParametresMesure { /** * @var Compteurs...

Remove automaticaly entity in BD when choice value not selected (or null selected)

I would like to know if symfony/doctrine can manage automaticaly the fact that instead of setting the value of my entity to null it could symply remove it. (by removing it I mean the records where the value equal null) exemple: I have a PICTURE entity linked to a VOTE...

Dependencies in forms Symfony2

I'm working on a webapplication in Symfony2. I came to a point in which I need some advice/explanation from some one more advanced in Symfony. I have a part of my database that is set up as follows: I have cards that belong to a card attribute set and consists...

Class inheritance in Symfony2

I'm a bit confused about an error that I'm getting: Undefined method 'getAsArray'. The method name must start with either findBy or findOneBy! getAsArray() is a method in my repository class, it's called in PostsController.php like so: $categoriesList = $this->getDoctrine()->getRepository('AirBlogBundle:Category')->getAsArray(); CategoryRepository.php is defined like this: namespace Air\BlogBundle\Repository; class CategoryRepository extends...

Symfony 2 - Class “Mingle\StandardBundle\Entity\Product” is not a valid entity or mapped superclass

I created a Product.php file in my bundle Mingle\StandardBundle\Entity like this: <?php namespace Mingle\StandardBundle\Entity; use Doctrine\ORM\Mapping as ORM; /* * @ORM\Entity * @ORM\Table(name="product") */ class Product { /* * @ORM\Column(type="integer") * @ORM\ID * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /* * @ORM\Column(type="string",length=100) */ protected $name; /* * @ORM\Column(type="decimal",scale=2) */ protected $price; /*...

Symfony/Twig how to render a Route set by anotation?

Let's say I have this code in a controller: <?php namespace Foo\BarBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration as Mvc; /** * @Mvc\Route("/foo/bar") */ class TestController extends Controller /** * @Mvc\Route("/test/{id}", requirements={"id" = "[0-9]{1,6}"}) * @Mvc\Template * * @return view */ public function testAction($id) { return array('test' => $id); } } How...

OAuth HwioBundle, different socialNetWork

I work to projekt in Symfony wich have regisrtation HWIOBundle for different social network. If user enter for example linkedin and some time for github I has two user in database. Who knows how to do was one?

Store entity from session doesn't work => $em->persist()

at first: Sorry for my poor english :-) A beginner need help! I have 3 entities/tables: Tables: contact_person id, title, firstname, surname, adress_id address id, street, zip, city, country_id country (fix values) id, name, code 1, Austria, AT 2, Germany, DE ... Entities: /** * ContactPerson * * @ORM\Table(name="contact_person") *...

Validation of a form before submission

Using Symfony, version 2.3 and more recent, I want the user to click on a link to go to the edition page of an already existing entity and that the form which is displayed to be already validated, with each error associated to its corresponding field, i.e. I want the...

wkhtmltopdf on openSuSE: cannot connect to X server

I need wkhtmltopdf on openSuSE. I have installed it via the repository. The version is 0.12.1. To render HTML with Symfony, I use the KnpSnappyBundle. By rendering a twig template, I got the following error message: The exit status code '1' says something went wrong: stderr: "wkhtmltopdf: cannot connect to...

I can't do update with an entity in my select symfony 2

$builder ->add('tecnicoId', 'entity', array( 'class' => 'MainHomeBundle:Tecnicos', 'property' => 'nombre', 'expanded' => false, 'multiple' => false )) ->add('cambiar', 'submit') ; controller $form = $this->createForm(new ServicioseditType(), $datos); $form->handleRequest($request); $em = $this->getDoctrine()->getManager(); $em->flush(); return $this->render('MainHomeBundle:Admin:editserv.html.twig', array("form"=>$form->createView())); view twig {{ form_errors(form.tecnicoId) }} {{...

Symfony 2 unable to pass entity repository to form

I have a form with a drop down and a set of checkboxes, i've used entity form field type to get the values via DB. it works with one of the entity but not with the other. i have this code seperately inside AddBadgesType there is NO AddBadges entity <?php...

ClassNotFoundException Symfony UserBundle

I'm developping a website on Symfony2, I want to intergrate FOSUserBundle. I am using Doctrine ORM User class. I've followed the installation steps but I got this error: ClassNotFoundException in AppKernel.php line 21: Attempted to load class "FOSUserBundle" from namespace "FOS\UserBundle". Did you forget a "use" statement for another namespace?...

How to create a console command in Symfony2 application

I need to create a console command for a Symfony2 application and I read docs here and here though I am not sure what of those I should follow. So this is what I did. Create a file under /src/PDI/PDOneBundle/Console/PDOneSyncCommand.php Write this code: namespace PDI\PDOneBundle\Console\Command; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use...

Symfony2: ajax call redirection if session timedout

I have a working dashboard with ajax request. I fire an ajax request on some events which will update a part of the dashboard. But if the session has expired, the part will be refreshed with the login page. How can i do a redirection after the ajax call if...

WebTestCase, Silex and $_GET

I'm experiencing some issues on a WebTestCase using Silex: on one of my controller's action, I need a parameter passed through a normal $_GET (I have to as it's an URL, and Apaches interprets the %2F if it's outside of the query string -- see Url Variables with %2f not...

Deserializing or parse XML response in Symfony2

I am calling a API method through cURL and I got this response: <?xml version="1.0" encoding="UTF-8"?> <jobInfo xmlns=""> <id>75080000002s5siAAA</id> <operation>query</operation> <object>User</object> <createdById>00580000008ReolAAC</createdById> <createdDate>2015-06-23T13:03:01.000Z</createdDate> <systemModstamp>2015-06-23T13:03:01.000Z</systemModstamp> <state>Open</state>...

Logs an entire array using Monolog [closed]

Is there any way to log an entire array using Monolog? I have been reading several docs but didn't find a way to log the entire array in a readable format, any advice? Docs I've read: Monolog, how to log PHP array into console? ...

Symfony2 move app.php from web directory to root directory

I moved app.php from web directory to root and i change the following two lines: $loader = require_once __DIR__.'/app/bootstrap.php.cache'; require_once __DIR__.'/app/AppKernel.php'; Also i move .htaccess file from web directory to root , my problem is that now the system cannot find JavaScript and CSS files....

Symfony change validation message globally

Is there a way to change the basic validation error message to one I need for all entities at once? Currently using Yaml config for every entity, but it's not a way. CF\MyBundle\Entity\User: properties: email: - Email: message: e-mail no válido - NotBlank: message: Campo obligatorio username: -NotBlank: message: Campo...

Using crontab to call wget every 5 minutes

I am working on a project where the wget and crontab are used to run a process in the background. I have a php file named "Hello.php" that I want to run this every 5 minutes. I have found that if I want to have a cron job run every...

Symfony2 & PHPUnit - Access getContainer()

I have a problem with my PHPUnit test on symfony2. To connect to my application, I use a web service, so I created a UserProvider. In my function loadUserByUsername I use symfony2 parameters saved in app/config/parameters.yml. As I'm not in a controller I need to use the global variable $kernel...

order attribute of an object in Synfony

I would like to reorder the attribute (COMMENTS) of my object (instance of ARTICLE) after I retrieve it from the DBB. Is this possible? My object is ARTICLE and it is linked to COMMENTS (which is defined as a collection in entity article) I know I can order through the...

symfony twig render dynamic twig code

In my symfony2 action, i have: $twigCode = '<li>{{ data.value }}</li>'; //In database $datas = array(array( 'value' => 'line 1'), array( 'value' => 'line 2')); return $this->render( '...List.html.twig', array( 'twigCode' => $twigCode, 'datas' => $datas ) ); In my twig template, i want something like: <ul> {% for data in...

Set Auth Token manually for different firewall

My application has 2 security firewalls "admin" - used by internal staff "account" - used by customers. Previoly I had one action under the account firewall, the action in the controller looks something like this. $user = //get user somehow $token = new UsernamePasswordToken($user, null, 'account', $user->getRoles()); $this->get('security.token_storage')->setToken($token); With this...

AngularJS execute some action in all application instances

I have AngularJS app called myApp. It has several controllers which are used in different pages (website is based on Symfony so page reloads happens sometimes). I need to execute some lines of code in every controller. how do I do that without duplicating that code?

Symfony Crawler: how to check that a link to a particular page exists

I'm writing some functional tests and i want to verify that the Edit link exists on the page if the user is logged in. The link is a simple <a href="/profile/22/edit">Edit</a>. How can I filter it using the Crawler component of Symfony? One solution is this: $this->assertEquals(1, $crawler->filter('html:contains("<a href="/profile/22/edit">")')->count()); But...