How to show Type name in Twig - symfony

I have 2 tables: Product and Type. Relationship is One Type has Many Product
Type: id, name
Product: id, name, type_id
I dont know how to show type name in Twig, I'm new in Symfony and here is my code:
<div>
{% for pro in product %}
<div>Product name: {{ pro.name }}</div>
<div>
Type name:
</div>
<div>Price: {{ pro.price }}</div>
<div>
{% for img in pro.images %}
<img src="{{ "/uploads/product/" ~ img.path }}" style="height: 100px;">
{% endfor %}
</div>
{% endfor %}
</div>

You can access the properties of an object in Twig. You should not look at your database, but the way your entities are made. Your Product has a $id, $name and $type. Type has $id and $name.
In Twig you can do {{product.name}}
To get the type, you want {{product.type}}
To get the name of the type, you want {{product.type.name}}
So, in your code, that would be:
<div>
Type name: {{ pro.type.name }}
</div>
Internally, the Twig parser will get $product and check if it has the method getName() when you do {{product.name}}. That same logic applies to {{product.type.name}}. It checks if $product has getType(), then if that has getName(). The PHP equivalant is $product->getType()->getName().
You almost never should type an actual method in your code. If you have to, you might want to take a step back and re-evaluate, because it often is a code smell.

You can just add {{ pro.type.name }} to your code:
<div>
{% for pro in product %}
<div>Product name: {{ pro.name }}</div>
<div>
Type name: {{ pro.type.name }}
</div>
<div>Price: {{ pro.price }}</div>
<div>
{% for img in pro.images %}
<img src="{{ "/uploads/product/" ~ img.path }}" style="height: 100px;">
{% endfor %}
</div>
{% endfor %}
</div>
And be sure that type attribute refer to Type entity. Your product entity should have type attribute like below:
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Type", inversedBy="products")
* #ORM\JoinColumn(nullable=false)
*/
private $type;
// getter
public function getType()
{
return $this->type;
}
And your Type entity should have products attribute like below:
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\Type", mappedBy="type")
* #ORM\JoinColumn(nullable=true)
*/
private $products;
public function getProducts()
{
return $this->products;
}

Related

Symfony - dropdown list with entity.propriety filter

i have 3 entities named Answer, Skill and Jointure.
Answer and Skill are linked to Jointure with a ManyToOne relation.
I display them in twig like that :
class HomeController extends AbstractController
{
/**
* #var JointureRepository
*/
public function __construct(JointureRepository $repository, ObjectManager $em)
{
$this->repository = $repository;
$this->em = $em;
}
/**
* #Route("/", name="home")
*/
public function index()
{
$JointureRepository = $this->getDoctrine()->getRepository(Jointure::class);
$arrJointures = $JointureRepository->findAll();
$this->em->flush();
return $this->render('pages/home.html.twig', [
'controller_name' => 'HomeController',
'jointure' => $arrJointures,
]);
}
}
and in my twig view :
{% for object in jointure %}
{% for skill in object.skills %}
{{skill.label}}
{% endfor %}
{% endfor %}
I've created a dropdown button who list all the skill.label properties who exists like that :
EDIT : Here my twig button :
<div class="form-group ">
<select id="inputState " class="form-control">
<option selected>Compétence</option>
{% for object in jointure %}
{% for skill in object.skills %}
<option>{{skill.label}}</option>
{% endfor %}
{% endfor %}
</select>
</div>
</div>
<div class="col-md-2">
<button type="submit" class="btn btn-primary btn-block">Search</button>
</div>
</div>
I want to show / display all answer.userEmail who have this related skill.label in a view in my template.I have to use EntityType ? Many thanks
You should start using Symfony Forms. Here is documentation https://symfony.com/doc/current/forms.html. It is not that simple at the beginning but it definitely worith it. Then you will be able to use EntityType https://symfony.com/doc/current/reference/forms/types/entity.html

Symfony PUGX Bundle - Passing custom variables

I use PUGX Bundle for managing my users.
I want simply pass to the registration template, somes custom variables, but I don't know how to do !
Here the code of the controller :
/**
* #Route("/register", name="company_registration")
*/
public function registrationCompanyAction(Request $request)
{
return $this->container
->get('pugx_multi_user.registration_manager')
->register('AppBundle\Entity\Company');
}
Where can I do ?
Custom variables can be rendered in templates if they are defined in the form type shown in config.yml, e.g.,
config.yml
...
pugx_multi_user:
users:
staff:
entity:
class: Truckee\MatchingBundle\Entity\Staff
# factory:
registration:
form:
type: Truckee\UserBundle\Form\StaffFormType
name: staff_registration
validation_groups: [Registration, Default]
template: TruckeeUserBundle:Staff:staff.form.html.twig
Form type
class StaffFormType extends BaseType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
parent::buildForm($builder, $options);
$builder
->add('organization', new OrganizationType())
;
}
public function getName()
{
return 'staff_registration';
}
...
}
staff form template
{% block content %}
<h4 onclick="orghelp();" title="Click for help">{{label_info('Staff Registration Form <span class="glyphicon glyphicon-question-sign"></span>') }}</h4>
<div id="dialog"><style>.ui-dialog-titlebar-close {
display: none;
}</style></div>
{% block fos_user_content %}
{% include 'TruckeeUserBundle:Staff:staff_content.html.twig' %}
{% endblock fos_user_content %}
{% endblock %}
content template
{% trans_default_domain 'FOSUserBundle' %}
<form action="{{ path('staff_registration') }}" method="POST" class="form-inline">
{%if form._token is defined %}{{ form_widget(form._token) }}{% endif %}
{{ bootstrap_set_style('form-inline') }}
{% include "TruckeeUserBundle:Person:person_manage.html.twig" %}
<p><strong>Organization</strong></p>
<div id="orgNotice"></div>
{% set staff = form %}
{% set form = form.organization %}
<div id="orgForm">
{% include "TruckeeMatchingBundle:Organization:orgForm.html.twig" %}
<div>
{{ bootstrap_set_style('') }}
{% set form = staff %}
{{ form_widget(form.save) }}
</div>
</div>
</form>

uniqueEntity message

i've created a form with symfony 2, and i check if the fields are unique with the UniqueEntity constraint. But i want the fields "firstname", "name" to appear in the message, like:
"Mark Blaze already exists!" rather than "this person already exists!"
can someone help?
part of the form builder
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('firstname')
->add('name')
Entity
/**
* #ORM\Entity
* #ORM\Entity(repositoryClass="InviteRepository")
* #UniqueEntity(fields={"firstname","name"}, message="this person already exists!")
*/
class Invite {
/**
* #ORM\Column(type="string",length=50)
*/
private $firstname;
/**
* #ORM\Column(type="string",length=50)
*/
private $name;
twig file
{{ form_start(form) }}
{{ form_errors(form) }}
{% spaceless %}
<div class="control-group">
{{ form_label(form.firstname, 'firstname *', { 'label_attr': { 'class':'control-label'} }) }}
{{ form_errors(form.firstname) }}
<div class="controls">
{{ form_widget(form.firstname) }}
{% if form.vars.help is defined %}
<span class="help-block">{{ form.vars.help }}</span>
{% endif %}
</div>
</div>
{% endspaceless %}
{% spaceless %}
<div class="control-group">
{{ form_label(form.name, 'name *', { 'label_attr': { 'class':'control-label'} }) }}
{{ form_errors(form.name) }}
<div class="controls">
{{ form_widget(form.name) }}
{% if form.vars.help is defined %}
<span class="help-block">{{ form.vars.help }}</span>
{% endif %}
</div>
</div>
{% endspaceless %}
Much thanks
In theory you can use this in the error message {{ value }} and this will represent the sent value. I use this in the emailconstraint so, 'The {{ value }} email address already in use'.
I think this would work for you too.
I rechecked your constraint and sadly, there you don't have the option to set a dynamic value. What I posted earlier was a solution for a really symfony validation and this constraint is part of doctrine. But any time, you can create your own constraint, if you want to fulfil your special needs:
$this->context->addViolationAt($errorPath, $constraint->message, array(), $criteria[$fields[0]]);

Dynamically remove Options from symfony2 choice (entity) form

I have a Entity Type form where I list all the friends of the current user. This is e.g. used for creating a new Group. Now I want to use the same form for adding people to the same group, so the Choice field should show all the friends of the current user that are not yet in the group. I thought I just use a form event to remove the options(users) that are already in the group.
My listener looks like this:
class FriendSelectListener implements EventSubscriberInterface {
public static function getSubscribedEvents() {
// Tells the dispatcher that we want to listen on the form.pre_set_data
// event and that the preSetData method should be called.
return array(FormEvents::PRE_SET_DATA => 'preSetData');
}
public function preSetData(FormEvent $event) {
$betRound = $event->getData();
$form = $event->getForm();
$groupForm = $form->get('userGroup');
$usersForm = $groupForm->get('users');
foreach($betRound->getUserGroup()->getUsers() as $user){
if($usersForm->has($user->getId())){
$usersForm->remove($user->getId());
}
}
}
}
But I can't render it, because in my test I removed the user with the id 2 and then I get the following error message while rendering:
Key "2" in object (with ArrayAccess) of type
"Symfony\Component\Form\FormView" does not exist in
/var/lib/stickshift/1ed1210eec124c179c45aac4ad484afd/app-root/data/269891/src/Strego/UserBundle/Resources/views/Form/selectFriends.html.twig
at line 5
Update:
This might be related to my view:
{% for id, choice in choices %}
{% set user = choice.data %}
<label>
<div class="people-list people-choose unselected" style="width:270px;">
<img src="{{ user.profilePic | imagine_filter('profile_thumb') }}" class="img-polaroid" alt="{{ user.nickname }}">
{#<img src="{{ asset('bundles/stregoapp/img/profile-thumb-90x90.png') }}" alt="Profilbild" class="img-polaroid">#}
<p>{{ form_widget(form[id]) }} <span class="label">einladen</span></p>
<h3>{{ user.nickname }}</h3>
<h3><small>{{ user.firstName }} {{ user.lastName }}</small></h3>
</div>
</label>
{% endfor %}
For me it seems like I only removed the form element but not the choice.
I found the problem, it was indeed my view. As soon as I stopped iterating over the options but used the child elemts of my form element it was working:
{% for child in form %}
{% set user = choices[child.vars.value].data %}
<label>
<div class="people-list people-choose unselected" style="width:270px;">
<img src="{{ user.profilePic | imagine_filter('profile_thumb') }}" class="img-polaroid" alt="{{ user.nickname }}">
<p>{{ form_widget(child) }} <span class="label">einladen</span></p>
<h3>{{ user.nickname }}</h3>
<h3><small>{{ user.firstName }} {{ user.lastName }}</small></h3>
</div>
</label>
{% endfor %}

Symfony 2 - Access mapped Object property form twig

I hava a entity with the following flied:
/**
* #ORM\ManyToOne(targetEntity="Document", inversedBy="posts")
* #ORM\JoinColumn(name="document_id", referencedColumnName="id")
*/
protected $image;
which I get with the following method:
public function indexAction() {
$posts = $this->getDoctrine()
->getRepository('airpaprcms2Bundle:Post')
->findByPageType(1);
if (!$posts) {
throw $this->createNotFoundException('No posts in Database!');
}
return $this->render('airpaprcms2Bundle:Default:index.html.twig', array('posts' => $posts));
}
How can I access a property of the mapped object form within twig? I tried post.image.file (the mapped entity Document has a property file)
{% for post in posts %}
<div>
<h1>
{{ post.title }}
</h1>
<p>{{ post.text }}</p>
<img src="{{ post.image.name }}" alt="{{ post.title }}" />
</div>
{% endfor %}
and get the following error message:
Item "file" for "" does not exist in airpaprcms2Bundle:Default:index.html.twig at line 11
What is the right syntax to access the mapped document property?
You can access the property of your linked entity with the following twig syntax:
{% for post in posts %}
{{ post.entityName.propertyName }}
{% endfor %}
In your case that would be:
{% for post in posts %}
{{ post.image.propertyName }}
{% endfor %}
Be sure to check that all post entities are linked to an image object. If one post entity has no link to an image, you will get a property not found error when trying to render your page.

Resources