Displaying an array | Twig - php

I'm having trouble returning an array of options from an SQL database. I've tried a few different variations of returning the data, but I can only seem to get single data points returning like radio buttons, input text, etc.
I have 3 checkboxes in a form: Blue car, Red car, Green car.
They all save to the database. However, a "1" is been added. eg. [Blue car, Red car, 1] is being stored.
When I try and return the data to the twig template, it doesn't load anything.
I'm new to twig and Symfony, and I'm partly learning through existing code which makes it hard for me to troubleshoot sometimes.
I'm looking for the output to be like this: Blue car (or) Blue car & Red car (or) Blue car, Red car & Green car. Happy for the code to be simplified for this output.
var
/**
* #var string
*
* #ORM\Column(name="sel_cars", type="string", length=255, nullable=false)
*/
private $sel_cars;
/**
* Get cars
*
* #return string
*/
public function getSelcars()
{
return $this->sel_cars;
}
/**
* Set cars
*
* #param string $sel_cars
*
* #return Listing
*/
public function setSelcars($sel_cars)
{
$this->sel_cars = $sel_cars;
return $this;
}
output
{% if item.sel_cars is not empty %}
{% set sel_cars = item.sel_cars|split(',') -%}
{% set sel_carsarray = { 'bluecar': 'Blue car', 'redcar': 'Red car', 'greencar': 'Green car'} %}
{% for row in sel_cars %}
{{ sel_carsarray[row] }}
{% endfor %}
{% endif -%}
Appreciate the help :)

I seemed to have figured it out.
changing all the above output code from
item.sel_cars
to
item.Selcars
It now returns the data.

Related

Where is my twig template getting its variables?

I am trying to sort of reverse engineer to this twig template to get back to where the the variables are being set in the first place so I can add more variables. This is a Drupal8 project. The beginning of the twig template "node--course.html.twig" is seen below. Its where I see the variables being set.
{#
/**
* #file
* Default theme implementation to display a node.
*
* Available variables:
* - node: Full node entity.
* - id: The node ID.
* - bundle: The type of the node, for example, "page" or "article".
* - authorid: The user ID of the node author.
* - createdtime: Time the node was published formatted in Unix timestamp.
* - changedtime: Time the node was changed formatted in Unix timestamp.
* - label: The title of the node.
* - content: All node items. Use {{ content }} to print them all,
* or print a subset such as {{ content.field_example }}. Use
* {{ content|without('field_example') }} to temporarily suppress the printing
* of a given child element.
* - author_picture: The node author user entity, rendered using the "compact"
* view mode.
* - metadata: Metadata for this node.
* - date: Themed creation date field.
* - author_name: Themed author name field.
* - url: Direct URL of the current node.
* - display_submitted: Whether submission information should be displayed.
* - attributes: HTML attributes for the containing element.
* The attributes.class element may contain one or more of the following
* classes:
* - node: The current template type (also known as a "theming hook").
* - node--type-[type]: The current node type. For example, if the node is an
* "Article" it would result in "node--type-article". Note that the machine
* name will often be in a short form of the human readable label.
* - node--view-mode-[view_mode]: The View Mode of the node; for example, a
* teaser would result in: "node--view-mode-teaser", and
* full: "node--view-mode-full".
* The following are controlled through the node publishing options.
* - node--promoted: Appears on nodes promoted to the front page.
* - node--sticky: Appears on nodes ordered above other non-sticky nodes in
* teaser listings.
* - node--unpublished: Appears on unpublished nodes visible only to site
* admins.
* - title_attributes: Same as attributes, except applied to the main title
* tag that appears in the template.
* - content_attributes: Same as attributes, except applied to the main
* content tag that appears in the template.
* - author_attributes: Same as attributes, except applied to the author of
* the node tag that appears in the template.
* - title_prefix: Additional output populated by modules, intended to be
* displayed in front of the main title tag that appears in the template.
* - title_suffix: Additional output populated by modules, intended to be
* displayed after the main title tag that appears in the template.
* - view_mode: View mode; for example, "teaser" or "full".
* - teaser: Flag for the teaser state. Will be true if view_mode is 'teaser'.
* - page: Flag for the full page state. Will be true if view_mode is 'full'.
* - readmore: Flag for more state. Will be true if the teaser content of the
* node cannot hold the main body content.
* - logged_in: Flag for authenticated user status. Will be true when the
* current user is a logged-in member.
* - is_admin: Flag for admin user status. Will be true when the current user
* is an administrator.
*
* #see template_preprocess_node()
*
* #todo Remove the id attribute (or make it a class), because if that gets
* rendered twice on a page this is invalid CSS for example: two lists
* in different view modes.
*
* #ingroup themeable
*/
#}
{# {{ kint() }} #}
<article id="node-{{ node.id }}" {{ attributes }}>
{{node}}
{{ title_prefix }}
{% if not page %}
<h2{{ title_attributes }}>
{{ label }}
</h2>
{% endif %}
{{ title_suffix }}
{% if node.field_packaging.value == '1' %}
{% set image = content.field_image %}
{% set ce = content.field_tax_credit_hours %}
{% set goal = content.field_goal %}
{% set target_audience = content.field_audience %}
{% set objectives = content.field_objectives %}
{% set accreditation = content.field_accreditation %}
{% set disclosure = content.field_disclosure_statement %}
{# {% set references_old = content.field_references %} #}
{% set references = content.field_references_par %}
{% set appendix = content.field_appendix %}
{% set faculty = content.field_faculty %}
{% set related_courses = content.field_related_courses %}
{# set suggested_courses = content.field_suggested_courses #}
{% set additional = content.field_callout %}
{% set expiration = node.field_expiration.value %}
I have tried taking words that appear to be unique like
field_tax_credit_hours
And search the project to see maybe where its being set but it only appears in other twig files. I also looked at the whole page as a whole to see maybe I can search for where the output is coming from. For example they very start of my page begins with:
<!-- returning result -->
When I search that it points me to a php function called getResult()
public function getResult() {
if ($this->rowBase() == "") {
print "<!-- rowBase empty -->";
\Drupal\Core\Database\Database::setActiveConnection();
return false;
}
print "<!-- returning result -->";
$result = $this->connection->query($this->rowBase())->fetchAll();
\Drupal\Core\Database\Database::setActiveConnection();
return $result;
}
searching for rowBase() i found this function:
public function rowBase() {
if (parent::accessCheck()) {
$sql = "SELECT * FROM learning_courseuser
WHERE idUser = " . $_SESSION['public_area_idst'] .
" AND idCourse = " . $this->ID. " ";
return $sql;
} else {
return "";
}
}
So it appears to not set the variables I need but instead returns the users info if the are logged in. So I am now stuck and don't really know where to go from here. I have been a PHP developer for a year or so and only did a team treehouse drupal course so it was very basic.
I noticed the page also returns this
<!-- BEGIN OUTPUT from 'themes/custom/site/templates/node--course.html.twig' -->
But searching for the string "BEGIN OUTPUT" returns nothing. So I don't know where to go from here.
It seems that the variables are coming from the "content" object but searching content in the project has WAY too many results to go through. Any ideas where to look would be fantastic.
UPDATE
I was asked to look into template_preprocess_node
and got this:
function site_preprocess_node(&$variables) {
$node = \Drupal::routeMatch()->getParameter('node');
if ($node && $node->getType() == 'course') {
$noti = new FormaNotification();
print "HERE";
print_r($noti->getResult());
exit;
if ($noti->getResult()) {
$variables['signIn'] = "yes";
if ($noti->getFormaAdmin())
$variables['is_forma_admin'] = "yes";
else
$variables['is_forma_admin'] = "no";
} else {
$variables['signIn'] = "no";
$variables['is_forma_admin'] = "no";
}
$current_url = Url::fromRoute('<current>');
$variables['signURL'] = 'http://' . $_SERVER['HTTP_HOST'] . $current_url->toString();
if ($node->get('field_packaging')->getValue()[0]['value'] == '2') {
$variables['regis'] = true;
} else {
$reg = new FormaRegis();
$reg->setConnection('docebo');
$reg->setID($node->get('field_docebo_course_id')->getValue()[0]['value']);
$result = $reg->getResult();
if(!empty($result)) {
$variables['regis'] = true;
} else {
$variables['regis'] = false;
}
}
} // course
}
So looking at it, it appears to have some function of registration sign in and not the variables
The answer is into CMS.
The machine name starting with field_* usually is made when you create a new field into a content type on CMS.
Login into cms (/user) and search for structure-> content types -> (your content types) and then manage fields.
You should find it.

get a list of all the object properties of different users that a user is following - symfony

I am building a books application where by for a user to see the books you upload he/she must follow you or become your friend.
The application is made up 3 entities Books, Users and Follow.
Here is a sample structure Follow table
id | followered_id | followed_id
1 | 1 | 2
2 | 1 | 3
3 | 2 | 1
From the above illutration user 1 is following/friend to 2 and 3. So all their books should appear on his profile. In the controller below I am able to come up with an attempt but I have to click on each user to view the books he has uploaded
$em = $this->getDoctrine()->getManager();
$me = $this->getAuthedUser(1);
$follows = $em->getRepository("AppBundle:Follow")->findBy(["follower" => $me]);
$followeds = [];
foreach ($follows as $follow) {
$followeds[] = $follow->getFollowed();
}
$followables = $em->getRepository("AppBundle:User")->findAll();
return $this->render("#App/index.html.twig", [
"me" => $me,
"followeds" => $followeds, //this
"followables" => $followables,
]);
below is the view of the above controller method
<h1>Welcome, {{ me.username }}!</h1>
<h2>Your followed people:</h2>
{% if followeds is not empty %}
<ul>
{% for followed in followeds %}
<li>{{ followed.username }} (see his profile)</li>
{% endfor %}
</ul>
{% else %}
you don't follow anyone yet.
{% endif %}
Here is the entity snippet of Following declarations
/**
* #var User
*
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\User")
*/, Kindly help me to get out of this.
and tell me if any further information is needed. Thank you in advance.
private $follower;
/**
* #var User
*
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\User")
*/
private $followed;
my present challenge is to be able to see all of the properties of a book published by a user e.g bookname, publisher etc that I am Following without clicking on the user that uploaded it.
{% for followed in followeds %}
<li> <!-- your followed profile link etc.--> </li>
{% if followed.books %}
<ul>
{% for book in followed.books %}
<li>{{ book.title }}</li>
{% endfor %}
<ul>
{% endif %}
{% endfor %}

Symfony3 - MISD Phone Number Bundle format

Is it possible to set the format returned by the entity containing a phone number property when using MISD Phone-Number-Bundle? For example I have a property $phoneNumber
When I call $this->getPhoneNumber() it returns the string formatted:
Country Code: 1 National Number: ########## Country Code Source:
but I want it in the format (or similar):
1 (###) ###-####
The reason I want to change this is because in that entity I am implementing the __toString() method and want the string returned to be a combination of 2 properties one being the "nickName" and other being the phone number in this type of format or similar NickName - 1 (###) ###-#### The purpose of this is to display them in a drop down form element setup in a form type I created.
Phone number is instance of libphonenumber\PhoneNumber. This class has __toString method, which returns not formated debug information about object's properties
https://github.com/giggsey/libphonenumber-for-php/blob/master/src/PhoneNumber.php
I have formated phone number with temlate option with SonataAdminBundle:
$listMapper
->add('phoneNumber', PhoneNumberType::class, [
'template' => ':CRUD:phoneNumber_list_field.html.twig'
]);
Template :CRUD:phoneNumber_list_field.html.twig contents:
{% extends 'SonataAdminBundle:CRUD:base_list_field.html.twig' %}
{% block field %}
{% if object.phoneNumber is null %}
-
{% else %}
{{ object.phoneNumber|phone_number_format(2) }}
{% endif %}
{% endblock %}
Here argument 2 for twig filter is \libphonenumber\PhoneNumberFormat::NATIONAL
https://github.com/giggsey/libphonenumber-for-php/blob/master/src/PhoneNumberFormat.php
I think I solved my own problem... My __toString() method looks like this and seems to do what I want.
use libphonenumber\PhoneNumberUtil;
//...
public function __toString()
{
$phoneNumberUtil = PhoneNumberUtil::getInstance();
$number = $phoneNumberUtil->format($this->phoneNumber, \libphonenumber\PhoneNumberFormat::NATIONAL);
return $this->nickName . " - " . $number;
}
Anyone see any issues or better ways to do this?

Symfony 2 Form Errors

i want to have a simple
{{ form_errors(form) }}
call in twig for all my validation errors.
But this is not working.
Only when i call a field specifically i get the validation message back, but only for this field.
Is it possible to return all my validation messages in one simple {{ form_errors(form) }} call ?
example of my entity validation :
/**
* #var string
*
* #ORM\Column(name="pdb_domain_account", type="string", length=255, nullable=false)
* #Assert\NotBlank(
* message = "The field name cannot be empty")
* #Assert\Regex("/^[A-z]+$/",
* message = "Only letters are allowed for the relation name.")
*/
private $pdbDomainAccount;
this is working for one field :
{{ form_errors(form.pdbDomainAccount) }}
You need to make sure that your form types are setting error-bubbling to true, so they pass the errors to the parent form, and then you can use {{ form_errors(form) }}
From Symfony2 doc:
If true, any errors for this field will be passed to the parent field
or form. For example, if set to true on a normal field, any errors for
that field will be attached to the main form, not to the specific
field.
http://symfony.com/doc/current/reference/forms/types/text.html#error-bubbling

Symfony form & entity & choice constraint confusion

I've got Doctrine entity with some choice field, let's say that it looks like this:
/**
* #var string
* #ORM\Column(name="color", type="string", nullable=false)
* #Assert\Choice(choices = {"red", "green", "blue"}, message="Choose valid color")
*/
protected $color;
And now I've got a form that's associated with my entity, let's say that specific field looks like that inside of it:
$builder->add(
'color',
'choice',
array(
'choices' => array(
'red' => 'Red like roses',
'green' => 'Green like grass',
'blue' => 'Blue like sky'
),
'expanded' => true
)
);
As far as I'm now, it's quite clear that possible values are duplicated inside constraint and inside the form. But let's go further, I'd like to display my entity inside of a template, so I must do something like that:
{% if entity.color == 'red' %}
Red like roses
{% elseif entity.color == 'green' %}
Green like grass
{% elseif entity.color == 'blue' %}
Blue like sky
{% endif %}
So we've now got a third place where not only values, but also labels are duplicated. I've thought of something like a service that serves as a twig extension and can be injected into the form builder but it doesn't solve duplication with constraint. Now I've got no idea how to solve it, I'd really like to have just one single place where I define things like that and most of all I'd like to keep them inside of entity as annotations but I don't know how to proceed with this.
Any ideas?
Instead of hardcoding the choices in your mapping, you should provide them with a callable. You could use my enum package for that.

Categories