Magento2 Attribute Group Name from Attribute Collection - attributes

I need Attribute Group Name from Attribute Collection associated with attribute Id. I have Aattribute Set ID.
Thanks!

/**
* #var \Magento\Eav\Model\ResourceModel\Entity\Attribute\Group\CollectionFactory
*/
protected $_groupCollection;
public function __construct(
\Magento\Eav\Model\ResourceModel\Entity\Attribute\Group\CollectionFactory $groupCollectionFactory
)
{
$this->_groupCollection = $groupCollectionFactory;
}
/**
* #param $attributSetID
* #return array
*/
public function getAttributeGroupName($attributeSetID){
$groups = $this->_groupCollection->create();
$groups->setAttributeSetFilter($attributeSetID);
$groupData = [];
/* #var $group \Magento\Eav\Model\Entity\Attribute\Group */
foreach ($groups as $group) {
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$attributeCollection = $objectManager->create('Magento\Eav\Model\ResourceModel\Entity\Attribute\Collection');
$attributeCollection
->setAttributeGroupFilter($group->getId())
->setAttributeSetFilter($attributeSetID);
foreach ($attributeCollection->getAllIds() as $attributeId) {
$groupData[$attributeId] = $group->getAttributeGroupName();
}
}
return $groupData;
}

Related

ES5 how to implement .Net IEqualityComaparer on data class for comparisons?

When I want to use a custom type T as hash key in .Net, I implement IEqualityComparer and pass it to hash map like Dictionary or HashSet, when adding new item, the GetHashCode and Equals method will be called to check whether two T instance are same.
for example, I have a immutable data class Foo:
sealed class Foo
{
public Foo(int field1, string field2)
{
Prop_1 = field1;
Prop_2 = field2;
}
public int Prop_1 { get; }
public string Prop_2 { get; }
}
and FooEuqalityComparer:
sealed class FooEuqalityComparer : IEqualityComparer<Foo>
{
public bool Equals(Foo x, Foo y)
{
return x == null ? y == null :
x.Prop_1 == y.Prop_1 &&
x.Prop_2 == y.Prop_2;
}
public int GetHashCode(Foo obj)
{
if (obj == null)
return 0;
return obj.Prop_1.GetHashCode() ^ obj.Prop_2.GetHashCode();
}
}
test:
var set = new HashSet<Foo>(new FooEuqalityComparer());
var foo1 = new Foo(1, "foo 1");
var not_foo2 = new Foo(1, "foo 1");
var foo3 = new Foo(3, "foo 3");
set.Add(foo1);
set.Add(not_foo2);
Assert.AreEqual(1, set.Count);
Assert.AreSame(foo1, set.Single());
set.Add(foo3);
Assert.AreEqual(2, set.Count);
How can I do it in nodejs?
Overwrite toString() is not a option because I want to keep reference to that object as key inside map.
After some search, I realized that javascript or ECMAScript use SameValueZero algorithm to compare objects, the best way still is using string as key.
so I use two map to achieve this:
class ObjectKeyMap {
/**
* #param {Object[]} keys -
* #param {function():string} keys[].getHashCode -
* #param {function(Object):T} valueSelector -
*
* #typedef {Object} T
*/
constructor(keys, valueSelector) {
const keyReferences = {};
keys.forEach(it => {
keyReferences[it.getHashCode()] = it;
});
this.keyReferences = keyReferences;
this.map = new Map(keys.map(it => [it.getHashCode(), valueSelector(it)]));
}
/**
* #param {string|{getHashCode:function():string}} key -
*
* #returns {string}
*/
_getStringKey(key) {
if (!key) {
return null;
}
if (Object.prototype.toString.call(key) === "[object String]") {
return key;
} else {
return key.getHashCode();
}
}
/**
* #param {string|{getHashCode:function():string}} key -
*
* #returns {T}
*/
get(key) {
const stringKey = this._getStringKey(key);
if (!stringKey || stringKey === "") {
return null;
}
return this.map.get(stringKey);
}
values() {
return [...this.map.values()];
}
/**
* #param {string|{getHashCode:function():string}} key -
*/
key(key) {
const stringKey = this._getStringKey(key);
if (!stringKey || stringKey === "") {
return null;
}
return this.keyReferences[stringKey];
}
keys() {
return Object.values(this.keyReferences).slice();
}
}
ObjectKeyMap assumes object to be used as key must have a getHashCode function which return identity string. It should be more readable if written in TypeScript.

Call to a member function format() on string symfony 3.4

I'm trying to register a new appointment in my database, after sending an email, but it shows me an error: Call to a member function format() on string,
in vendor\doctrine\dbal\lib\Doctrine\DBAL\Types\DateTimeType.php
,
because in the booking entity, there is the date and time I need to register which are datetime types.
Here is the booking entity :
<?php
namespace Doctix\FrontBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Booking
*
* #ORM\Table(name="booking")
*
class Booking
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var \DateTime
*
*#ORM\Column(name="date_rdv", type="datetime", nullable=true)
*/
private $dateRdv;
/**
* #var \DateTime
*
*#ORM\Column(name="heure_rdv", type="datetime", nullable=true)
*/
private $heureRdv;
/**
* #var bool
*
*#ORM\Column(name="valider_rdv", type="boolean", nullable=true)
*/
private $validerRdv;
/**
* #ORM\ManyToOne(targetEntity="Doctix\MedecinBundle\Entity\Medecin")
* #ORM\JoinColumn(nullable=true)
*/
private $medecin;
/**
* #ORM\ManyToOne(targetEntity="Doctix\PatientBundle\Entity\Patient")
* #ORM\JoinColumn(nullable=true)
*/
private $patient;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set dateRdv
*
* #param \DateTime $dateRdv
*
* #return Booking
*/
public function setDateRdv($dateRdv)
{
$this->dateRdv = $dateRdv;
return $this;
}
/**
* Get dateRdv
*
* #return \DateTime
*/
public function getDateRdv()
{
return $this->dateRdv;
}
/**
* Set heureRdv
*
* #param \DateTime $heureRdv
*
* #return Booking
*/
public function setHeureRdv($heureRdv)
{
$this->heureRdv = $heureRdv;
return $this;
}
/**
* Get heureRdv
*
* #return \DateTime
*/
public function getHeureRdv()
{
return $this->heureRdv;
}
/**
* Set validerRdv
*
* #param boolean $validerRdv
*
* #return Booking
*/
public function setValiderRdv($validerRdv)
{
$this->validerRdv = $validerRdv;
return $this;
}
/**
* Get validerRdv
*
* #return bool
*/
public function getValiderRdv()
{
return $this->validerRdv;
}
/**
* Set medecin
*
* #param \Doctix\MedecinBundle\Entity\Medecin $medecin
* #return Booking
*/
public function setMedecin(\Doctix\MedecinBundle\Entity\Medecin $medecin)
{
$this->medecin = $medecin;
return $this;
}
/**
* Get medecin
*
* #return \Doctix\MedecinBundle\Entity\Medecin
*/
public function getMedecin()
{
return $this->medecin;
}
/**
* Set patient
*
* #param \Doctix\PatientBundle\Entity\Patient $patient
* #return Booking
*/
public function setPatient(\Doctix\PatientBundle\Entity\Patient $patient)
{
$this->patient = $patient;
return $this;
}
/**
* Get patient
*
* #return \Doctix\PatientBundle\Entity\Patient
*/
public function getPatient()
{
return $this->patient;
}
}
Here is the controller:
public function patientHandleBookingAction(Request $request){
$id = $request->query->get('id');
$date = $request->query->get('date');
$time = $request->query->get('time');
// $user = $this->getUser();
$em = $this->getDoctrine()->getManager();
$repoPatient = $em->getRepository('DoctixPatientBundle:Patient');
$patient = $repoPatient->findOneBy(array(
'user' => $this->getUser()
));
$repoMedecin = $em->getRepository('DoctixMedecinBundle:Medecin');
$medecin = $repoMedecin->findOneBy(array(
'id' => $request->query->get("idMedecin")));
$mailer = $this->get('mailer');
$message = (new \Swift_Message('Email de Confirmaton'))
->setFrom("medmamtest#gmail.com")
->setTo($patient->getUser()->getUsername())
->setBody(
$this->renderView(
// app/Resources/views/Emails/registration.html.twig
'Emails/registration.html.twig',
array('name' => 'mam')
),
'text/html'
);
$mailer->send($message);
if($mailer){
$booking = new Booking();
$booking->setMedecin($medecin);
$booking->setPatient($patient);
$booking->setDateRdv('date');
$booking->setHeureRdv('time');
$booking->setValiderRdv(0);
}
$em->persist($booking);
$em->flush();
// A remplacer par un contenu plus approprié
return $this->render('DoctixPatientBundle:Patient:confirm.html.twig',array(
'time' => $request->query->get("time"),
'date' => $request->query->get("date"),
'medecin' => $medecin,
'patient' => $patient,
// 'date' => $date,
// 'time' => $time
));
}
Thanks
This error is happening because you are trying to set the date and time as strings on your booking entity.
$booking->setDateRdv('date');
$booking->setHeureRdv('time');
Try to change it to:
$booking->setDateRdv(new \DateTime($date));
$booking->setHeureRdv(new \DateTime($time));

EventEmitter error after updating to NPM 3.10

I have updated NPM and now my code is returning the following error (please see picture):
Error Message can someone please provide guidance in identifying the culprit? My suspicion is that it has to do with inheritss which I'm not familiar with.
/**
* Expose the constructor.
*/
exports = module.exports = Store;
/**
* Module dependencies.
*/
var EventEmitter = process.EventEmitter;
/**
* Store interface
*
* #api public
*/
function Store (options) {
this.options = options;
this.clients = {};
};
/**
* Inherit from EventEmitter.
*/
Store.prototype.__proto__ = EventEmitter.prototype;
/**
* Initializes a client store
*
* #param {String} id
* #api public
*/
Store.prototype.client = function (id) {
if (!this.clients[id]) {
this.clients[id] = new (this.constructor.Client)(this, id);
}
return this.clients[id];
};
/**
* Destroys a client
*
* #api {String} sid
* #param {Number} number of seconds to expire client data
* #api private
*/
Store.prototype.destroyClient = function (id, expiration) {
if (this.clients[id]) {
this.clients[id].destroy(expiration);
delete this.clients[id];
}
return this;
};
/**
* Destroys the store
*
* #param {Number} number of seconds to expire client data
* #api private
*/
Store.prototype.destroy = function (clientExpiration) {
var keys = Object.keys(this.clients)
, count = keys.length;
for (var i = 0, l = count; i < l; i++) {
this.destroyClient(keys[i], clientExpiration);
}
this.clients = {};
return this;
};
/**
* Client.
*
* #api public
*/
Store.Client = function (store, id) {
this.store = store;
this.id = id;
};
The current way to get the EventEmitter class is:
const EventEmitter = require('events');
You should not be using process.EventEmitter.
In addition, the modern way to subclass an object is using either the ES6 class syntax or using Object.create(), not using __proto__.

Symfony2 - Using controller security for user and category

I am trying to restrict user access from accessing the CRUD access in the controller.
I have a bi-directional OneToOne relationship with User and Category. It's setup to only allow 1 user to be able to access 1 blog.
I am testing this by logging in as another user that is not related to this category. And upon clicking on new, the form loads by-passing any security I have setup.
Speculating that the problem is with the $title parameter being passed in, (trying to pass this in as the route variable) as I don't think I'm setting this up correctly.
Can someone guide me on what I'm doing wrong?
Controller code
/**
* Post controller.
*
* #Route("/category")
*/
/**
* Creates a new Post entity.
*
* #Route("/", name="category_create")
* #Method("POST")
* #Template("AcmeDemoBundle:Page:new.html.twig")
*/
public function createAction(Request $request, $title)
{
// User security
$em = $this->getDoctrine()->getManager();
$categoryRepository = $em->getRepository('AcmeDemoBundle:Category');
$category = $categoryRepository->findOneBy(array(
'title' => '$title',
));
$owner = $category->getUser();
$currentUser = $this->get('security.context')->getToken()->getUser();
if ($owner != $currentUser) {
throw new AccessDeniedException('You do not have access for this');
}
// Form creation
$post = new Post();
$form = $this->createCreateForm($post);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($post);
$em->flush();
return $this->redirect($this->generateUrl('category_show', array('id' => $post->getId())));
}
return array(
'post' => $post,
'form' => $form->createView(),
);
}
Category entity
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=255)
*/
private $title;
/**
* #var string
*
* #Gedmo\Slug(fields={"title"}, unique=false)
* #ORM\Column(length=255)
*/
private $catslug;
/**
* #ORM\OneToMany(targetEntity="Post", mappedBy="category")
*/
protected $posts;
/**
* #ORM\OneToOne(targetEntity="Acme\DemoBundle\Entity\User", inversedBy="cat")
* #ORM\JoinColumn(name="cat_id", referencedColumnName="id")
*/
protected $user;
User entity
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="username", type="string", length=255)
* #Assert\NotBlank(message="Field cannot be blank")
*/
private $username;
/**
* #var string
*
* #ORM\Column(name="password", type="string", length=255)
*/
private $password;
/**
* #ORM\Column(type="string", length=255)
* #Assert\NotBlank()
*/
private $email;
/**
* #ORM\Column(type="json_array")
*/
private $roles = array();
/**
* #var bool
*
* #ORM\Column(type="boolean")
*/
private $isActive = true;
/**
* #Assert\NotBlank
* #Assert\Regex(
* pattern="/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).*$/",
* message="Use 1 upper case letter, 1 lower case letter, and 1 number")
*/
private $plainPassword;
/**
* #ORM\OneToOne(targetEntity="Acme\DemoBundle\Entity\Category", mappedBy="user")
*/
private $cat;
You can try to create own Security Voter to check if user has a permission to this action. Sample code:
class CategoryVoter implements VoterInterface
{
const CREATE = 'create';
/**
* #param string $attribute
* #return bool
*/
public function supportsAttribute($attribute)
{
return in_array($attribute, [
self::CREATE
]);
}
/**
* #param string $class
* #return bool
*/
public function supportsClass($class)
{
$supportedClass = 'Acme\DemoBundle\Entity\Category';
return $supportedClass === $class || is_subclass_of($class, $supportedClass);
}
/**
* #param TokenInterface $token
* #param object $blog
* #param array $attributes
* #return int
*/
public function vote(TokenInterface $token, Category $category, array $attributes)
{
....
$attribute = $attributes[0];
$user = $token->getUser();
switch($attribute) {
case 'create':
if ($user->getId() === $category->getUser()->getId()) {
return VoterInterface::ACCESS_GRANTED;
}
break;
....
}
...
}
}
create action:
public function createAction(Request $request, $title)
{
$em = $this->getDoctrine()->getManager();
$categoryRepository = $em->getRepository('AcmeDemoBundle:Category');
$category = $categoryRepository->findOneBy([
'title' => '$title',
]);
...
if (false === $this->get('security.context')->isGranted('create', $category)) {
throw new AccessDeniedException('Unauthorised access!');
}
...
}

symfony2 can't login “Bad credentials”

I am writing a website using the Symfony framework but for some reason, the login process is not working.
I always get message: Bad credentials
Here is my security.yml
# app/config/security.yml
jms_security_extra:
secure_all_services: false
expressions: true
security:
firewalls:
secured_area:
pattern: ^/
anonymous: ~
form_login:
login_path: /login
check_path: /login_check
access_control:
- { path: ^/admin, roles: ROLE_ADMIN }
providers:
in_memory:
memory:
users:
user: { password: userpass, roles: [ 'ROLE_USER' ] }
contant_manager: { password: manpass, roles: [ 'ROLE_CONTENT_MANAGER' ] }
admin: { password: adminpass, roles: [ 'ROLE_ADMIN' ] }
encoders:
Symfony\Component\Security\Core\User\User: plaintext
My User.php class
<?php
namespace YouMustKnowIt\NewsBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;
use Doctrine\Common\Collections\ArrayCollection;
use APY\DataGridBundle\Grid\Mapping as GRID;
/**
* #ORM\Table(name="users")
* #ORM\Entity(repositoryClass="\YouMustKnowIt\NewsBundle\Entity\UserRepository")
*
* #GRID\Source(columns="id, username, email, role.name, isActive")
*/
class User implements AdvancedUserInterface, \Serializable
{
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*
* #GRID\Column(filterable=false)
*/
private $id;
/**
* #ORM\Column(type="string", length=25, unique=true)
*/
private $username;
/**
* #ORM\Column(type="string", length=32)
*/
private $salt;
/**
* #ORM\Column(type="string", length=100)
*/
private $password;
/**
* #ORM\Column(type="string", length=60, unique=true)
*/
private $email;
/**
* #ORM\ManyToMany(targetEntity="RolesList", inversedBy="users")
*
* #GRID\Column(field="roleslist.role", type="text", filter="select", title="role")
*/
private $role;
/**
* #ORM\OneToMany(targetEntity="NewsCatalog", mappedBy="user")
* #ORM\Column(name="created_news", nullable=true)
*/
private $createdNews;
/**
* #ORM\Column(name="is_active", type="boolean")
*/
private $isActive;
public function __construct()
{
$this->isActive = false;
$this->salt = md5(uniqid(null, true));
$this->role = new \Doctrine\Common\Collections\ArrayCollection();
$this->createdNews = new \Doctrine\Common\Collections\ArrayCollection();
}
public function __toString()
{
return $this->username;
}
public function isAccountNonExpired()
{
return true;
}
public function isAccountNonLocked()
{
return true;
}
public function isCredentialsNonExpired()
{
return true;
}
public function isEnabled()
{
return $this->isActive;
}
/**
* #inheritDoc
*/
public function getRoles()
{
return $this->role->toArray();
}
/**
* #inheritDoc
*/
public function getUsername()
{
return $this->username;
}
/**
* #inheritDoc
*/
public function getSalt()
{
return $this->salt;
}
/**
* #inheritDoc
*/
public function getPassword()
{
return $this->password;
}
/**
* #inheritDoc
*/
public function getEmail()
{
return $this->email;
}
/**
* #inheritDoc
*/
public function eraseCredentials()
{
}
/**
* #see \Serializable::serialize()
*/
public function serialize()
{
return serialize(array(
$this->id,
));
}
/**
* #see \Serializable::unserialize()
*/
public function unserialize($serialized)
{
list (
$this->id,
) = unserialize($serialized);
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set username
*
* #param string $username
* #return User
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
/**
* Set salt
*
* #param string $salt
* #return User
*/
public function setSalt($salt)
{
$this->salt = $salt;
return $this;
}
/**
* Set password
*
* #param string $password
* #return User
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Set email
*
* #param string $email
* #return User
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Set isActive
*
* #param boolean $isActive
* #return User
*/
public function setIsActive($isActive)
{
$this->isActive = $isActive;
return $this;
}
/**
* Get isActive
*
* #return boolean
*/
public function getIsActive()
{
return $this->isActive;
}
/**
* Add role
*
* #param \YouMustKnowIt\NewsBundle\Entity\RolesList $role
* #return User
*/
public function addRole(\YouMustKnowIt\NewsBundle\Entity\RolesList $role)
{
$this->role[] = $role;
return $this;
}
/**
* Remove role
*
* #param \YouMustKnowIt\NewsBundle\Entity\RolesList $role
*/
public function removeRole(\YouMustKnowIt\NewsBundle\Entity\RolesList $role)
{
$this->role->removeElement($role);
}
/**
* Add createdNews
*
* #param \YouMustKnowIt\NewsBundle\Entity\NewsCatalog $createdNews
* #return User
*/
public function addCreatedNews(\YouMustKnowIt\NewsBundle\Entity\NewsCatalog $createdNews)
{
$this->createdNews[] = $createdNews;
return $this;
}
/**
* Remove createdNews
*
* #param \YouMustKnowIt\NewsBundle\Entity\NewsCatalog $createdNews
*/
public function removeCreatedNews(\YouMustKnowIt\NewsBundle\Entity\NewsCatalog $createdNews)
{
$this->createdNews->removeElement($createdNews);
}
/**
* Get createdNews
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getCreatedNews()
{
return $this->createdNews;
}
/**
* Get role
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getRole()
{
return $this->role;
}
}
My UserRepository.php class
<?php
namespace YouMustKnowIt\NewsBundle\Entity;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\NoResultException;
class UserRepository extends EntityRepository implements UserProviderInterface
{
public function loadUserByUsername($username)
{
$q = $this
->createQueryBuilder('u')
->select('u, g')
->leftJoin('u.groups', 'g')
->where('u.username = :username OR u.email = :email')
->setParameter('username', $username)
->setParameter('email', $username)
->getQuery();
try {
$user = $q->getSingleResult();
} catch (NoResultException $e) {
$message = sprintf(
'Unable to find an active admin User object identified by "%s".',
$username
);
throw new UsernameNotFoundException($message, 0, $e);
}
return $user;
}
public function refreshUser(UserInterface $user)
{
$class = get_class($user);
if (!$this->supportsClass($class)) {
throw new UnsupportedUserException(
sprintf(
'Instances of "%s" are not supported.',
$class
)
);
}
return $this->find($user->getId());
}
public function supportsClass($class)
{
return $this->getEntityName() === $class
|| is_subclass_of($class, $this->getEntityName());
}
public function findAll()
{
return $this->createQueryBuilder('u');
}
}
SecurityController.php
<?php
namespace YouMustKnowIt\NewsBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\SecurityContext;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
use YouMustKnowIt\NewsBundle\Entity\User;
class SecurityController extends Controller
{
/**
* #Route("/login", name="login")
*/
public function loginAction()
{
$request = $this->getRequest();
$session = $request->getSession();
if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
$error = $request->attributes->get(
SecurityContext::AUTHENTICATION_ERROR
);
} else {
$error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
$session->remove(SecurityContext::AUTHENTICATION_ERROR);
}
return $this->render(
'YouMustKnowItNewsBundle:User:login.html.twig',
array(
'last_username' => $session->get(SecurityContext::LAST_USERNAME),
'error' => $error,
)
);
}
/**
* #Route("/login_check", name="login_check")
*/
public function loginCheckAction()
{
}
/**
* #Route("/logout", name="logout")
*/
public function logoutAction()
{
}
/**
* #Route("/recover_pass", name="recover_pass")
*/
public function recoverPasswordAction(Request $request)
{
$data = array();
$form = $this->createFormBuilder($data)
->add('email', 'email')
->getForm();
if ($request->getMethod() == 'POST') {
$form->bind($request);
if ($form->isValid()) {
$data = $form->getData();
$user = $this->getDoctrine()
->getRepository('YouMustKnowItNewsBundle:User')
->findOneByEmail($data['email']);
if (isset($user)) {
$this->createNewPassword($user);
return $this->redirect($this->generateUrl('homepage'));
} else {
$this->get('session')->getFlashbag()->add(
'error_message',
'The user with such email doesn\'t exist.'
);
}
}
}
return $this->render('YouMustKnowItNewsBundle:Default:recoverPass.html.twig', array(
'form' => $form->createView()
));
}
private function sendEmail(User $user)
{
$message = \Swift_Message::newInstance()
->setSubject('YouMustKnowIt! Password restoration.')
->setFrom('php.gr2#gmail.com')
->setTo($user->getEmail())
->setBody('Your new password: ' . $user->getPassword());
$this->get('mailer')->send($message);
}
private function generatePassword($length = 7)
{
$num = range(0, 9);
$alf = range('a', 'z');
$_alf = range('A', 'Z');
$symbols = array_merge($num, $alf, $_alf);
shuffle($symbols);
$code_array = array_slice($symbols, 0, $length);
$code = implode("", $code_array);
return $code;
}
private function encodePassword(User $user)
{
$factory = $this->get('security.encoder_factory');
$encoder = $factory->getEncoder($user);
$password = $encoder->encodePassword(
$user->getPassword(),
$user->getSalt()
);
return $password;
}
private function createNewPassword(User $user)
{
$password = $this->generatePassword();
$user->setPassword($password);
$this->sendEmail($user);
$encodedPassword = $this->encodePassword($user);
$user->setPassword($encodedPassword);
$em = $this->getDoctrine()->getEntityManager();
$em->persist($user);
$em->flush();
$this->get('session')->getFlashbag()->add(
'success_message',
'On your email the new password was sent.'
);
}
}
and finally login.html.twig
{% extends '::base.html.twig' %}
{% block body %}
{% if error %}
<div>{{ error.message }}</div>
{% endif %}
<form action="{{ path('login_check') }}" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="_username" value="{{ last_username }}" />
<label for="password">Password:</label>
<input type="password" id="password" name="_password" />
#<input type="hidden" name="_csrf_token" value="/" />
<input type="submit" name="login" />
</form>
{% endblock %}
If you are using an entity that is mapped to a database then your Provider: is missing the correct mapping.
providers:
users:
entity: { class: YouMustKnowItNewsBundle:User, property: username }

Resources