Menu
  • HOME
  • TAGS

OAuth HwioBundle, different socialNetWork

php,symfony2,oauth,hwioauthbundle

If user's email is similar in both social accounts, you can use email field to identify user. You should create user provider class. If user with provided social token won't be found in database, user provider will try to find user by email and add new social token for specified...

Class inheritance in Symfony2

php,symfony2,doctrine2

Usually this error occurs when you forget to specify the repository class inside your entity class. Try modifying to the Entity annotation of your entity class to: /** * @ORM\Entity(repositoryClass="AppBundle\Entity\CategoryRepository") */ class Category {} ...

Force Uppercase on Symfony2 form text field

php,forms,symfony2

I’m not sure if you ask for server-side validation or assistance for client-side uppercase input. In case of the latter: you could add a CSS class or a data-* attribute (something like ->add('PID', 'text', ['label'=>'License Number', 'required' => FALSE, 'attr' => ['data-behavior' => 'uppercase']])) to the PID element. Then, you...

how symfony2 remember me work without any table for token?

php,symfony2,cookies,remember-me

It stores the username and the token expiration together with the token class name and the signature in the single cookie. Here is where it's being processed: https://github.com/symfony/symfony/blob/2.8/src/Symfony/Component/Security/Http/RememberMe/TokenBasedRememberMeServices.php#L39 So the whole protection is based on using the secret token (the one you specify in parameters) and user's password. Answering the...

Symfony2 relationship between two entities

php,mysql,entity-framework,symfony2

It's normal that the creation of a new email is not associated to a skin object. How could it ? The relation is unidirectional, and only works when you create a skin and you give it an email. To create an email and give it a skin, you have to...

Starts with Symfony2 : No route found for “GET /”

php,symfony2,install

that's because your demo route is equal to /app/example or something like that. Go to DefaultController in your AppBundle and change @Route parameter to single slash /

Symfony2 service unable to find template

php,email,symfony2,templates,twig

Even if your service lies in the same namespace as it's your template, that does not mean that you can call it directly like that. Did you tried the way you render normal controller templates, like this: ->setBody($this->twig->render( 'AppBundle:Emails:email-voucher.html.twig', [ 'order' => $order, 'voucher' => $voucher, 'customer' => $customer ]...

Symfony2/Twig - iterate over select options

php,symfony2,twig

<select name="country"data-width="100%"> {% for key,val in form.country.vars.choices %} <option value="{{ val.value }}" {{ form.country.vars.value == '' and key==0 ? ' selected ' :(val.value == form.country.vars.value ? ' selected ' : '') }}>{{ val.label | trans }}</option> {% endfor %} </select> ...

symfony twig render dynamic twig code

symfony2,twig

You will have to use twig core or may be customized view rendering Check below code $loader = new Twig_Loader_Array(array( 'index.html' => 'Hello {{ name }}!', )); $twig = new Twig_Environment($loader); echo $twig->render('index.html', array('name' => 'Fabien')); check here for documentation: http://twig.sensiolabs.org/doc/api.html#built-in-loaders...

Deserializing or parse XML response in Symfony2

php,xml,symfony2,deserialization,jmsserializerbundle

It depends on your intention. If you want to directly push part or all of the XML to an entity/document object for saving to a database then the JMSSerializerBundle can do this very smartly and is definitely the best way to do it. If however you just want to extract...

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

symfony2

Add this method to your Tecnicos entity: public function __toString() { return $this->name; // could be anything that returns a string, even a string itself (but wouldn't be relevant). } ...

Using crontab to call wget every 5 minutes

php,symfony2,crontab,wget

use the console component make it run your hello.php script call the command in your crontab bash /your/dir/app/console yourcommand or even simpler run php your/dir/hello.php...

Extending Twig's AppVariable

php,symfony2,twig

What probably was done by the old developers was overriding the app variable. Until Symfony @2.7 the class was called GlobalVariables and lives in the following namespace - Symfony\Bundle\FrameworkBundle\Templating. As of @2.7 it's called AppVariable and it lives in this namespace - Symfony\Bridge\Twig. What is done behind the scenes? That...

Symfony2 fail during installation

php,symfony2

Why don't you use composer?The composer make more than "symfony" command file.

How to concatenate a parameter value with a constant string in Yaml

symfony2,yaml

You don't need a concatenation character, you can append the constant directly after the parameter. For example, for a service definition in services.yml: my.service: class: %my.service.class% arguments: - @logger, - %some_parameter%, - %parameter_url%?wsdl, ...

WebTestCase, Silex and $_GET

symfony2,silex,web-testing

The server globals (like $_GET) are populated by Apache. When running the functional test, Apache is skipped so $_GET is not populated anymore. Instead of using the server globals, you should use the Request object to extract the GET parameters. This way, the framework will intercept both the PHPUnit injected...

Form get data from collection

symfony2

Assuming the Question sub-form / collection in your Questionnaire form is called 'questions': $questionForms = $form->get('questions'); foreach ($questionForms as $questionForm) { $notMappedQuestionData = $questionForm->get('notMappedFieldName')->getData(); } ...

Validation of a form before submission

php,validation,symfony2,form-submit

In place of: $form->submit($request->request->get($form->getName())); Try: $form->submit(array(), false); ...

Symfony 2 : Generated bundle will not find routes

php,symfony2

The debug message says that you are in prod environment. Have you tried accessing your route from the dev environment : mydomain.local/app_dev.php/hello/somename or clearing the cache ?...

Symfony one-to-one, unidirectional relation

symfony2,doctrine2

There's no change you can make to your annotations to make this work with your existing relationships. You have defined a nullable one-to-one relationship between the Contact and User entities. From a class perspective this means that a Contact's $user must either point to an instance of User or be...

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

php,symfony2,doctrine2

When you store doctrine entities in the session they become detached from the EntityManager. You need to merge any entities which are already in the database back into the EntityManager. Something like this (checking for null where necessary): foreach($contactPersons as $key => $contactPerson) { $mergedCountry = $em->merge($contactPerson->getAddress()->getCountry()); $contactPerson->getAddress()->setCountry($mergedCountry); $em->persist($contactPerson); }...

Symfony2: changing the request class and updating the test environment

php,symfony2,request,phpunit

I think you have to override the class for test.client which, by default, uses Symfony\Bundle\FrameworkBundle\Client. Something like: <parameters> <parameter name="test.client.class">My\Bundle\AppBundle\Test\Client</parameter> </parameters> First, take a look at the base class Symfony\Component\BrowserKit\Client. If you look at the request method of this class you will find this: public function request(/* ... */) {...

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

php,symfony2,routing,twig,url-routing

When you omit the name it's being autogenerated for you. The autogenerated name is a lowercase concatenation of bundle + controller + action. For example, if you have: Bundle AppBundle Controller MyController Action: testAction() the name would be app_my_test. You can list all routes using Terminal: php app/console router:debug All...

Doctrine OneByOne's and Date

php,symfony2,doctrine2,entity

Your entity class needs getters (and setter). class News { // ... /** * @ORM\Column(name="published_at", type="datetime") */ private $published_at; public function getPublished_at() { return $this->published_at; } } with this {{ news_item.published_at }} will call News::getPublished_at. (...) if not, and if foo is an object, check that getBar is a valid...

Set Auth Token manually for different firewall

symfony2

This may be a little hacky, but manually wiriting the token to the session achieved what I wanted $token = new UsernamePasswordToken($user, null, 'account', $user->getRoles()); $this->get('session')->set('_security_account',serialize($token)); // Needed to prepend "_security_" to the firewall name to get "_security_account" Didnt even need to call lines such as //Didnt seem to need...

Update session in symfony2 for shoppingg cart

php,symfony2,symfony-2.1,php-5.3,symfony-2.3

You can simplify your code to, i guess your session array would look something like array( '11' =>array('id'=>'11','title'=>'some product','product_quantity'=>2), '12' =>array('id'=>'12','title'=>'some product','product_quantity'=>1), '13' =>array('id'=>'13','title'=>'some product','product_quantity'=>3), ); key in your cart array will be product id so there will be no chance of duplicate product in array now in below code...

Adding own action to SonataAdminBundle dropdown menu

symfony2,sonata

One way would be to override the template that is used when editing. Now, what you need to do is: Create new directory (if you already haven't) in app/Resources called SonataAdminBundle. Inside, create another one called views. This would create a path like app/Resources/SonataAdminBundle/views. This is Symfony basic template overriding....

Attempted to load class “COM” from namespace -Symfony2

php,class,symfony2,ms-access

In Symfony you use namespaces. imagine that you want to make an instance of COM into a controller, lets say MyController. Your controller PHP file will begin with this rule: namespace AppBundle\Controller; Now if you make an instance of the PHP COM class PHP will search this class into the...

Use a PHP file to Symfony

php,symfony2,elasticsearch

You need to import the namespace for the ElasticSearch object into your controller class. Typically this would be done with a use statement near the top of the file (under the namespace declaration for the class), i.e.: namespace MyBundle\Controller use Elasticsearch; class index { public function indexAction() { $client =...

Symfony2 - assets do not load

javascript,php,css,symfony2,assets

Your asset files need to be qualified by a bundle - assets:install installs them in an appropriately named subdirectory of /web/bundles: <link href="{{ asset('bundles/myvalley/css/style.css') }}" type="text/css" rel="stylesheet" /> <img src="{{ asset('bundles/myvalley/images/file.png') }}" alt="some image" /> If you look for your files within the web directory you will see this directory...

Redirecting all ip to maintenance page except some ips

apache,.htaccess,symfony2

mod_rewrite doesn’t know a %{REMOTE_URI} variable. Probably you mean %{REQUEST_URI}.

Symfony2 Functional Testing: Is a database required or not?

php,unit-testing,symfony2,doctrine2,functional-testing

Answer to this question in not simple yes/no, you can do it in both ways, both have its advantages and disadvantages. 1. With test database You mention that you need to write controller test. Testing controller is testing of almost top layer of your application flow. Controller depends on many...

Symfony2 FosUserBundle is loosing session

php,symfony2,fosuserbundle

Ok, i have noticed that fosuserbundle is loosing session with Symfony 2.6, so i switched to 2.3 and now it seems to be working. Thank you very much....

How to create a console command in Symfony2 application

php,symfony2,symfony-2.6,symfony-components,symfony-console

You are reading article about Console Component. This is slightly different than registering a command in your bundle. First, your class should live in Namespace Command, and it must include the Command prefix in classname. You've mostly done that. I will show you a sample command to grasp the idea...

Symfony / Sonata Admin: List form on Edit form

php,symfony2,sonata-admin,symfony-sonata,sonata

The fastest way to do what you are looking for is overriding the edit template. At your admin serivce declaration you can do so: services: sonata.admin.mail: class: %sonata.admin.category.class% tags: - { name: sonata.admin, manager_type: orm, group: "Categories", label: "Category" } arguments: - ~ - %skooli.category.class% - ~ calls: - [...

Symfony2 creating and persisting entity relationships

php,mysql,symfony2,doctrine2

When you create two entities with a one-to-one relationship, both entities need to be persisted either explicitly or by using cascade persist on one side of the relationship. You also need to explicitly set both sides of the relationship. Doctrine - Working with Associations - Transitive persistence / Cascade Operations...

Embedded form entity is not persisted

symfony2

I eventually found out where the problem was. Entity will be not persisted if there is no changed mapped fields. In my case I change just file field which is virtual field and not mapped to DB. Here is some information about this issue in documentation: The PreUpdate and PostUpdate...

Using Twig Variables inside config.yml

symfony2,twig

I suggest to use parameters.yml to define configuration params. parameters.yml serv: "http://www.server.de" config.yml twig: globals: serv: "%serv%" path: "%serv%/path/" ...

Symfony\Component\Config\Exception\FileLoaderLoadException] error

php,symfony2,twig,swiftmailer

As noted by redbirdo, you have = instead of : in your parameters.yml, which should be like this: parameters: database_driver: pdo_mysql database_host: 127.0.0.1 database_port: null database_name: symblog_db database_user: root database_password: null mailer_transport: "gmail" mailer_encryption: "ssl" mailer_auth_mode: "login" mailer_host: "smtp.gmail.com" mailer_user: "[email protected]" mailer_password: "xxxxxxxxx" secret: JaTylkoTrenuje ...

Twig: Allow HTML, but escape script

symfony2,twig,html-sanitizing

I would suggest adding a new Twig filter that fits your needs. It should look something like {{var | filter_black_listed() }} and in the filter logic you add something like class FilterBlackListedExtension extends \Twig_Extension { private $blacklistedTags = ['script', 'p']; public function getFilters() { return array( new \Twig_SimpleFilter('filter_black_listed', array($this, 'htmlFilter')),...

Get dates in “human readable” format

php,symfony2,date,fosrestbundle

If it's a DateTime() object, and I assume it is, you should be able to do: $entEmail->getCreatedAt()->format('Y-m-d H:i:s') More information on DateTime::format()...

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

php,symfony2,doctrine2,one-to-many,query-builder

When you specify multiple FROMs, later one will overwrite the previous ones. So, instead of writing: $queryBuilder ->select('pm', 'c') ->from('MySpaceMyBundle:PointsComptage', 'pc') ->from('MySpaceMyBundle:ParametresMesure', 'pm') ->leftJoin('MySpaceMyBundle:Compteurs', 'c', 'WITH', 'pm.compteurs = c.id') ->where('pc.id = c.pointsComptage ') ->andWhere('pc.id = :id') ->setParameter('id', $id); I believe you need something like this: $queryBuilder ->select('pc', 'c', 'pm') ->from('MySpaceMyBundle:PointsComptage',...

order attribute of an object in Synfony

php,symfony2

You could add a hidden field to you query that sorting things in the order that you wanted so that you don't need to process the complete ArrayCollection to sort. public function findByArticleInOrderOfState() { return $this->createQueryBuilder('c') ->select('c') ->addSelect(' CASE WHEN c.state = :state_new THEN 1 WHEN c.state = :state_viewed THEN...

Doctrine persist entity with inverse relation not work

symfony2,doctrine2,entity

SOLVE: I can solve it. The code of my entities thats ok. I change the controller function. First I create the product object, set the providerRate to null and them persist it. After I create the providerRate object and set the product object. public function ajaxNewProductAction() { $request = $this->getRequest();...

Symfony2 & PHPUnit - Access getContainer()

php,symfony2,login,parameters,phpunit

In the Symfony documentation How to Create a custom UserProvider, under 'Create a Service for the User Provider' it states: The real implementation of the user provider will probably have some dependencies or configuration options or other services. Add these as arguments in the service definition. So, rather than using...

Symfony 2 unable to pass entity repository to form

php,forms,symfony2,runtime-error

You have not included the Symfony EnityRepository class at the top of your form file so PHP is looking for it in the same directory as your form class. Hence the error message. Add this to your form class (or qualify EntityRepository inline): use Doctrine\ORM\EntityRepository; ...

Symfony2 Doctrine: ContextErrorException: Catchable Fatal Error: Object of class DateTime could not be converted to string

php,symfony2,doctrine2

Try using parameters in your QueryBuilder: $query = $this->createQueryBuilder('p') ->update('MyBundle\Products', 'p') ->set('p.published', ':dateNow') ->setParameter('dateNow', $dateNow) ->getQuery(); ...

Securing Symfony RESTful API consumed by angular front?

angularjs,api,symfony2,oauth,wsse

It all depends on what your requirements are. First of all, OAuth 2 is an authentication mechanism/spec which you can use in combination with sessions/bearer tokens/... This also applies for local accounts (since you want to do user registration). FOSAuthServerBundle is a bundle to implement the server-side of the OAuth2...

Transfert a Zend Project to Symfony

php,symfony2,zend-framework

There is no way* I can think of that would allow you to automatically transfer a project from Zend Framework 1 to Symfony2. You would have to start all over again, from scratch. My boss made me do that, there was this app written in C, Python, Perl, Bash and...

wkhtmltopdf on openSuSE: cannot connect to X server

php,symfony2,pdf-generation,twig,wkhtmltopdf

The solution for openSuSE: Install xvfb-run (on other *nix-systems maybe "xvfb") Change in the config part of the bundle (in app/config/config.yml) the binary option from "wkhtmltopdf" to xvfb-run -a -s "-screen 0 640x480x16" wkhtmltopdf Check the folder permissions. For german users: http://www.antondachauer.de/2015/06/19/wkhtmltopdf-unter-opensuse-mit-symfony-knpsnappybundle/...

Symfony Array Collection as Entity Property

php,symfony2,doctrine2

From your description it seems that Household and PetType has a cardinality of m-to-one; that means that an Household record could have only a PetType while a PetType could be associated to more than one Household record. From DB point of view that means foreign key into Household table. If...

Symfony form: disable “required” for a field from Twig

php,forms,symfony2,twig

You can set that in your form type to disable the field validation. ->add('test', null, array( 'required' => false )) If you want to disable it for the whole field you can try something like this: {{ form_start(form, { attr: {novalidate: 'novalidate'} }) }} ...

Symfony Entity query builder that checks for free spots

php,mysql,symfony2,doctrine2,dql

A having will work fine like so: $qb->select('s') ->from('FooChallengeBundle:Slot', 's') ->join('s.teams', 't') ->groupBy('s') ->having('count(t) < s.amount') ->getQuery() ->getResult(); ...

Include a method when object is serialized in JMS

symfony2,serialization,jmsserializerbundle

You need to set @VirtualProperty and @SerializedName. use JMS\Serializer\Annotation\VirtualProperty; use JMS\Serializer\Annotation\SerializedName; class Person { .... .... .... /** * @VirtualProperty * @SerializedName("foo") */ public function getFoo(){ return $this->id + 1; } .... .... .... } You can read more about it here: http://jmsyst.com/libs/serializer/master/reference/annotations Pay attention that this only works for...

Setting cookie for AngularJS translate locale using PHP

php,angularjs,symfony2,angular-translate

Set the cookie via PHP: <?php setcookie("_locale", "en"); ?> and retrieve it from angular with ngCookies: angular.module('app', ['ngCookies']) .controller('ExampleController', ['$cookies', function($cookies) { // Retrieving the cookie var locale = $cookies.get('_locale'); // Do something with locale }]); ...

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

css,symfony2,twig,assetic

From the Symfony docs and this section as well: Notice that in the original example that included JavaScript files, you referred to the files using a path like @AppBundle/Resources/public/file.js, but that in this example, you referred to the CSS files using their actual, publicly-accessible path: bundles/app/css. You can use either,...

Is it possible to share session between different PHP versions?

php,apache,symfony2,session,iis

Apparently setting session cookie domains does not work for top level domains (TLD), like .dev Changed my code to: ini_set('session.cookie_domain', '.local.dev'); and now I am able to set session variables on .local.dev website and read them in new.local.dev Both apps are physically in separate folders, operate from two IIS entries...

Silex - How to process template includes separately

symfony2,templates,include,silex

Yes. They are called sub requests. Read the documentation here.

Unique Entity Error message

api,symfony2,exception-handling,doctrine

The Symfony validator service can be used directly to validate any object for which validation constraints are defined. For example in a controller: $validator = $this->get('validator'); $errors = $validator->validate($test); To perform validation within a service you can pass the validator service into your service....

Why tree is invalid?

symfony2,doctrine2,tree,doctrine-extensions,stofdoctrineextensions

I found problem, when i delete a entity by $em->remove method, doctrine extension assume that onDelete=cascade for entity & change lft & rgt values of tree, then run query for removing of entity(and all children), but my entity have onDelete=restrict, then lft & rgt values are updated, but children is...

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

php,forms,symfony2,entity,symfony-2.6

Set data_class option for your InYourMindFriendType Checkout http://symfony.com/doc/current/reference/forms/types/form.html#data-class...

Dropzone.js and symfony formbuilder

javascript,php,symfony2,formbuilder

Ok I found the answer... It was simple as possible.. You need to just add a option: paramName: "form[file]" To Your dropzone configuration. ...

“Unable to open database file” error when trying to load Doctrine Data Fixtures in Symfony

symfony2,doctrine2,behat

As suggested in Symfony website, if you run into a kind of permissions issue, Mac users should use specific permissions on app/cache folder by running commands below: HTTPDUSER=`ps aux | grep -E '[a]pache|[h]ttpd|[_]www|[w]ww-data|[n]ginx' | grep -v root | head -1 | cut -d\ -f1` $ sudo chmod +a "$HTTPDUSER allow...

Symfony2 form builder without class check if multiple fields are empty

validation,symfony2,constraints,formbuilder

the easiest solution is to just set both as required ... but.. on post you could check as simple as if( empty($form->get('name')->getData()) && empty($form->get('dob')->getData())){ $form->addError(new FormError("fill out both yo")); // ... return your view }else { // ... do your persisting stuff } ... the symfony way would possibly be...

Symfony FOS editing/updating username/email

php,symfony2

I solved this out.. public function editAction(Request $request, $id) { $userManager = $this->get('fos_user.user_manager'); $form = $this-> createFormBuilder($user) ->add('username') ->add('email') ->add('save', 'submit') ->getForm(); $form->handleRequest($request); if ($form->isValid()) { $userManager->updateUser($user); } return $this->render('PRACTestBundle:Default:edit.html.twig', array('form' => $form->creaveView())); } ...

Symfony2 move app.php from web directory to root directory

symfony2

In your composer.json you have these lines: "extra": { "symfony-app-dir": "app", "symfony-web-dir": "web", You need to update those and run composer update to make your bootstrap.php.cache file ready for the new structure....

How can i view Result of Database from doctrine in twig

php,symfony2,doctrine2,twig

Firstly, the findBy() in your controller will always return an array, so your code will be clearer if you replace customerUser with customerUsers: $customerUsers = $this->getDoctrine() ->getRepository('FPMAppBundle:CustomerUser') ->findBy( array( "idUser" => $userId ) ); return $this->render( "FPMAllgemeinBundle:Start:companydata.html.twig", array( "customerUsers" => $customerUsers ) ); Then in your twig you could display...

Change role of one user no working with Symfony2

symfony2,fosuserbundle,roles

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...

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

php,symfony2,phpunit,functional-testing

You can use Crawler::filterXPath() to check for the presence or even absence of html elements matching all sorts of criteria. To check for the presence of a link I prefer to use the element id as that is most likely to remain constant. For example, if you modify your link...

Symfony Functional Testing: how to understand why the test fails (with a 500 Error)

php,symfony2,phpunit,functional-testing

May be these can help: there is a test.log file in app/logs folder, you can remove it, run the tests, when the error happens open the newly generated file, read what happend, that's it. Or you add DebugBundle to registerBundles method in AppKernel.php file, and use its dump() method, like...

Symfony/Twig radio style formbuilder

php,symfony2,twig,formbuilder

I solved this problem by editing, contoller: ->add('categoryId', 'entity', array( 'class' => 'MyBundle:Category', 'property' => 'name', 'expanded' => true, 'multiple' => false, 'choices' => $this->getDoctrine() ->getRepository('MyBundle:Category') ->findAll(), 'required' => true, )) And in my twig gallery: <div class="row"> {% for child in form.categoryId %} <div class="radio i-checks col-md-3"> <label>{{ form_widget(child,...

Jms serializer @JMS\Inline() annotation overrides an actual id

php,symfony2,doctrine2,jmsserializerbundle,jms-serializer

You should not expose the id from the detail when using inline. Source: https://github.com/schmittjoh/JMSSerializerBundle/issues/460#issuecomment-113440743...

AngularJS execute some action in all application instances

angularjs,symfony2

You can use angular.service Services Angular services are substitutable objects that are wired together using dependency injection (DI). You can use services to organize and share code across your app. click here for More details ...

Unable to configure Symfony (3rd party) bundle

php,symfony2,rss

I havent tried this bundle yet, but i think you need to tell doctrine that you want to save your newly created feed into the database: $feeds = new Feed; $reader->readFeed($url, $feeds, $date); $em = $this->getDoctrine()->getManager(); $em->persist($feeds); $em->flush(); return $this->render('default/index.html.twig'); UPDATE According to the docs if you want to use...

How adapt the path to the previous and next article

php,symfony2

If you have a variable defining active/inactive status, you can use a PHP "if" or "if/else" command to only perform your concatenation when the variable defining active status is of a certain value.

comparison operator is not working in twig

php,symfony2

try to not convert the dates to string with twigs date filter e.g {% set upcoming_days =daysdiff(event_startdate) %} instead of {% set upcoming_days =daysdiff(event_startdate)|date("d.m.y") %} ...

How to query in Doctrine2 WHERE = 'value from a related Entity'

php,json,symfony2,orm,doctrine2

This query worked for me: find the first entity by value: $postOwner = $em->getRepository('GabrielAppBundle:AuthBundle\LiveUser')->findOneByUsername('john'); Query the second entity then use first entity object as parameter $posts= $em->createQuery( "SELECT p FROM GabrielAppBundle:UploadPlugin\Post p WHERE p.postOwner = :postOwner" )->setParameter('postOwner',$postOwner); ...

ClassNotFoundException Symfony UserBundle

symfony2,fosuserbundle

When you try to clear cache but its not getting cleared you should use --no-warmup option, this will make sure that you cache is re-generated and cache is not warmed up only. I think this can help you: php app/console cache:clear --env=prod --no-warmup or php app/console cache:clear --env=dev --no-warmup ...

entities relations with doctrine (symfony 2)

symfony2

I wouldn't do it with intermediate tables, just in the case that I explain below, so... Patient could be in different hospitals databases - ManyToMany Patient must be in just one social security (In the same country) - ManyToOne Patient could be in different pharmacies databases - ManyToMany Patient just...

Symfony2: ajax call redirection if session timedout

ajax,symfony2,session

Found a working solution : Add a function in my global controller which check if session is still active and responds with "ok" if yes, "ko" if not. public function pingAction() { $securityContext = $this->container->get('security.context'); if ($securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED') || $securityContext->isGranted('IS_AUTHENTICATED_FULLY')) { return new Response("ok"); } return new Response("ko"); } and i...

avoiding container strings in dependency injection in symfony

php,symfony2,dependency-injection

If you're requesting the service from a controller, you can setup your controller to be a service too. Then you can pass the employee repository service to it using dependency injection. That way you will not have the string reference in the controller, but in the configuration. http://symfony.com/doc/current/cookbook/controller/service.html...

Symfony “No route found for ”GET /check.php" fresh install

php,symfony2,http-status-code-404,symfony-2.7

A fresh install of symfony does not have any routes. In your bundle you'll need to define the route for /blog. The file at /app/config/routing.yml should look something like this. my_bundle: resource: "@MyBundle/Resources/config/routing.yml" This will ensure the routes you setup in your bundles config are included. So in /src/MyBundle/Resources/config/routing.yml you...

How to write and use Monolog handlers and channels

php,symfony2,monolog,symfony-2.6

You can try that way, monolog: channels: ["testchannel"] handlers: test: # log all messages (since debug is the lowest level) level: debug type: stream path: "%kernel.logs_dir%/testchannel.log" channels: ["testchannel"] And in the controller you can get the logger and do your thing; class DefaultController extends Controller { public function indexAction() {...

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

php,forms,symfony2,doctrine

You could use a doctrine entity listener: https://symfony.com/doc/current/bundles/DoctrineBundle/entity-listeners.html http://doctrine-orm.readthedocs.org/en/latest/reference/events.html#entity-listeners And have something like this in it: public function postUpdateHandler(Vote $vote, LifecycleEventArgs $event) { if (null === $vote->getValue()) { // Following two lines could be avoided with a onDelete: "SET NULL" in Picture orm mapping $picture = $vote->getPicture(); $picture->removeVote($vote); $this->em->remove($vote);...

Logs an entire array using Monolog [closed]

php,symfony2,monolog,symfony-2.6

If you check the logger interface (https://github.com/php-fig/log/blob/master/Psr/Log/LoggerInterface.php) you will see all of the logging methods gets message as a string, thus you get a warning when you try to log with a variable type other than string. I tried to use a processor to format the array in a custom...

Setup VPS with a Symfony2 project from git repository

symfony2,vps

Here are my deployment steps: git clone project go to project directory php composer.phar install (and if composer is not in the project directory curl -sS https://getcomposer.org/installer | php) app/console doctrine:database:create app/console schema:update --force app/console assets:install web --symlink chmod 777 -R app/cache app/logs web/media/cache (I often use liip imagine, it...

display the name but insert the id whit entity field type

symfony2

An Entity field is the wrong thing to use in this case - the form will try to map an instance of the Technical class onto the Services's integer $techId field, which cannot work. You need to use a standard choice field and pass the list of (Technical entity) id...

Append inline scripts inside Twig layout block

php,symfony2,templates,twig,fosuserbundle

After the EDIT the situation is more clear. The behaviour you expect works with template inheritance only; it won't work with include, the way you have it in app/Resources/FOSUserBundle/views/Registration/register.html.twig. To do what you want, do one of the following: Place the inline JavaScript code from the javascript block of app/Resources/FOSUserBundle/views/Registration/register_content.html.twig...

Symfony 2: “No route found for ”GET /" - error on fresh installation

php,symfony2

Try http://localhost:8000/app/example Fresh installation has no routes for the root path "/"...

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

php,symfony2,doctrine,entity,bundle

Annotations have to be placed inside /** */ comment block, otherwise they are not recognized.

AppBundle's Best Practice and how-to go further

php,symfony2,doctrine2,entity

If you follow the same strategy as your existing entities, you need to define the four entities in the following files: src/AppBundle/Entity/ForumCategory.php src/AppBundle/Entity/ForumPost.php src/AppBundle/Entity/ForumSection.php src/AppBundle/Entity/ForumTopic.php Then, the namespace of each entity will be namespace AppBundle\Entity; However, when you have several related entities, it's better to create a subdirectory inside the...

Dependencies in forms Symfony2

php,forms,symfony2,events,entities

Create a form type CardAttributeValueType for CardAttributeValue entity, inside this form add fields depending on passed attribute type: class CardAttributeValueType extends AbstractType public function buildForm(FormBuilderInterface $builder, array $options) { $builder->addEventListener(FormEvents::PRE_SET_DATA, function(FormEvent $event) { $value = $event->getData(); $form = $event->getForm(); if (!$value) { return; } switch ($value->getCardAttribute()->getType()) { case 'text': $form->add('valueVarchar',...

Symfony change validation message globally

php,symfony2,symfony-2.3

The easiest way is to define an translations file. # app/Resources/translations/validators.es.yml This value should not be blank.: Campo obligatorio This value is not a valid email address.: e-mail no válido ...

Conflicts in routing in symfony between bundles

symfony2

Your app has a single routing configuration which can include other configurations. Probably app/config/routing.yml. That configuration file will include the routes for your bundles by using the resource key that can import routes from another routing.yml file or from annotations in a PHP controller. The order of those will determine...