best way customize field_error in symfony 3 - symfony

i have a entity with path field
/**
* #var string
* #Assert\NotBlank(message="Please, upload scontrino/fattura della stufa acquistata.")
* #Assert\File(mimeTypes={ "application/pdf","image/png" ,"image/jpg","image/jpeg" })
* #ORM\Column(name="path_file", type="string", length=255)
*/
private $path;
i have this field in a form
->add('path', FileType::class, array('data_class' => null))
;
and in the twig file
<div class="row">
<div class="input-field col s12 ">
{{ form_errors(form.path) }}
{{ form_widget(form.path) }}
</div>
</div>
when i press submit button and i put i not allowed file now my message is
Il mime type del file non è valido ("application/zip"). I tipi permessi sono "application/pdf", "image/png", "image/jpg", "image/jpeg".
I want to change that message but i don't understand the best way to do that.
If i must do it in entity file or in form file or in twig file

You have to add:
mimeTypesMessage = "with the text you want", in the #Assert\File
in your #Assert\File of your entity
/**
* #var string
* #Assert\NotBlank(message="Please, upload scontrino/fattura della stufa acquistata.")
* #Assert\File(mimeTypes={ "application/pdf","image/png" ,"image/jpg","image/jpeg" }, mimeTypesMessage = "with the text you want")
* #ORM\Column(name="path_file", type="string", length=255)
*/
The symfony Reference

Related

Get the message from assert in symfony template

I have a question related to Assert form validation in symfony. So I have :
/**
* #ORM\Column(type="string")
* #Assert\NotBlank(message="client.firstName.notBlank")
* #Assert\Length(
* min = 2,
* max = 50,
* minMessage = "client.firstName.invalid",
* maxMessage = "client.firstName.invalid"
* )
* #Assert\Regex(
* pattern = "/^[0-9]+$/i",
* htmlPattern = "^[0-9]+$",
* message="client.firstName.regex"
* )
*/
protected $firstName;
And in validators.yml :
client:
firstName:
notBlank: 'Not Blank'
invalid: 'Invalid'
regex: 'Regex'
In form I have :
<div class="form-group">
{{ form_label(form.firstName) }}
{{ form_widget(form.firstName) }}
<div class="invalid-feedback">
{{ 'client.firstName'|trans({}, 'validators') }}
</div>
</div>
When I try to submit the form I get the message : client.firstName. I need a way to get message from assert. Can you help me please ? Thx in advance.
You need add one other file for each your assert messages:
# app/Resources/translations/validators.en.yml
client.firstName.notBlank: Please enter your firt name.
......
I think this is not necessary:
<div class="invalid-feedback">
{{ 'client.firstName'|trans({}, 'validators') }}
</div>

Details list in symfony2, from two bundles

I have little in the development of Symfony and I have a question: To show a list with details of two Bundles.
My project have a Owner, but can have 1 o more consultants. The Entity has been related but when the results are listed only can view the user id. How can see the user name?
I will attach a image with my entities.
Thanks,
View
Entities
I need show the name of the differents consultants in a project. These are users too. I have already related the owner of the project, but this consultant is a field in my entity.
Attachment images to reference, and the php and twig files content. See the image: Database relation, and view.
UserProjectController
public function showAction(UserProject $userProject, User $user) {
$id = $userProject->getId();
$em = $this->getDoctrine()->getManager();
$project = $em->getRepository('ProjectBundle:Project')->find($id);
$userProjects = $em->getRepository('ProjectBundle:UserProject')->findby(array('idproject' => $id, 'status' => '1'));
if (empty($userProjects)) {
return $this->redirectToRoute('userproject_new');
}
$users = $em->getRepository('UserBundle:User')->findby(array('id' => 1));
return $this->render('ProjectBundle:Userproject:show.html.twig', array(
'userProjects' => $userProjects, 'project' => $project, 'User' => $user,
));
}
Entity User
/**
* #ORM\OneToMany(targetEntity="ProjectBundle\Entity\UserProject", mappedBy="user")
*/
protected $uproject;
Entity UserProject
/**
* #ORM\ManyToOne(targetEntity="ProjectBundle\Entity\Project", inversedBy="userproject")
* #ORM\JoinColumn(name="project_id", referencedColumnName="id")
* #Assert\NotBlank()
*/
protected $idproject;
/**
* #ORM\ManyToOne(targetEntity="UserBundle\Entity\User", inversedBy="uproject")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
* #Assert\NotBlank()
*/
protected $user;
Entity Project
/**
* #ORM\OneToMany(targetEntity="ProjectBundle\Entity\UserProject", mappedBy="idproject")
*/
protected $userproject;
View show.html.twig
{% for userProject in userProjects %}
<br>
<dl>
<dt><span class="text-primary">{{'User_id'|trans}}</span></dt>
<dd>
{{ userProject.user }}
</dd>
<br>
<dt><span class="text-primary">{{'Consultor_id'|trans}}</span></dt>
<dd>
{{ userProject.consultorId }}
</dd>
<br>
<dt><span class="text-primary">{{'Status'|trans}}</span></dt>
<dd>
{% if userProject.status == 1 %}
<span class="text-success">{% trans %}Enabled{% endtrans %}</span>
{% elseif userProject.status == 0 %}
<span class="text-danger">{% trans %}Disabled{% endtrans %}</span>
{% endif %}
</dd>
<br>
</dl>
{% endfor %}

Can't access every object property in Twig

I have a News entity with the next properties:
text
start_date
expire_date
Here's part of the class:
//News.php
/**
* #ORM\Column(type="string", length=200)
*/
private $text;
/**
* #ORM\Column(type="datetime")
*/
private $start_date;
/**
* #ORM\Column(type="datetime")
*/
private $expire_date;
I want to show all the news in a list in a twig template, this is how I'm doing that:
<div class="list-group">
{%for news in news%}
<div class="panel panel-default">
<div class="panel-heading">{{ news.start_date|date('Y-m-d') }}</div>
<div class="panel-body">
{{ news.text }}
</div>
</div>
{%endfor%}
</div>
The fact is that I get the following error:
Neither the property "start_date" nor one of the methods "start_date()", "getstart_date()"/"isstart_date()" or "__call()" exist and have public access in class "AppBundle\Entity\News".
But If I try to render only the text property, I am able to access it.
Why is that?
Your attribute is private. you can add a getter
public fucntion getStartDate() {
return $this->start_date;
}
and in twig
{{ news.startDate|date('Y-m-d') }}

Get facebook profile picture with HWIOAuthBundle

I know this subject was already discussed but however I still cannot find a solution.
I use HWIOAuth Bundle with FOSUserBundle for my users and socials connections.
#app/config.yml
#HWIOAuthBundle
hwi_oauth:
firewall_name: main
resource_owners:
facebook:
type: facebook
client_id: %oauth.facebook.id%
client_secret: %oauth.facebook.secret%
scope: "email"
options:
display: popup
infos_url: "https://graph.facebook.com/me?fields=id,name,email,picture.type(square)"
paths:
email: email
profilepicture: picture.data.url
http_client:
verify_peer: false
How can I integrate the "profilepicture: picture.data.url" on my Twig file ?
<li class="user-header">
<img src="{{ asset('theme/AdminLTE/dist/img/user2-160x160.jpg') }}" class="img-circle" alt="User Image" />
<p>
{{ app.user.username }}
</p>
</li>
Thanks a lot, I don't understand how can I use this parameter "profilepicture: picture.data.url" to get the facebook profile picture with HWIOAuthBundle.
you can receive require details in i.e. loadUserByOAuthUserResponse(UserResponseInterface $response):
/* #var $response \HWI\Bundle\OAuthBundle\OAuth\Response\UserResponseInterface */
var_dump(
$response->getEmail(),
$response->getProfilePicture()
);
I solved this issue adding a field in my Entity :
//Acme/UserBundle/Entity/User.php
/**
* #var string
*
* #ORM\Column(name="profile_picture", type="string", length=250, nullable=true)
*
*/
protected $profilePicture;
And modifying the UserProvider.php like this :
//Acme/UserBundle/OAuth/UserProvider.php
protected function updateUserByOAuthUserResponse(User $user, UserResponseInterface $response)
{
$providerName = $response->getResourceOwner()->getName();
$providerNameSetter = 'set'.ucfirst($providerName).'Id';
$user->$providerNameSetter($response->getUsername());
$user->setProfilePicture($response->getProfilePicture());
if(!$user->getPassword()) {
// generate unique token
$secret = md5(uniqid(rand(), true));
$user->setPassword($secret);
}
return $user;
}

How can I use two property on form_widget

I can show form by this codes.
$builder->add('icon', 'entity', array(
'class' => 'UserBundle:IconPics',
'property' => ‘label', 'expanded' => true, 'multiple' => false,
));
in twig
{{ form_label(form.icon) }}
{{ form_widget(form.icon) }}
There appeares radiobutton labeled 'PictureA' ,'PictureB','PictureC'....
But I want to use not only 'label' property but also 'pic' entity as well to make
the link to jpg file.
How can I use two property via one form_widget?
My code are below.
I have tables such as
in User.php
/**
* #ORM\ManyToOne(targetEntity="Acme\UserBundle\Entity\IconPics", inversedBy="icon")
* #ORM\JoinColumn(name="icon", referencedColumnName="id",nullable=true)
*/
private $icon;
in Icon.php
/**
* #var string
*
* #ORM\Column(type="string")
*/
private $label;
/**
* #var string
*
* #ORM\Column(type="string")
*/
private $pic;
/** * * #ORM\OneToOne(targetEntity="Acme\UserBundle\Entity\User", inversedBy="icon")
* #ORM\JoinColumn(name="icon", referencedColumnName="id")
*/
private $icon;
icon table is like
|id |pic |label
|1 |aaa.png |pictureA
|2 |bbb.png |pictureB
|3 |ccc.png |PictureC
This might not be the most elegant solution but it's a quick one. The proper solution would probably be writing a custom field type which would involve writing a lot of code.
There is a simple trick to achieve what you want. Just add a method to your entity that will be used to get both values at once:
public function getFormViewData()
{
return $this->getLabel() . ';' . $this->getPicture();
}
Then use this method in the property attribute:
$builder->add('icon', 'entity', array(
// ...
'property' => 'formViewData',
));
Finally use the twig split filter to separate get the two values in your template (see the example) and adapt your template (i.e. by overriding the form_label widget ) to use these instead of the original value.
{#
inside the overriden widget set the label correctly before rendering it
and extract the picture url.
#}
{% set label = label|split(';')|first|trans %}
{% set picture = label|split(';')|last %}
{{ label }}
{{ picture }}
Got the idea?

Resources