How to display the title of the node in plain text in TWIG on Drupal 8? - tags

I created TWIG for my node, my products, my groups and my stores.
I'm on Drupal 8. For my nodes, I want to display the title. I use the following code:
{{ label }}
But there is the markup inside and I do not want it. So I tried the following code and it works. But is it a good practice ?
{{ label.0 }}
How to display the title of the node in plain text in TWIG on Drupal 8 ?

When using the node.html.twig or a child of that template, you will have access to the node variable, which is a limited implementation of the node object.
From the comments for the classy theme node.html.twig file:
* - node: The node entity with limited access to object properties and methods.
* Only method names starting with "get", "has", or "is" and a few common
* methods such as "id", "label", and "bundle" are available. For example:
* - node.getCreatedTime() will return the node creation timestamp.
* - node.hasField('field_example') returns TRUE if the node bundle includes
* field_example. (This does not indicate the presence of a value in this
* field.)
* - node.isPublished() will return whether the node is published or not.
As is described in that comment, the value of the node title without any markup can be accessed in twig by using:
{{ node.label }}.

Related

Symfony 2.6.3 {{ form_errors( form ) }} is blank when isValid() returns false

I'm using Symfony V2.6.3
I have a simple form with three fields based on a Type class.
The Entity class that the Type class specifies via setDefaultOptions() has the use Symfony\Component\Validator\Constraints as Assert; statement.
Each field has an #Assert\NotBlank() constraint in the Entity class.
CSRF is enabled.
HTML5 validation is disabled.
If I submit the form with all fields blank, the following happens:
In the controller:
isValid() returns false
getErrors( true ) returns an error for each field
In the template:
{{ form_errors( form ) }} generates no text for the form or any of the fields.
I created a custom form theme and modified {% block form_errors %} to
dump the errors variable. The dump shows the errors property is a FormErrorIterator object with two properties: form, which is, I believe the field definition, and errors which is an empty array.
Oddly enough, drilling down into the form property reveals an errors property that is an array with a single FormError object that contains the error message.
This is not my first time using forms. It has worked just fine for me in the past. Could this be a new bug in 2.6?
I have searched for this and all I found were situations where getErrors() was also returning nothing.
Thanks in advance,
Dave
Okay. I finally found the answer to this question.
Many thanks to thenetimp on the Symfony forum. He had the same problem and figured it out (http://forum.symfony-project.org/viewtopic.php?f=23&t=42841&p=135003&hilit=form_errors#p135003).
Turns out that you have to call createView() after calling isValid(). That actually makes sense when you think about it.
Form errors are bound to a FormType, not to the complete Form. The RootType will only contain the errors that bubbled up from sub types. The sub types will only contain the errors of their type and the ones bubbled up from sub sub types, etc.
Doing {{ form_errors(form) }} will only render the errors of the root form. Assume there was an error on a form.name field, you can get this error by doing: {{ form_errors(form.name) }}.

Laravel 4 - get data from multiselect form

I'm using Laravel 4, and I have two tables related 'Many to many': 'Actividad' and 'Material'. Every Actividad can have one or more Materials, and every Material can belong to one or more Actividad.
So, I have made a form to create a new Actividad where you can save one or more Materials. I've done that with a multiselect input. Like that:
{{ Form::label('material_id', 'Material necesario:') }}
<p>{{ Form::select('material_id', $material_id, Input::old('material_id'), array('multiple')) }}</p>
I don't know if I'm doing correctly but, before saving anything, my first problem is that I'm only obtaining one result. I suppose I should get every option 'checked' in the form... The relevant part of my Controller is:
$material = Input::get('material_id');
return var_dump($material);
I should obtain a list of options selected, but the result of that in my browser is:
string(1) "1"
This is the first time I'm working with tables related in this way, and probably I'm doing something wrong (in the form, in my controller, in my Models,...)
Thank you very much for your help!!
Just change your code to this
{{ Form::select('material_id[]', $material_id, Input::old('material_id'), array('multiple')) }}
I hope this helps.
if you are using custom response handlers on the client side such in the case of submitting info with AJAX, all you need to do is to simple add "[]" to the name of the select control.
e.g.
<select name="material_id[]" multiple>
This is the same case as with regular PHP. The other methods are required if you want Laravel to handle the form elements for you when rendering a new response/view. ( page reload ). This reload doesn't happen with REST requests.

How to set a my own form representation for my own type

I have created my own form type in my Symfony 2 project whose a child of the date type. I call it in the controller :
$form = $this->createFormBuilder($customer)
->add('my_own_field_name', 'my_own_date_type', array())
->getForm();
In the twig template :
{{form_row(form.my_own-field_name)}}
Is it possible to say to Symfony2 to call my own twig for a representation of this field through the 'form_row' function instead of having the date type representation
Thank you
Consider having a look at this part of the official SF2 documentation.
As told in the doc, the getName method of your custom type helps SF2 find a custom form renderer. As your type name is my_date_type, SF2 will try to look for a my_date_type_widget block in a configured form templates list (as shown at the end of this post and in the official doc).
You just have to create a template fields.html.twig in your bundle resources/views/Form/ folder that specifies this block as shown in the doc and add your own logic in it.
Don't forget to add the config lines
# app/config/config.yml
twig:
form:
resources:
- 'YourOwnBundle:Form:fields.html.twig'
to tell symfony to always use this to render this form type.

Mapping a deeply-nested property_path to a parent form

I'm building a form in Symfony 2 whose fields will vary depending on how the corresponding entity is configured.
Briefly, each entity has a set of "detail" fields that can hold different types and configurations of data.
For example, a Project entity might have the following configuration:
url renders as a text input and validates as a URL with max length of 300 chars.
description renders as a textarea with no validation constraints.
logo renders as a file input and validates as an image file with max dimensions of 500x500.
And so on. The part that makes this interesting is that all of this is configured via database tables so that an administrator could change the configuration of these models via a UI.
The (relevant part of the) database structure looks something like this:
project stores the Project records.
project_detail stores the value of each detail field for each Project.
detail_type defines the type and configuration for each detail field.
detail_type_assignment defines which detail types are available for each entity and the order in which the fields should display on forms.
Everything is working great so far except for rendering error messages in forms.
When any of these detail fields generates a validation error, it is displayed at the top of the form:
Note in the above image, "EIN" is a field that exists in the Project entity (i.e., implemented the normal way for a Symfony form), while "URL" and "Logo Upload" are implemented as detail fields.
Here's what the ProjectType looks like:
class ProjectType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('ein', 'ein')
;
/* Add detail fields to the form builder. */
foreach($this->getDetailTypes() as $detailType)
{
$slug = $detailType->getSlug();
$formatter = $detailType->createFormatterInstance('');
$builder->add(
$slug
, $formatter->getFormFieldType()
, $formatter->getFormFieldOptions()
);
/* E.g.,
*
* $builder->add(
* 'url'
* , 'text'
* , array('label' => 'URL', ...)
* )
*/
}
}
...
}
I'm pretty sure what's going on here is that the ViolationMapper can't translate the property_path correctly.
For example, at runtime, the property_path of the url value is project.details[url].value, but the field is located at project.url.
I would prefer not to construct a complex form hierarchy so that the position of each field matches its property_path. Is there a way I can change path that violations get added to in the ExecutionContext?
In your view I feel like you shouldn't use form(form) inside of form_start(form) and form_end(form). I believe that would generate the <form> tag twice
Old answer:
Idk what your twig looks like but I'm assuming somehow the error in the form row isn't being displayed. http://symfony.com/doc/current/book/forms.html#rendering-a-form-in-a-template talks about it.
From the link:
{# src/Acme/TaskBundle/Resources/views/Default/new.html.twig #}
{{ form_start(form) }}
{{ form_errors(form) }}
{{ form_row(form.task) }}
{{ form_row(form.dueDate) }}
{{ form_end(form) }}
Take a look at each part:
form_start(form) - Renders the start tag of the form.
form_errors(form) - Renders any errors global to the whole form (field-specific errors are displayed next to each field);
form_row(form.dueDate) - Renders the label, any errors, and the HTML form widget for the given field (e.g. dueDate) inside, by default, a div element;
form_end() - Renders the end tag of the form and any fields that have not yet been rendered. This is useful for rendering hidden fields and taking advantage of the automatic CSRF Protection.
form_row can be split into each of its parts:
<div>
{{ form_label(form.task) }}
{{ form_errors(form.task) }}
{{ form_widget(form.task) }}
</div>
and the form_errors() function should display what you want.

Generate subform in ajax call

I have a form with collection of subforms - student with different studies - relation manyToOne. I have corrent database schema and entities and form builder works well. I don't know how to append new "study" object. I need to get html tags from somewhere in either cases - when there is at least one "study: object (clone him) or there is no such a one.
Let's assume that study object has 2 fields: name and year. If for a student there is such a record (object) it's first input in generated form has name "student[study][0][name]". And is surrounded by . When I click "Add new study" button I want to duplicate this surrounding div and change id's and name's of html form elements respectively. Is there ready library or method to use?
But there may happen there is no study records so far. So I need to get form from server through ajax call. Unfortunately returned form has inputs with names like "study[name]". Is it possible to render this form similar to first case - I mean "student[study][0][name]". But i'd like to avoid manually generate twig template for form - I prefer
{{ form_widget(form) }}
You should be dealing with data-prototype rather than issuing separate AJAX request. The whole concept of adding/removing subform items is described here:
http://symfony.com/doc/current/reference/forms/types/collection.html#adding-and-removing-items
Obviously, you will need to some JS (jQuery is highly recommended) in order to replicate subform fields.
You should note, however, that data-prototype behaves differently when you initially have empty or non-empty collection. At least I have encountered this weird behavior. As far as I remember, in first your when you say {{ form_rest(form) }} additional DIV is appended with data-prototype attribute consisting of form's HTML. In second case actual HTML (not as an attribute) is appended with ID attribute "form_name_$$name$$" where you need to replace $$name$$ with proper index.
Now, you really should take a look - maybe all this has been fixed in some recent versions but I can't be sure...
Hope this helps a bit...