api,symfony2,exception-handling,doctrine , Unique Entity Error message


Unique Entity Error message

Question:

Tag: api,symfony2,exception-handling,doctrine

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 send the right error status with the right error message.

When I insert a duplicate entry in the database, I would like to get the message and an exeption relative to the fact it is a duplicate. Instead I get a 500 error with the SQL Message.

{
"error": {
    "code": 500,
    "message": "Internal Server Error",
    "exception": [
        {
             "message": "An exception occurred while executing 'INSERT INTO  .... \n\nSQLSTATE[23505]: Unique violation: 7 ERROR:  duplicate key value violates unique constraint \"uniq_1d1c63b3aa08cb10\"\nDETAIL:  Key (login)=(bast) already exists.",
            "class": "Doctrine\\DBAL\\DBALException",
            "trace": [

Here is where I get the 500.

    $test = new Utilisateur();
    $test->setLogin('test');

    $manager = $this->getDoctrine()->getManager();
    $manager->persist($test);
    $manager->flush();

How can I retrieve the message "UNIQUE ERROR MESSAGE" ?


Answer:

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.


Related:


How to make the Twitter API returns me over 800 tweets


api,twitter,timeline,tweets,home
How to make the Twitter API (home_timeline) returns me over 800 tweets? For example applications like tweetbot how do it to have more updates in the 3000 home timeline? I think that using a cache system but which one?

Symfony2: changing the request class and updating the test environment


php,symfony2,request,phpunit
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...

Symfony one-to-one, unidirectional relation


symfony2,doctrine2
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...

square connect api batch processing


api,batch-processing,square,square-connect
I need assistance with batch processing, especially in adding tax codes to items. I'm experimenting with the square batch processing feature and my sample cases are create 2 items and add the tax code to them. In all 4 requests - 2 for creating item, 2 to 'put' the tax...

Unique Entity Error message


api,symfony2,exception-handling,doctrine
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...

REST api : correctly ask for an action


api,rest,endpoint
I'm currently working on a REST api. I've read a few times how to handle endpoints the right way, using the protocol (post, put, ...) to define which action should be made. Let's say I have a list of quotes. I have : a GET endpoint /quotes that let me...

Using Graph API Explorer gets friends list but my own app doesn't . (Graph API Explorer token v.s App Token)


facebook,api,facebook-graph-api
I am trying to get my friends list in my app. If I use the access token in my Graph API Explorer console and hit the url. https://graph.facebook.com/v2.3/me?access_token='GraphAPIToken'. I am able to get the complete friends list. If I try using the SDK or any library like fbgraph for nodejs...

Set Auth Token manually for different firewall


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

Symfony 2 unable to pass entity repository to form


php,forms,symfony2,runtime-error
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...

REST API with token based authentication


angularjs,codeigniter,api,rest,token
I want to develop a web site with AngularJS. On the backend side I will use Codeigniter REST framework. I have some security issues and I don't want to start developing without fixing them on my mind. I don't want to use something like api key because it will be...

ClassNotFoundException Symfony UserBundle


symfony2,fosuserbundle
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?...

Use higher API level in android with an external library


java,android,api,android-studio,material-design
Would it be possible to import an external library (.jar file) in an android project containing the features of API level 21, and then use them in my application with a minimum sdk version set to say like 17? I'm really into Matierial Design but as Google states, "To use...

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


css,symfony2,twig,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...

Validation of a form before submission


php,validation,symfony2,form-submit
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...

Force Uppercase on Symfony2 form text field


php,forms,symfony2
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' =>...

Setup VPS with a Symfony2 project from git repository


symfony2,vps
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...

Logs an entire array using Monolog [closed]


php,symfony2,monolog,symfony-2.6
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? http://symfony.com/doc/current/cookbook/logging/monolog.html https://www.webfactory.de/blog/logging-with-monolog-in-symfony2 ...

Removing Alert When Using DeleteFile API


vb.net,vba,api,delete
I'm writing a VBA application which involves looping a large number of directories recursively. I am using the FindFirstFile API to to achieve this, as it offers a substantial performance boost over the FileSystemObject. In order to remove the FSO from my code entirely, I need a routine to delete...

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


php,symfony2,doctrine,entity,bundle
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; /*...

Stuck with nested serializer using Django Rest Framework and default user


django,api,rest,django-rest-framework,serializer
The models and serializers are described in the pastebin: http://pastebin.com/ZxzxWY7V In my database I have a user which also has a member profile and a set of credentials attached to it. Now... when I run this as is and try to pull a user using the AuthUserModelSerializer I get the...

Ruby API Call Page Issue


ruby-on-rails,ruby,json,api,httparty
This might be a basic issue but very common so it might be helpful to other people in the future. I use HTTParty to make a get request to an API, which returns some information, something like this: { datapath: "blah-blah.blah.blah", success: true, info: { row_limit: 500, total_results: 2700, total_pages:...

Symfony2/Twig - iterate over select options


php,symfony2,twig
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...

Update session in symfony2 for shoppingg cart


php,symfony2,symfony-2.1,php-5.3,symfony-2.3
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'];...

Ruby on Rails posting to an API using javascript via a proxy


javascript,ruby-on-rails,ruby,xml,api
I'm very new to Ruby on Rails and I'm hoping this will be a quick fix. I have a very simple form (firstname, surname, email) that needs to post XML to an API on another domain. Everything on our site is clientside javascript so I would like to post to...

Give port number and passed parameters in WSO2


java,api,wso2,wso2-am,api-manager
I am trying to learn WSO2 but have been stuck at a minor step which i believe should be quite easy to do. While creating a new api i need to give the production endpoint. What i want to give is the url along with the port as well. So...

Link to another resource in a REST API: by its ID, or by its URL?


json,api,rest,api-design,hateoas
I am creating some APIs using apiary, so the language used is JSON. Let's assume I need to represent this resource: { "id" : 9, "name" : "test", "customer_id" : 12, "user_id" : 1, "store_id" : 3, "notes" : "Lorem ipsum example long text" } Is it correct to refer...

Symfony/Twig radio style formbuilder


php,symfony2,twig,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">...

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

Symfony2 creating and persisting entity relationships


php,mysql,symfony2,doctrine2
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...

CORS, Client vs. Server & Rails API GET Request


ruby-on-rails,ruby,api,curl,client
I've built a GET Rails API that checks for an access token and that the registered request.env["HTTP_X_REAL_IP"] matches the IP address that is registered within the admin panel of the app. Example request: https://staging.mysite.com/api/v1/products?access_token=7b9f3cddd3914a6f45fa692997fe6dc9 The API works great when I'm making requests from a server by curling the request or...

Symfony\Component\Config\Exception\FileLoaderLoadException] error


php,symfony2,twig,swiftmailer
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/symblog.dev/app/config/parameters.yml (which is being imported from "/opt/lampp/htdocs/symblog.dev/app/config/config.yml")....

Unable to configure Symfony (3rd party) bundle


php,symfony2,rss
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...

Blockchain receive API with same address


api,bitcoin,blockchain
I need to accept bitcoins on my website (PHP). I'm using blockchain and i have read the api: https://blockchain.info/api/api_receive Is quite simple but i have some questions, but first i will try to explain what i need. Client send bitcoins to my wallet (Any amount they want) Server will be...

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


php,forms,symfony2,doctrine
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...

Is there any way to find out when an album got added to spotify with the web api?


javascript,api,web,timestamp,spotify
My usecase is to present the latest added album of an artist (regardless of releasedate). I use the https://api.spotify.com/v1/artists/[artistId]/albums to get the albums but I can't find any information about how the response is ordered. Is it random or actually sorted by the date the album got added to spotify?...

How to write and use Monolog handlers and channels


php,symfony2,monolog,symfony-2.6
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...

Inbox api use them to tag relevant mails just like inboxsdk.com


python,api,google-inbox
I tried using newly released Inbox api to sort out and tag my mails, but I am stuck at categorising mails after I had successfully logged in using api.

Deserializing or parse XML response in Symfony2


php,xml,symfony2,deserialization,jmsserializerbundle
I am calling a API method through cURL and I got this response: <?xml version="1.0" encoding="UTF-8"?> <jobInfo xmlns="http://www.force.com/2009/06/asyncapi/dataload"> <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>...

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


php,symfony2,doctrine2
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") *...

Symfony change validation message globally


php,symfony2,symfony-2.3
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...

Symfony Entity query builder that checks for free spots


php,mysql,symfony2,doctrine2,dql
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...

wkhtmltopdf on openSuSE: cannot connect to X server


php,symfony2,pdf-generation,twig,wkhtmltopdf
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...

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


php,symfony2,routing,twig,url-routing
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...

How adapt the path to the previous and next article


php,symfony2
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...

IOS Use Core Data Only in Specific Parts of an app


ios,api,core-data
I'm new to Core Data and trying to use it for persisting objects for offline support in an app communicating with JSON Back-end. I was using NSObjects for my models and now use NSManagedObjects. I only need to save these server objects in a few parts of the app, and...

Symfony2: ajax call redirection if session timedout


ajax,symfony2,session
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...

Using crontab to call wget every 5 minutes


php,symfony2,crontab,wget
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...

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


php,symfony2,phpunit,functional-testing
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...

Return value -Java API design VS. C API


java,api
I used C a lot before and now use Java. I have a question of API design in JAVA. In C, I always use int as a meaningful return value, and put multiple objects(some of which will be changed) in arguments. e.g, int foo(int x, int y, int *result) {...