I'm using Symfony with annotation and assert to do some validation checks in a form. With the following annotation I'm checking if a field is not blank:
#Assert\NotBlank(message="not_blank")
This generated a message in the correct language, this case:
The field cannot be empty
Now I want to add the field name as a placeholer so I don't need to make a separate message for every field. So something like:
#Assert\NotBlank(message="not_blank {{ name=email }}")
<trans-unit id="1">
<source>not_blank</source>
<target>This {{ name }} field cannot be empty</target>
</trans-unit>
In the translation file it would then be:
Then I can output:
The email field cannot be empty
If this is possible then I don't need to make separate message for every field like: name, email, street etc..
If you open #Assert\NotBlank you can see:
class NotBlank extends Constraint
{
public $message = 'This value should not be blank.';
}
So you can't use it in another way, but you can create custom constraint by extending the base constraint class Constraint
See Tutorial
Related
When I use:
public function configureFields(string $pageName): iterable
{
return [
AssociationField::new('XYZ')
];
}`
I get error "Object of class App\Entity\XYZ could not be converted to string"
When I add ->autocomplete() to the AssociationField::new('XYZ'), then it works, but on save it displays error "Expected argument of type "?string", "App\Entity\XYZ" given at property path "XYZ".
Whats the CORRECT way to use this field with many to one relation? Symfony Easy Admin documentation https://symfony.com/doc/current/EasyAdminBundle/fields/AssociationField.html doesn't help at all.
Your entity App\Entity\XYZ will be converted to a string in your association field (which is a standard symfony entity type). Otherwise there is no way to set a label in your entity select.
It will try to convert it using the __toString method, so you need to add it in your entity.
For example:
/**
* #ORM\Entity(repositoryClass=XyzRepository::class)
*/
class Xyz
{
public function __toString(){
return $this->name; //or anything else
}
EasyAdmin should be able to guess the entity class, so you don't have to specify it like you would for a simple EntityType.
I try to set the user informations who is logged-in on a twig template but I can't find a way.
In particular, I try to make a comments section and I would like the user to write only the comment text.Doing so, I would like to setAuthor( app.user.username) on the template twig because I cannot get user information on the Controller file.
so on my controller file,in the function show, I put this :
if($form->isSubmitted() && $form->isValid() ){
$comment->setCreatedAt(new \DateTime())
->setExercice($exercice)
//would like to do it but cannot
//->setAuthor(app.user.username);
So I search a way to maybe make something like
{{form_row(commentForm.author,{'attr': {
'value': app.user.username,
'class':hidden
}})}}
Is there a way to do it ?
the error I get is :
Variable "hidden" does not exist.
Your original error, Variable "hidden" does not exist., happens because you've attempted to reference hidden as if it were a variable or constant, rather than a literal string. To use it as a literal string you need to quote it:
{{ form_row(commentForm.author, {attr: {
value: app.user.username,
class: 'hidden'
}}) }}
You do not need to quote the keys of the array (e.g. value: and class:) because non-scalar values cannot be used as keys.
However as #msg pointed out you should not rely on the form on the view to obtain the user details. This opens the form up to manipulation, meaning anyone would be able to impersonate other people in any comment posted. Definitely populate that field of the comment entity directly during the controller. -- If you do this prior to checking if the form is submitted that information will be available to the view also, e.g. exposing $comment to the view would mean {{ comment.username }} would also work.
I would like to give formBuilder User Entity as hidden value.
$form->add('user','hidden',array("data" => $user))
$user is User Entity.
However it shows this error.
Expected argument of type "Acme\UserBundle\Entity\User", "string" given
If I use 'null' instead of 'hidden'
$form->add('user',null,array("data" => $user))
it doesn't show the error and shows the select box of user Entity.
However I would like to use hidden.
How can I make it??
You did't specify the field type correctly - this is the correct way:
...
$formBuilder->add('user', HiddenType::class);
...
...
$form = $formBuilder->getForm();
$form->get('user')->setData($user->getId());
But you can't assign entity to the hidden field, so you can assign user's id for user identification.
Another option is to make data transformer and define own EntityHiddenType - more on this here: symfony : can't we have a hidden entity field?
I have "Person" entity that has a property "Status" and this property is an OneToMany relationship in Doctrine.
/**
*
* #ORM\OneToMany(targetEntity="\My\Bundle\Entity\Status", mappedBy="person")
*
**/
protected $status;
What I need to do is to display in my view is just the last status.
How can I get just the last status in my twig view? Is there something like, for exmample, {{ person.status.last }} ?
Or should I query the last status in my controller and pass it to view as another var?
Yes, you can do it exactly like this {{ person.status.last.someField }} to echo a someField property of last status (in natural query order) for person object.
This is possible because person.status is a Doctrine Collection which has methods like first or last. You can check this for more information.
If you've used Symfony2's generators to create CRUD forms from database entities, you may wind with an error like this on the "create new record" screen:
StringCastException: A "__toString()" method was not found on the objects of type
"ScrumBoard\ServiceBundle\Entity\Users" passed to the choice field. To read a
custom getter instead, set the option "property" to the desired property path.
If I'm reading this correctly, the problem is that it needs to display a dropdown list of users for the record I'm creating, but it doesn't know how to turn a "User" entity into a string.
Defining the __toString() method on my Users entity class fixes the problem. However, I can see right from the text of the error message that there is an alternative: read a customer getter instead, which is accomplished by "[setting] the option "property" to the desired property path."
This sounds like some kind of annotation. But in my searching, I can't figure out what that is. Because I want to have a thorough understanding of Symfony2--can someone help me out?
Thanks!
When creating an entity ( superclass of choice ) field type in a form. You need to specify which property shall be used for the labels/values otherwise the __toString() method of the underlying object will be used.
$builder->add('users', 'entity', array(
'class' => 'AcmeHelloBundle:User',
'property' => 'username',
));
Read more about it in the Form Type Reference for entity field Type.
Additional Info
A __toString() related error generally often comes from twig when generating a route in a template aswell.
if outputting an object an object in twig with {{ object }} ... twig will call the object'S __toString method.
This "trick" is used by the crud generated templates with SensioGeneratorBundle.
{{ path('article_show', {'id': article}) }}
with the route being something like this:
article_show:
pattern: /article/{id}
defaults: { _controller: AcmeArticleBundle:Article:show }
If you have the __toString method in your Article entity set to something like ...
public function __toString()
{
return $this->id;
}
... you dont't need to type
{{ path('article_show', {'id': article.id) }}
Generally Twig will automatically output Article::getId() if you use
{{ article.id }}
Hope this clarifies your findings.