I have a video entity that only contains a video from YouTube. To do this, I have to add a constraint in the entity with an assert, I tried "Range" with minimum: https://youtube.com/watch?v= and by specifying the string group. It’s no working! Help me! Here is the code of the entity:
/**
* #ORM\Column(type="string", length=255, nullable=true)
* #Assert\Range(
* min = "https://youtube.com/watch?v=",
* groups = {"string"}"
* )
*/
private $video;
You should try to solve this task with a custom validation constraint. It allows your code to assert that a request parameter contains https://youtube.com/watch?v= or even to check that video url is a valid video (with request to a Youtube API with a help of Guzzle client or Youtube API library). More info see in the official Symfony docs. https://symfony.com/doc/current/validation/custom_constraint.html
Related
I'm using symfony with API PLATFORM to create a contacts share system :
One User can share one or many contacts to one or many other users.
I created ContactShare entity :
/**
* #ApiResource()
* #ORM\Entity(repositoryClass=ContactShareRepository::class)
*/
class ContactShare
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\OneToMany(targetEntity=Contact::class, mappedBy="contactsToShare")
*/
private $contacts;
/**
* #ORM\ManyToOne(targetEntity=AppUser::class, inversedBy="shareContactsOwner")
*/
private $sender;
/**
* #ORM\OneToMany(targetEntity=AppUser::class, mappedBy="shareContactsReceivers")
*/
private $receivers;
...
...
}
When i tested with postman i can post a new share :
My question is :
How to add constraints or validators to prevent the POST method of contact share if we
share the same contacts to the same user, and Prevent POST method if we send the same
contact to a duplicated user ?
You can create a custom validator and call valid as shown here.
If validation returns one (or more) error, you should return some kind of response with proper HTTP status code (4xx?).
Moreover, if this validation should be performed only for this API call (I think this is a domain requirement, so it should be always applyed, but it's only a guess of mine) you can take advantage of validation groups.
UPDATE: API Platform seems to take care of this on your behalf, so you don't need to call explicitly valid
I'm beginner php, but in my project require fetch data from jira api. I'm using api-platform and I want to systeme can auto fetch and auto save data from jira api into entiy after a specified period of time. I hope everyone can help me. My entity is here:
/**
* #ApiResource()
* #ORM\Entity(repositoryClass="App\Repository\JiraRepository")
*/
class Jira
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $key;
/**
* #ORM\Column(type="string", length=255)
*/
private $name;
/**
* #ORM\Column(type="string", length=255)
*/
private $projectTypeKey;
/**
* #ORM\Column(type="string", length=255)
*/
private $avartarUrl;
I want to auto save into that. How to create an automatic action in symfony? Help me. Thank you very much
Well it's really hard to say anything, because there is little known about your projects and what type of architecture and best practices you use in your project. I can help brainstorm into what you need to make this possible:
At first you need to have an console command, which will be launched via cron tasking (that should answer your specified period of times)
Inside your command, you will need to launch a service, for example: ApiService..., in there you will have to write a logic in which you will fetch your jira data (lot's of options here, provided library, curl request, etc.). (I'd recommend, to have the endpoints written in an .env file, because you will need to authenticate, before getting the data each time.)
After you get your specified data, you should loop your data, and then call a factory and pass the data you need which will create your entity, bring back the entity in the service and then to persist and flush into the database...
Hope it helps.
I am facing a weird problem relating to UUIDs.
I have developed a REST API using Symfony2+FOSRestBundle+JMSSerializer. As I need to update some tables from two sources I thought of using UUID as primary key for one entity.
I did a doctrine:mapping:import to generate entities in my Symfony project. Everything correct. I ended up with the following entity (only exposing the key field and generated getter for simplicity):
<?php
namespace Stardigita\TgaAPIBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* TgaBookings
*
* #ORM\Table(name="tga_bookings", indexes={[...]})
* #ORM\Entity
*/
class TgaBookings
{
/**
* #var string
*
* #ORM\Column(name="book_cd_booking_UUID", type="blob", length=16, nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $bookCdBookingUuid;
/**
* Get bookCdBookingUuid
*
* #return string
*/
public function getBookCdBookingUuid()
{
return $this->bookCdBookingUuid;
}
...
No setter was generated. I can still do it myself and I will, as I will need to know the key beforehand.
The data for this field is correctly stored in the table as a BINARY(16). When I recover the data calling the REST GET method, I get this:
[
{
"book_cd_booking_uuid": "Resource id #1244",
"book_cd_booking": 8,
....
My question is: how can I get the actual data from the field?
I suppose something has to be done in the field getter, but I tried some solutions without any success.
Thanks.
UPDATE:
I've managed to get the actual data logged, modifying the getBookCdBookingUuid method this way:
/**
* Get bookCdBookingUuid
*
* #return string
*/
public function getBookCdBookingUuid()
{
return bin2hex($this->bookCdBookingUuid);
}
and changed the type to "guid" in the property annotation:
/**
* #var string
*
* #ORM\Column(name="book_cd_booking_UUID", type="guid", length=16, nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $bookCdBookingUuid;
I have represented the hex UUID correctly in the log before returning the results in the controller:
[2014-11-03 19:52:07] app.ERROR: 1046684e5f6711e4a09f00089bce936a [] []
But still getting an exception relating UTF invalid characters:
request.CRITICAL: Uncaught PHP Exception RuntimeException: "Your data could not be encoded because it contains invalid UTF8 characters." at /var/www/tga_api/vendor/jms/serializer/src/JMS/Serializer/JsonSerializationVisitor.php line 36 {"exception":"[object] (RuntimeException: Your data could not be encoded because it contains invalid UTF8 characters. at /var/www/tga_api/vendor/jms/serializer/src/JMS/Serializer/JsonSerializationVisitor.php:36)"} []
Also I got no response from the service. A 500 error is returned.
Please, I need to solve this issue. Any ideas are welcome.
Thanks.
GeneratedValue
I notice you're using the annotation #ORM\GeneratedValue(strategy="IDENTITY") for the UUID property. IDENTITY means the database should/will use auto-increments, which shouldn't be done when using UUIDs. Please change it to #ORM\GeneratedValue(strategy="NONE") or remove it completely.
Conversion
The string form of a UUID (like 01234567-89ab-cdef-0123-456789abcdef) should be converted to binary when it's persisted in the database, and converted back when fetched from the database.
The easiest way to do this is to introduce a custom type. See here for an example.
Bugs
Doctrine (even master/2.5) has some issues with using UUIDs in associations. I'm attempting to fix these issues in PR #1178.
If you need UUIDs in associations and can't wait till it's fixed, then use regular integer ids and have the UUID is a separate column.
Is it possible to create custom metadata information in the entities? Something that would use the already present functionality of using either Annotation, yml or xml to store metadata about the entity.
Example:
/**
* #var string
*
* #ORM\Column(name="text", type="text")
* #CUSTOM\Meta(key="value") // <-- Extra information
*/
protected $text;
For what I've been researching, it seems that I should use the functionality of ClassMetadataFactory. Is it possible, or would I have to make it from scratch?
I would like set email to not required on my User entities. How do what ?
I've searched in FOSUserBundle/config/ but i don't find any "required" parameter about email.
Following Tib's answer, here is the way I did it. It's working fine :
/**
* User
*
* #ORM\Table(name="user")
* #ORM\Entity
* #ORM\AttributeOverrides({
* #ORM\AttributeOverride(name="email", column=#ORM\Column(type="string", name="email", length=255, unique=false, nullable=true)),
* #ORM\AttributeOverride(name="emailCanonical", column=#ORM\Column(type="string", name="email_canonical", length=255, unique=false, nullable=true))
* })
*/
class User extends BaseUser {
// ...
}
EDIT :
The previous solution is easy to implement and was working fine, but after updating Symfony to version 2.1.8 and without changing anything in my app, generating entities failes throwing a Doctrine mapping exception (Invalid field override ...)
In spite of loosing a lot of time trying to solve that issue, I was just stucked.
Then I finally realized that FOSUserBundle provides lot of features I don't use, but doesn't really fit my needs, which are quite basic.
I need to disable email requirement because my app user management is "software like" : no registration, no email sending, no profil, user and roles managed only by admin, etc...
I was adapting a tool not designed for my needs. So I decided to make my own implementation of Symfony security.
It is a little more work, but it's not very difficult and the result is far better and more flexible than adapting FOSUserBundle. Of course, for a "classic" website or web app, FOSUserBundle is the best.
If you are in this case too, I suggest you to do so. Here is the doc to begin : Security in the Book and Security in the CookBook
I hope this can help you.
Sorry for my poor english, I hope it is intelligible
Check this PR https://github.com/doctrine/orm-documentation/pull/117/files and look at #AttributeOverrides
You need to override following methods in the entity User.
class User extends BaseUser // inheritance from fos
{
/**
* #var string
* #ORM\column(type="string", name="email", length=255, unique=true, )
* #Assert\Email(
* checkMX = true
* )*/
protected $email
}
}
You need to change Table definition to:
class User extends BaseUser // inheritance from fosUserBundle
{
/**
* #var string
* #ORM\column(type="string", name="email", length=255, unique=false, nullable=true )
*/
protected $email
}
}
Same thing is needed for emailCanonical attribute.
If that not pass. You will need to copy entire model from FOS into your bundle and then change it as I wrote.
check the doc: https://github.com/FriendsOfSymfony/FOSUserBundle/blob/1.2.0/Resources/doc/doctrine.md
Regards Max