Email user not required - symfony

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

Related

Api platform, prevent POST method when some datas are the same

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

How to auto fetch data and save into db from other api in api-platform

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.

Sonata admin – blank page on production when ModelManagerException is thrown

I have defined unique constraint on one property of my entity.
/**
* #var string
* #ORM\Column(type="string", length=10, unique=true)
*/
protected $customID;
In Sonata admin, when new object is created with same ID, blank page on production is shown (in dev production, I can see that ModelManagerException is thrown, which is expected result).
How can I display an error on production?
Maybe use https://symfony.com/doc/current/reference/constraints/UniqueEntity.html for that field and it will show validation error before saving so no exception will be thrown.
Example:
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* #ORM\Entity
* #UniqueEntity("customID")
*/
class YourEntity {}

Access control lists in Symfony2 using FOSUserBundle - adding roles to a user

I'm hoping this is more simple than the docs I've been reading.
I have a number of entities with ManyToOne relationships with a standard FOSUserbundle user entity that can login users, register them, logout etc.
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
public function __construct()
{
parent::__construct();
}
Each of my users can also have a number of pets. I.e. here's the cat entity (simplified):
class Cat
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* #ORM\ManyToOne(targetEntity="User")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
**/
private $user_id;
How should I add an access control list user role that defines if the user has any cats or not, and if they do, allows them onto the "cats only" part of my website.
Note (slightly related): I feel mildly retarded when it comes to database design using doctrine, I'll upvote anyone that can point me to a good tutorial / explanation of designing things with different kind of joins, especially if it's a in Symfony/Doctrine environment.
Well, since you haven't gotten anything else yet. I'll throw something out there but my experience is only moderate so far.
In the controller for your cats owners page, you could query if the user has any associated cat entities.
You need to add OneToMany/ManyToOne annotations to your user and cat class, and a variable for the associations. This you could review straight out of the doctrine section of the symfony2 book (If you are working with Symfony2 and haven't taken the time to read the book, that is the minimal level of knowledge to work with the full stack and I suggest you read it all). (Do you really need a entity class just for cat, you could have a pet entity with a "type" option.)
check the security context to ensure logged in, then query db.
$em = $this->getDoctrine()->getManager();
$ownersCats = $em->getRepository('PetsPetSiteBundle:Blog')->findBy(array('type'=>'cat'));
or for one result only
$ownersCats = $em->getRepository('PetsPetSiteBundle:Blog')->findOneBy(array('type'=>'cat'));
Once you have this result if it comes back false, you know he has no cats. Otherwise continue.
Obviously you could make this perform better by only querying for id's or something if you don't plan on using the entities on that page or just performing a count query and seeing if it's greater than 0?

Symfony: How do I annotate entity properties that are objects to get Doctrine to store a foreign key?

I'm still getting to grips with Symfony and Doctine and I appreciate this might sound overly simple.
I have at present two basic entities: WebSite (having id and canonicalUrl properties) and Job which has, as one property, a WebSite.
A Job has one WebSite; a WebSite can be referenced by many Jobs. Both are under the same namespace.
Relevant here is the Job entity:
/**
*
* #ORM\Entity
*/
class Job
{
/**
*
* #var integer
*
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
*
* #var WebSite
*/
protected $website;
}
In database terms, a persisted Job should be storing the id of the relevant WebSite.
Without any changes to the above, calling php app/console doctrine:migrations:diff generates a new migration for a table named Job with a single id field.
How do I annotate Job::website such that Doctrine knows to create an integer field and to get the value as the id of the Website object?
You must explicitly define the relationship. The shortest would be
/**
* #ORM\Entity
*/
class Job
{
/**
* #var WebSite
*
* #ORM\ManyToOne(targetEntity="Website")
*/
protected $website;
}
However, should you find yourself wanting to tweak the relationship to better suit your needs, have a look at the annotation reference (ManyToOne and JoinColumn for this particular case). There's also quite a comprehensive article about association mapping, which you might find interesting.

Resources