i am trying to build an custom validator with symfony2 but something strange happens:
i have created both Password and PasswordValidate by following the steps in symfony2 cookbook but first time when i load the page i get this error:
AnnotationException: [Semantical Error] The annotation "#Symfony\Component\Validator\Constraints\Password" in property NMSP\MyBundle\Entity\User::$password does not exist, or could not be auto-loaded.
after reloading the error disappears and the validation still not fires and it return the code is valid.
here is the relevant code:
//annotation declaration:
/**
* #ORM\Column(type="string", length="32", unique="true")
*
* #Assert\MinLength(3)
* #Assert\Password2()
*/
protected $password;
//load files with the following in the code
services:
validator.password:
class: NMSP\MyBundle\Validator\PasswordValidator
tags:
- { name: validator.constraint_validator, alias: password }
can`t figure this one out:(
Assuming your custom validator constraint is not in the Symfony\Component\Validator\Constraints namespace, but your own namespace: NMSP\MyBundle\Validator.
You should add the following use statement:
use NMSP\MyBundle\Validator as NMSPAssert;
Then use the following annotation on the $username property:
#NMSPAssert\Password()
That should do it.
Related
I'm trying to create a custom Token authenticator for my Symfony 6.2 and API Platform project
class TokenAuthenticator extends JWTTokenAuthenticator
{
/**
* #param PreAuthenticationJWTUserToken $preAuthToken
* #param UserProviderInterface $userProvider
* #return UserInterface
*/
public function getUser($preAuthToken, UserProviderInterface $userProvider): UserInterface
{
$user = parent::getUser($preAuthToken, $userProvider);
var_dump($preAuthToken->getPayload());exit;
}
}
But I always get this error:
Attempted to load interface "AuthenticatorInterface" from namespace "Symfony\Component\Security\Guard".
Did you forget a "use" statement for "Symfony\Component\Security\Http\Authenticator\AuthenticatorInterface"?
that means, there's no AuthenticatorInterface on Security\Guard and Http\Authenticator replaces it, so the LexikJWTAuthenticationBundle must be updated to include the new change.
This new class contains new functions so is there any documentation regarding them? Also, the purpose of establishing this class TokenAuthenticator is to make the old token invalid when changing the password, so is there a better way to do this?
I am working on a new project in Symfony 5.3. I am using this command bin/console make:entity for creating entities.
This wizard automatically creates an entity with $id as primary key of type integer. I am prefering UUID instead of integer.
How I should change settings to get Entity like this?
Thank you
namespace App\Entity;
use App\Repository\EventRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\IdGenerator\UuidGenerator;
/**
* #ORM\Entity(repositoryClass=EventRepository::class)
*/
class Event
{
/**
* #ORM\Id
* #ORM\Column(type="uuid", unique=true)
* #ORM\GeneratedValue(strategy="CUSTOM")
* #ORM\CustomIdGenerator(class=UuidGenerator::class)
*/
private $id;
...
}
There is no option to set the generated identifier strategy on make entity.
You can see all available option using php bin/console make:entity -h
Also there are no configuration in doctrine.yaml file to define this.
It could be a good feature to add for current and next version
To request a new feature, you can create a new issue feature request type:
https://github.com/symfony/symfony/issues/new/choose
You will need a github account
Got everything in my form validating using i18n just fine but cant figure out how to translate the form validation. For example right now when I try and submit the form with an empty field I get the pop-up validation message "Please fill out this field."
Translation is turned on and annotations enabled:
// config_dev.yml
framework:
router:
resource: "%kernel.root_dir%/config/routing_dev.yml"
strict_requirements: true
profiler: { only_exceptions: false }
translator: { fallback: en }
validation: { enable_annotations: true }
Entity is rigged for validation annotations:
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
....
/**
* #var string
* #Assert\NotBlank(message = "Custom validation error message")
* #ORM\Column(name="url", type="string", length=512)
*/
private $url;
I also created the file validators.en.yml in my app/Resources/translations folder but not sure where to go from here. Can anyone help?
You could translate validation messages in app/Resources/translations/validators.fr.xlf (example for french xlf translation file)
Here the Docs you are looking for: http://symfony.com/doc/current/validation/translations.html
I want to validate form using asserts in Entity class but when I submit the form, it says $form->isValid() is true.
Here is how I got it setup:
// config.yml
validation: { enabled: true, enable_annotations: false }
// validation.yml
Software\Bundle\Entity\Program:
properties:
name:
- NotBlank: ~
// MyForm
...
$builder
->add('name', 'text', [
'label' => 'word.name'
])
;
...
// Program.php
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255, nullable=false)
*/
private $name;
I tried also via Annotations but it did not help.
I know I can put 'constraints' property to my form and there set new NotBlank() but I want to have that validation on Entity level since I am going to use an API and I want to have validation in one place instead of two.
Is my validation.yml file ignored or what?
EDIT
I did not mention one important thing that my form is embedded into another one. in this case you must use 'cascade_validation' property in your form options.
This answer helped me a lot Symfony2 - Validation not working for embedded Form Type
Your configuration seems correct but your yml is ignored, try to clear your cache.
Also where is your validation.yml ? It must be in a path like : src/AppBundle/Resources/config/validation.yml
In your annotation example, there is no validation constraint you must add #Assert\NotBlank on your property. Nullable = false is only for your database schema.
Symfony doc about validation : http://symfony.com/doc/current/cookbook/validation/custom_constraint.html#using-the-new-validator
Same question about using validation.yml : Symfony2 how to load validation.yml
I have the Sonata Media Bundle installed but I don't use the gallery portion of the bundle.
How do I disable the Gallery?
I am using Symfony 2.3 and I have the standard Media Bundle install as per the documentation.
Solution thus far:
If you look at this issue https://github.com/sonata-project/SonataAdminBundle/issues/460 from the admin bundle you can disable a admin by adding the show_in_dashboard: false tag to the yaml file.
To do this I simply add my own compiler that adds this flag for me then:
Create your compiler: http://symfony.com/doc/current/components/dependency_injection/tags.html
Add your compiler to your bundle: http://symfony.com/doc/2.3/cookbook/service_container/compiler_passes.html
And you are done. If there is a better solution I'd love to hear about it.
Example of compiler:
namespace YourBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
class OverrideMediaGalleryCompilerPass implements CompilerPassInterface
{
/**
* You can modify the container here before it is dumped to PHP code.
*
* #param ContainerBuilder $container
*
* #api
*/
public function process( ContainerBuilder $container )
{
$definition = $container->getDefinition( 'sonata.media.admin.gallery' );
if ( $definition ) {
/**
* The purpose here is to disable the sonata admin gallery from showing up
* in the dashboard. This goes through and adds show_in_dashboard parameter
* that disables this.
*/
if ( $definition->hasTag( 'sonata.admin' ) ) {
$tags = $definition->getTag( 'sonata.admin' );
$tags[ 0 ][ 'show_in_dashboard' ] = false;
$definition->clearTag( 'sonata.admin' );
$definition->addTag( 'sonata.admin', $tags[ 0 ] );
}
}
}
}
Just add below service configuration into your config.yml or sonata_admin.yml file to disable gallery and media menu from admin panel or use services.yml file in config directory and load it from dependencyInjection class
#Application/Sonata/MediaBundle/DependencyInjection/ApplicationSonataMediaExtension.php
<?php
namespace Application\Sonata\MediaBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;
/**
* This is the class that loads and manages your bundle configuration
*
* To learn more see {#link http://symfony.com/doc/current/cookbook/bundles/extension.html}
*/
class ApplicationSonataMediaExtension extends Extension
{
/**
* {#inheritDoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.yml');
}
}
Use only sonata.media.admin.gallery: service if you want to remove only gallery menu
#Application/Sonata/MediaBundle/Resources/config/services.yml
#Disable gallery & media menu from admin panel
services:
sonata.media.admin.media:
class: %sonata.media.admin.media.class%
tags:
- { name: sonata.admin, manager_type: orm, show_in_dashboard: false, label_catalogue: %sonata.media.admin.media.translation_domain% , label_translator_strategy: sonata.admin.label.strategy.underscore }
arguments:
- ~
- %sonata.media.admin.media.entity%
- %sonata.media.admin.media.controller%
- "#sonata.media.pool"
calls:
- [setModelManager, ["#sonata.media.admin.media.manager"]]
- [setTranslationDomain, [%sonata.media.admin.media.translation_domain%]]
- [setTemplates, [{ inner_list_row: SonataMediaBundle:MediaAdmin:inner_row_media.html.twig , base_list_field: SonataAdminBundle:CRUD:base_list_flat_field.html.twig , list: SonataMediaBundle:MediaAdmin:list.html.twig , edit: SonataMediaBundle:MediaAdmin:edit.html.twig }]]
sonata.media.admin.gallery:
class: %sonata.media.admin.gallery.class%
tags:
- { name: sonata.admin, manager_type: orm, show_in_dashboard: false, label_catalogue: %sonata.media.admin.media.translation_domain% , label_translator_strategy: sonata.admin.label.strategy.underscore }
arguments:
- ~
- %sonata.media.admin.gallery.entity%
- %sonata.media.admin.gallery.controller%
- "#sonata.media.pool"
calls:
- [setTranslationDomain, [%sonata.media.admin.media.translation_domain%]]
- [setTemplates, [{ list: SonataMediaBundle:GalleryAdmin:list.html.twig }]]
then clear your cache to reflect changes
php app/console cache:clear
I've achieved this by listing the allowed items for the dashboard in sonata.yaml, effectively hiding the gallery:
sonata_admin:
dashboard:
groups:
sonata_media:
label: "Media Library"
label_catalogue: SonataMediaBundle
items:
- sonata.media.admin.media
why don't you just edit app\config\sonata\sonata_admin.yml file end comment or remove line containing sonata.media.admin.gallery?
The quickest way - but - dirty way it to edit the sonata media config file:
vendor/sonata-project/media-bundle/Resources/config/doctrine_orm_admin.xml
You only need too add this
show_in_dashboard="false"
in the tag attribute of the service sonata.media.admin.gallery
<tag name="sonata.admin" show_in_dashboard="false" manager_type="orm" group="sonata_media" label="gallery" label_catalogue="%sonata.media.admin.gallery.translation_domain%" label_translator_strategy="sonata.admin.label.strategy.underscore"/>
If you use mongodb or phpcr then edit the corresponding file.
Also you can do the same for the sonata.media.admin.media service in the same file, so all the "Media" block in the admin will disapeared. But the services are still enable, so you manage your picture in your own entity admin as a sub-entity.
I hope this will help someone as it took me 30min to find the right file ...