I have upgrade Symfony 3.4 ( Propel ORM ) to Symfony 4.1 (Propel ORM).
I have added my schema.xml file in scr->propel folder
.
<database name="yoursource" defaultIdMethod="native" namespace="Entity">
<table name="activity_log" idMethod="native" phpName="ActivityLog">
<column name="activity_log_id" phpName="ActivityLogId" type="INTEGER" primaryKey="true" autoIncrement="true" required="true"/>
<column name="activity_type_id" phpName="ActivityTypeId" type="INTEGER" required="true" defaultValue="1"/>
</table>
</database>
My Model generate in src->Entity folder
My Controller code like below
namespace App\Controller;
use Entity;
use Entity\Person;
class PersonController extends AbstractController
{
public function logincheckAction(Request $request) {
$person = PersonQuery::create()->filterByEmail($email)->findOne();
}
}
Get below error :
Attempted to load class "PersonQuery" from namespace "App\Controller".
Did you forget a "use" statement for another namespace?
Thanks for help..
Related
i'm using sonata admin, i tried to override max length allowed for name of categorie
I have an entity MyEntity who extend Application\Sonata\ClassificationBundle\Entity\Category
// MyEntity admin class
I put this following function, regarding https://sonata-project.org/bundles/core/master/doc/reference/conditional_validation.html#inline-validation
public function validate(\Sonata\Form\Validator\ErrorElement $errorElement, $object)
{
parent::validate($errorElement, $object);
$errorElement->with('name')
->assertLength(['max' => 100])
;
}
Current display
Expected to get ride of this 32 max length on name's field
Thx for helping
It looks like what you need to do instead, is override this validation config: https://github.com/sonata-project/SonataClassificationBundle/blob/3.x/src/Resources/config/validation.xml
<class name="Sonata\ClassificationBundle\Model\Category">
<property name="name">
<constraint name="NotBlank"/>
<constraint name="Length">
<option name="min">2</option>
<option name="max">32</option>
</constraint>
</property>
</class>
I'm currently working on a Symfony2 project which uses Sonata.
Previous developers have made modifications inside the vendors directly which is obviously a huge mistake so I'm in the process of refactoring this. I'm currently stuck with some modifications that have been made to constraint mapping from the FOSUserBundle.
The file is: /vendor/friendsofsymfony/user-bundle/FOS/UserBundle/Resources/config/validation/orm.xml
They actually disabled the UniqueEntity constraint on the class FOS\UserBundle\Model\User based on the field usernameCanonical, like this:
<?xml version="1.0" ?>
<constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping
http://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">
<class name="FOS\UserBundle\Model\User">
<!-- <constraint name="Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity">
<option name="fields">usernameCanonical</option>
<option name="errorPath">username</option>
<option name="message">fos_user.username.already_used</option>
<option name="groups">
<value>Registration</value>
<value>Profile</value>
</option>
</constraint> -->
<constraint name="Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity">
<option name="fields">emailCanonical</option>
<option name="errorPath">email</option>
<option name="message">fos_user.email.already_used</option>
<option name="groups">
<value>Registration</value>
<value>Profile</value>
</option>
</constraint>
</class>
</constraint-mapping>
How can I reproduce this change in the overriden FOSUserBundle, or the overriden SonataUserBundle ?
I have a solution, but don't know if it will fit your needs.
You can change de validation groups name in your config.yml for fos_user.
For example :
fos_user:
...
registration:
...
form:
validation_groups: [YourBundleNameRegistration, Default] #before it was [Registration, Default]
profile:
...
form:
...
validation_groups: [YourBundleNameProfile, Default] #before it was [Profile, Default]
Then the validation constraints defined in /vendor/friendsofsymfony/user-bundle/FOS/UserBundle/Resources/config/validation/orm.xml will not applied anymore.
You have to copy the original orm.xml, and paste it in your YourBundle/Resources/config directory. And in this copy you replace Registration and Profile by YourBundleNameRegistration and YourBundleNameProfile. And then you remove the unique constraint on usernameCanonical.
As much as the answer from #Nico pointed me to the right direction, here is the complete setup I've had to do in order to integrate it into the SonataUserBundle and have my custom validation groups taken into account.
As a matter of fact, it seemed that my custom orm.xml file was not loaded. So after changing the validation groups, no more validation occurred at all.
1. Create a file orm.xml
In Application\Sonata\UserBundle\Resources\config\validation\:
<?xml version="1.0" ?>
<constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping
http://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">
<class name="FOS\UserBundle\Model\User">
<!-- <constraint name="Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity">
<option name="fields">usernameCanonical</option>
<option name="errorPath">username</option>
<option name="message">fos_user.username.already_used</option>
<option name="groups">
<value>Registration</value>
<value>Profile</value>
</option>
</constraint> -->
<constraint name="Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity">
<option name="fields">emailCanonical</option>
<option name="errorPath">email</option>
<option name="message">fos_user.email.already_used</option>
<option name="groups">
<value>CustomRegistration</value>
<value>CustomProfile</value>
</option>
</constraint>
</class>
</constraint-mapping>
2. Tell FOSUserBundle and SonataUserBundle
To use the custom validation groups (I've stripped down the non-relevant configuration lines):
app/config/fos/fos_user.yml:
fos_user:
registration:
form:
validation_groups:
- CustomRegistration
profile:
form:
validation_groups:
- CustomProfile
app/config/sonata/sonata_user.yml:
sonata_user:
profile:
form:
validation_groups:
- CustomProfile
3. Tell the compiler to load the "overriden" validation file
Add Application\Sonata\UserBundle\DependencyInjection\Compiler\ValidationPass.php class. This is based on the original class from FOSUserBundle:
class ValidationPass implements CompilerPassInterface
{
/**
* {#inheritDoc}
*/
public function process(ContainerBuilder $container)
{
if (!$container->hasParameter('fos_user.storage')) {
return;
}
$storage = $container->getParameter('fos_user.storage');
if ('custom' === $storage) {
return;
}
$validationFile = __DIR__ . '/../../Resources/config/validation/' . $storage . '.xml';
if ($container->hasDefinition('validator.builder')) {
// Symfony 2.5+
$container->getDefinition('validator.builder')
->addMethodCall('addXmlMapping', array($validationFile));
return;
}
}
}
Edit Application\Sonata\UserBundle\ApplicationSonataUserBundle:
class ApplicationSonataUserBundle extends Bundle
{
/**
* {#inheritdoc}
*/
public function build(ContainerBuilder $container)
{
parent::build($container);
$container->addCompilerPass(new ValidationPass());
}
}
4. Override the default validation groups in the UserAdmin class of Sonata (within an overloaded UserAdmin class)
/**
* {#inheritdoc}
*/
public function getFormBuilder()
{
$this->formOptions['data_class'] = $this->getClass();
$options = $this->formOptions;
$options['validation_groups'] =
(!$this->getSubject() || is_null($this->getSubject()->getId())) ? 'CustomRegistration' : 'CustomProfile';
$formBuilder = $this->getFormContractor()->getFormBuilder( $this->getUniqid(), $options);
$this->defineFormBuilder($formBuilder);
return $formBuilder;
}
I don't know if there was a simpler way to achieve this. Nevertheless, it works for me.
I am creating a Task Management Application Demo project just to get the hold of symfony2. So far I have finished CRUD operations.
This is my defaultcontroller. I am calling the getNumberOfTasks() here.
namespace TaskManagerBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use TaskManagerBundle\Entity\Projects;
use TaskManagerBundle\Form\ProjectType;
class DefaultController extends Controller
{
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('TestBundle:Projects')
->findAll();
$tasks = $em->getRepository('TestBundle:Projects')
->getNumberOfTasks();
return $this->render('TestBundle:Default:index.html.twig', [
'projects' => $entities,
'tasks' => $tasks,
]
);
}
This is my ProjectRepository, where I have defined the getNumberOfTasks method.
<?php
namespace TaskManagerBundle\Entity\Repository;
use Doctrine\ORM\EntityRepository;
use TaskManagerBundle\Entity\Projects;
use TaskManagerBundle\Entity\Tasks;
/**
* ProjectsRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class ProjectsRepository extends EntityRepository
{
public $id;
public function getNumberOfTasks()
{
//$projects = new Projects();
$query = $this->getEntityManager()
->createQuery(
'SELECT p FROM TestBundle:Tasks p WHERE p.projects = :project_id'
)
->setParameter('project_id', $this->id )
->getResult();
return count($query);
}
}
This is my index.html.twig
{% for project in projects %}
<tr>
<td>
{% if project.completed == 0 %}
{{ tasks }}
{% else %}
Completed
{% endif %}
</td>
</tr>
{% endfor %}
I am trying to get the number of tasks for each project. How do I do that?
In yii2 I could just do $this->id but here I am not able to do that.
You don't need the "getNumberOfTasks" method at all.
What you should be doing is specifying the associations in your Doctrine Entities.
You can read about it here:
http://doctrine-orm.readthedocs.org/en/latest/reference/association-mapping.html
Based on your naming, I would suspect a OneToMany relationship from Project to Task, and a ManyToOne relationship from Task to Project.
When mapped correctly, in Twig you can then use:
{{ project.tasks|length }}
to get the number of tasks in a project. All you need to do is to pass the Project Entity to Twig and Symfony will handle the rest, including loading in all relationships.
This is the best way of doing what you are trying to do.
I finished installing sonata-admin bundle + fosuser bundle.
after creating users using the command line , i found out that when i login using admin admin its gives me bad credentials , so after debugging for a while i found out that the fos:user:create save users to fos_user_user not user table .
how to fix this and make the fos:user:create save created users in user table .
here is a snippet of my config.yml
fos_user:
db_driver: orm
firewall_name: main
user_class: Application\Sonata\UserBundle\Entity\User
#user_class: Sizar\JobeetBundle\Entity\SizarUser
group:
group_class: Application\Sonata\UserBundle\Entity\Group
sonata_user:
class: # Entity Classes
user: Application\Sonata\UserBundle\Entity\User
if needed any configs then i will add it in the comments below
the User.php class
namespace Application\Sonata\UserBundle\Entity;
use Sonata\UserBundle\Entity\BaseUser as BaseUser;
class User extends BaseUser {
protected $id;
public function __construct() {
parent::__construct();
}
public function getId() {
return $this->id;
}
}
the orm User file
<?xml version="1.0" encoding="UTF-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping
http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
<entity name="Application\Sonata\UserBundle\Entity\User" table="fos_user_user">
<id name="id" column="id" type="integer">
<generator strategy="AUTO" />
</id>
</entity>
</doctrine-mapping>
You will have to update you mapping config, so that doctrine knows which table it is mapped to
<?xml version="1.0" encoding="UTF-8"?>
<doctrine-mapping ...>
<entity name="Application\Sonata\UserBundle\Entity\User" table="fos_user_user">
...
</entity>
</doctrine-mapping>
Here you will need to update the "table" property to the correct database table. Possibly you will need to recreate the database.
See FosUserBundle - Install docs for further info about the setup of your entities for the usage with FosUserBundle
i'm using FOS User Bundle and I want to override the validation file FOS/UserBundle/Resources/config/validaiton.xml:
<constraint name="FOS\UserBundle\Validator\Unique">
<option name="property">usernameCanonical</option>
<option name="message">fos_user.username.already_used</option>
<option name="groups">
<!-- <value>Registration</value> -->
<value>Profile</value>
</option>
</constraint>
username is not in my Registration form (I just set it to hidden), that's the validation should not produce any error...
Maybe there is a better way to remove the username of the form...
To remove the username field of the form in a proper way, you should override the RegistrationFormType, creating your own and extending it from the original FOSUserBundle
<?php
namespace Acme\UserBundle\Form\Type;
use Symfony\Component\Form\FormBuilder;
use FOS\UserBundle\Form\Type\RegistrationFormType as BaseType;
class RegistrationFormType extends BaseType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder->add('email', 'email')
->add('plainPassword', 'repeated', array('type' => 'password'))
// your other custom fields, if any.
}
}
Now, you should declare the overrided form as a service, and then tell to FOSUserBundle configuration file that you are using now an overrided form. Here is the complete documentation.
You can put entity validation info in any validation.yml file. So you can do
#validation.yml
FQCN\Of\User\Entity:
constraints:
- FOS\UserBundle\Validator\Unique:
property: usernameCanonical
groups: [Profile]
message: fos_user.username.already_used
properties:
# property validations here