Creating Custom Field with FOSUserBundle - symfony

I want to add an address and telephone number using FOSUserBundle. How can I add a Custom fields, with FOSuserBundle, to have a profile that contains address and telephone number....

Create an own user bundle and in the MyCompanyUserBundle.php you set
public function getParent(){
return 'FOSUserBundle';
}
Then in your new UserBundle you create a User entity and let it extend from the base user of the FOS user bundle:
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="user")
*/
class User extends BaseUser
{
public function __toString(){
return $this->firstname . ' ' . $this->lastname . ' (' . $this->email . ')';
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
}
EDIT
Set the user in the config as well:
fos_user:
db_driver: orm
firewall_name: main
user_class: MyCompany\UserBundle\Entity\User

the problem is in :
when i follow the symfony documentation:https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/Resources/doc/index.md in step a) Doctrine ORM User class
i have created a folder doctrine contains User.orm.yml:
src/Acme/UserBundle/Resources/config/doctrine/User.orm.yml
Acme\UserBundle\Entity\User:
type: entity
table: fos_user
id:
id:
type: integer
generator:
strategy: AUTO
this file crush any update in your entities and update of your database shemea .The solution is to delete this folder.

You don't have to add custom fields but you have to create your own user model.
Read the doc, all is explained:
https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/Resources/doc/index.md#step-3-create-your-user-class

Related

Conditional resetting email templates in FosUserBundle Symfony Framework

I have a project in symfony using FosUserBundle and PugxMultiUserBundle because I need 2 user types.
There are CmsUsers and Platform players.
I need a way to have Fos email templates (resetting template,registering template etc.) per user type.
One reset template for CmsUser and another template for Players.
Same thing for Registering.
The problem occurs because these templates are configured in config.yaml
fos_user:
db_driver: orm
firewall_name: api
user_class: PanelBundle\Entity\User
from_email:
address: '%fos_from_address%'
sender_name: '%fos_from_name%'
service:
mailer: api.custom_mailer
user_manager: pugx_user_manager
registration:
confirmation:
enabled: true
template: 'ApiBundle:Email:confirm.email.twig'
resetting:
retry_ttl: 1800 # After how much seconds (30 min) user can request again pass reset
token_ttl: 604800 # After how much seconds (1 week) user token is valid (inactive in user mailbox)
email:
template: 'ApiBundle:Email:resetting.email.twig'
I need a way to config or implement this in conditional way.
If the user type is CmsUser load this template, else load another.
<?php
namespace ApiBundle\Mailer;
use FOS\UserBundle\Mailer\TwigSwiftMailer as BaseMailer;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class CustomUserMailer extends BaseMailer
{
public function __construct(\Swift_Mailer $mailer, UrlGeneratorInterface $router, \Twig_Environment $twig, array $parameters)
{
parent::__construct($mailer, $router, $twig, $parameters);
}
/**
* #param string $templateName
* #param array $context
* #param string $fromEmail
* #param string $toEmail
*/
protected function sendMessage($templateName, $context, $fromEmail, $toEmail)
{
// Create a new mail message.
$message = \Swift_Message::newInstance();
$context['images']['top']['src'] = $message->embed(\Swift_Image::fromPath(
__DIR__.'/../../../web/assets/img/email/header.jpg'
));
$context['images']['bottom']['src'] = $message->embed(\Swift_Image::fromPath(
__DIR__.'/../../../web/assets/img/email/footer.jpg'
));
$context = $this->twig->mergeGlobals($context);
$template = $this->twig->loadTemplate($templateName);
$subject = $template->renderBlock('subject', $context);
$textBody = $template->renderBlock('body_text', $context);
$htmlBody = $template->renderBlock('body_html', $context);
$message->setSubject($subject);
$message->setFrom($fromEmail);
$message->setTo($toEmail);
$message->setBody($htmlBody, 'text/html');
$message->addPart($textBody.'text/plain');
$this->mailer->send($message);
}
}
Hy,
if you can desactivate the FosUserBundle sending emails and create a custom listener who made the same things, get the code of the FosUserBundle listeners and adapt it (ex: add a if($user instanceof CmsUser) etc.) to send custom emails per type.
Check the listeners (EmailConfirmationListener and ResettingListener) in /vendor/friendsofsymfony/user-bundle/EventListener

How to remove Form Field From FOSUserBundle Symfony2.8?

I have install FOSUserBundle in my Symfony project. Now I want to Remove Registration Form Field that by default provide by FOSUserBundle.
Registration Form Fields Are :
User Name
Email Id
Password
Repeat Password
Now I don't want Email Field when User are register so I override Registration form in my bundle.
\\ Front\FrontBundle\Form\RegistrationType.php
<?php
namespace Front\FrontBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
class RegistrationType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->remove('email'); // here I code for remove email field.
}
public function getParent()
{
return 'FOS\UserBundle\Form\Type\RegistrationFormType';
// Or for Symfony < 2.8
// return 'fos_user_registration';
}
public function getBlockPrefix()
{
return 'app_user_registration';
}
// For Symfony 2.x
public function getName()
{
return $this->getBlockPrefix();
}
}
then I change config.yml and services.yml file
\\ App/config/config.yml
fos_user:
db_driver: orm
firewall_name: main
user_class: Front\FrontBundle\Entity\User
registration:
form:
type: Front\FrontBundle\Form\RegistrationType
\\app/config/services.yml
services:
app.form.registration:
class: Front\FrontBundle\Form\RegistrationType
tags:
- { name: form.type, alias: app_user_registration }
So After done with this Email Field remove from my Registration Form but when I submit form after filling username , password , repeat password it's give me any error that The email is not valid.
So I need to change any other file to remove email validation with email field ?
Thanks.
you can remove the field as you have done, but you must make sure that there is no residual server side validation that requires it.
how to do this depends on how you've extended the FOS User class (or if you have).
annotated constraints look like this for instance (from the docs)
class Author
{
/**
* #Assert\NotBlank() <--- remove this
*/
public $name;
}
if youv'e extended the class, you can remove it from your own member definition.
If you've not extended it, extend it and then dont put in the validation constraint.
Or failing everything else (and I think this is hacky), issue a default in the controller before you call isValid().
public function someAction(Request $request) {
// ...
$user = new User();
// fill empty value
$user->setEmail('blank#blank.blank');
// form stuff here
// ...
if ($form->isValid()) {
// do some stuff
}
return $this->render(blahblahbal);
}

Error while generating doctrine entities with FOSUser Bundle in Symfony2

I'm using FOSUser bundle and everything went ok until I tried to create the database entities, I get this error:
It has nothing to do with the bug in Symfony 2.5, I'm using version 2.7
Case mismatch between loaded and declared class names: App\UserBundle\Entity\user vs App\UserBundle\Entity\User
This is my config file for fos:
fos_user:
db_driver: orm # other valid values are 'mongodb', 'couchdb' and 'propel'
firewall_name: main
user_class: App\UserBundle\Entity\User
My classes and namespaces they seem to have the right caps, I don't know why this is happening. I tried to clear the cache, no errors but didn't work.
The user class is App/UserBundle/Entity/User.php, here's the content:
<?php
namespace App\UserBundle\Entity;
use FOS\UserBundle\Model\User as BaseUser;
/**
* User
*/
class User extends BaseUser
{
public function __construct()
{
parent::__construct();
}
}
What happens if you amend your User entity to appear as below (replacing user_table with intended table name)?
namespace App\UserBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use FOS\UserBundle\Model\User as BaseUser;
/**
* User
* #ORM\Table(name="user_table")
* #ORM\Entity
*/
class User extends BaseUser
{
public function __construct()
{
parent::__construct();
}
}
I found the problem, I was using yaml for the entity definition and the filename was user.orm.yml instead of User.orm.yml.

Extend SonataUserBundle Entity

I want to extend default user entity attributes. In database after extending FOSUserBundle with SonataUserBunle there are 2 tables for storing users: fos_user and fos_user_user. I want to extend fos_user
Here is app/AppKernel.php:
new Sonata\UserBundle\SonataUserBundle('FOSUserBundle'),
new Application\Sonata\UserBundle\ApplicationSonataUserBundle(),
in app/config.yml file I set:
fos_user:
db_driver: orm<br>
firewall_name: main<br>
user_class: Acme\DemoBundle\Entity\User<br>
group:<br>
group_class: Application\Sonata\UserBundle\Entity\Group<br>
sonata_user:
security_acl: true
class:
user: Acme\DemoBundle\Entity\User
admin:
user:
class: Acme\DemoBundle\Admin\UserAdmin
parameters:
sonata.user.admin.user.class: Blogger\BlogBundle\Admin\UserAdmin
sonata.user.admin.user.entity: Blogger\BlogBundle\Entity\User
doctrine:
orm:
auto_mapping: auto
SonataUserBundle is created in src/Application/Sonata/UserBundle
To override SonataUserBundle, i extended UserAdmin by creating another UserAdmin class in src/Acme/DemoBundle/Admin/UserAdmin and all works fine
Now I want to extend User entity (fos_user table) to add new attributes.
Here is my Acme/Demo/Entity/User.php that I want to extend the default User entity
namespace Acme\DemoBundle\Entity;
use FOS\UserBundle\Entity\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="fos_user")
*/
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/*
* #ORM\Column(type="string", name="newAttribute")
*/
protected $newAttribute;
public function __construct()
{
parent::__construct();
// your own logic
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
}
What should I do to extend default fos_user table with php app/console doctrine:generate:entities Acme/DemoBundle
I've read many posts about this issue but none of the solutions helped me. I tried to extend Model class instead of Entity class but also nothing changed
You don't have to.
new Sonata\UserBundle\SonataUserBundle('FOSUserBundle')
Here your are telling the SonataUserBundle to use the FOSUserBundle as well.
Then in your User entity you set:
use Sonata\UserBundle\Entity\BaseUser as BaseUser;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="User")
*/
class User extends BaseUser
Because you have said to the SonataUserBundle "use the fosuserbundle" and you extend from the sonata user bundle user entity he's gonna "merge" those 2 models into 1 and add your custom fields from in your user entity as well.

Is it possible to use a custom User Provider to sign a comment when using FOSCommentBundle?

I am using a custom UserProvider for the authentication in my Symfony2.1 application. I would like to use FOSCommentBundle to implement comments. But when it comes to sign the comment by the comment's author, I am stuck.
Basically, I have two databases. One from which I can retrieve users' credentials (username, salt, password,...) but which I can't make any modification, the other one I can use to store the users information (like her/his comment(s)) in an User entity.
When I am mapping the Comment entity with this User entity, there is a problem since FOSCommentBundle retrieves the entity which implements the UserInterface (in my security bundle) and not this User entity.
Basically, is there a way to tell FOSCommentBundle to retrieve another User entity than the one used for Authentication?
Thanks
Did you try FOSUserBundle integration with FOSCommentsBundle?
You need to implement SignedCommentInterface like this.
<?php
// src/MyProject/MyBundle/Entity/Comment.php
namespace MyProject\MyBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use FOS\CommentBundle\Entity\Comment as BaseComment;
use FOS\CommentBundle\Model\SignedCommentInterface;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* #ORM\Entity
*/
class Comment extends BaseComment implements SignedCommentInterface
{
// .. fields
/**
* Author of the comment
*
* #ORM\ManyToOne(targetEntity="MyProject\MyBundle\Entity\User")
* #var User
*/
protected $author;
public function setAuthor(UserInterface $author)
{
$this->author = $author;
}
public function getAuthor()
{
return $this->author;
}
public function getAuthorName()
{
if (null === $this->getAuthor()) {
return 'Anonymous';
}
return $this->getAuthor()->getUsername();
}
}

Resources