Angular2 passing value to backend in one array - angular2-routing

I have a posts component and in that post component I am fetching users id and commentor's id those who comment on the posts from post microservice and showing that in posts index page. I have a post microservice and user microservice. Now I want to send the ids of user's and commentor's to users microservice and want to fetch the name of them and display that in posts index page.
In posts index page it is showing like this:
Posts user commentor
A 1 3
B 6 5
C 9 4
So, in place of 1 3 6 5 9 4 I want to display the name of them and user_id and commentor_id is in one table in user_microservice. In index.html I am displaying the id's like this
<tr *ngFor="let post of posts" >
<td>{{ post.name }}</td>
<td>{{ post.user_id }}</td>
<td>{{ post.commentor_id }}</td>
</tr>
Could anyone please help me? Thanks.

As far as I understand you need something that loads i.e. the user display name from the microservice.
For that case you should create a small component that can do that.
The code then might look like that:
<td><app-user-name [userid]="post.user_id"></app-user-name></td>
In the component app-user-name you need an input parameter
#Input() userid: string = ''
In the ngOnInit() you then should pick up that value and call the service and load the user display name.
Similar to that:
ngOnInit(){
this.someservice.getUserName(this.userid)
.subscribe(data => this.username = data)
....
}
In the template of that component you just need to display the {{username}}
The username is displayed as soon as it is loaded.

Related

Dynamic table in JSP and Spring MVC

I am writing an application using Spring MVC and Hibernate. In one of my application pages, the JSP page consists of dynamically generated tables based on the criteria specified by the end-user. For example, the end-user enters the "number of employees" on the page and upon clicking submit, the next page shows all the companies that have a number of employees equal to or greater than the value entered by the end-user. For each company, a separate / individual table is generated, header of the table shows the name of the company from database (This part is working completely fine). Now in the table for the company itself, I want to display data for that company only and likewise, every table header will display the name of the company and the data for that company only. Any ideas of how can I display the data for company in the table. Below is my code
Controller
Int numberOfemployees // This value is entered by the end user
List<Company> companies = companyService.listAllCompany(numberOfEmployees );
ModelAndView companiesResults = new ModelAndView("companies-result");
CompanyForm companyForm = new CompanyForm();
companyForm.setCompanies(companies);
companiesResults.addObject("company", companies);
for (Company company : companies) {
int company_id = company.getCompany_id(); //Get id of the company to get its attributes/data from database
List<CompanyAttribute> companyAttributes =companyService.listCompanyAttributes(company_id);
}
companyForm.setCompanyAttributes(companyAttributes);
companiesResult.addObject("companyForm", companyForm);
companiesResult.addObject("companyAttributte", companyAttributes);
}
Below is my JSP
<c:forEach items="${companyForm.companies}" var="company" varStatus="status">
<h6>${company.company_name}</h6>
<div class="table-responsive">
<table>
<thead>
<tr>
<th>Company portfolio</th>
<th>Company points</th>
</tr>
</thead>
<tbody>
<c:forEach items="${companyForm.companyAttributes}" var="companyAttribute" varStatus="status">
<tr>
<td>${companyAttribute.portfolio}</td>
<td>${companyAttribute.points}</td>
</tr>
</c:forEach>
</tbody>
</table>
</c:forEach>
I will appreciate any ideas on how can I display data for each company in its table. My approach is showing me empty table for every company. Should I use some kind of scripplet in JSP page or is there any other approach. I am new to JSP and Spring MVC, any ideas will be appreciated.
I had a similar problem a few years ago and solved it that way:
// In my controller
mav.addObject("order", order);
// In my jsp
<c:forEach items="${order.articles}" var="article">
...
</c:forEach>
This is not working. But then I tried this
// In my controller
mav.addObject("articles", order.getOrderArticles());
// In my jsp
<c:forEach items="${articles}" var="article">
it works as expected. As you can see I added the list of articles as another object in my model. And then it is possible to iterate over this object in the jsp.

Display dynamically informations in a Symfony layout

I have a layout included in another one that display my menu. The labels of my menu items need to be dynamic (like the unread messages number of a mailbox). Then I did this :
My orders
(
{{ render(controller('MyController', {'etat':2})) }}
<span style="color:red">with {{ render(controller('MyController', {'etat':2})) }} in late</span>
)
I would like to display labels according to the number that return my controller. I don't know how to get it in a variable.
When rendering your template in your controller
return $this->render('twig_template_name.html.twig', array('variable_name' => $variable);
you pass a variable to the twig template in the array of options as I showed. Your code
{{ path('mypath',{'etat': '2' }) }}
prints a path defined in the routing.yml under the 'mypath' section and ends up adding a GET request variable to the link ('?etat=2'), if 'mypath' showed an absolute route 'www.website.com/yourpath',
{{ path('mypath',{'etat': '2' }) }} would produce 'www.website.com/yourpath?etat=2', which would send your controller for a route /yourpath/{etat} a variable etat with a value of 2 so all you need to do now is change 2 with an actual dynamic value which you receive from another controller.
I am not sure what etat is but lets say it's an article and it has it's id, you have a blog page with lots of articles and the controller that prints them all out sends an array of articles to the twig template, on your twig template you do something like:
{% foreach article in articles %}
{{ article.title }}
{{ article.story }}
read more
{% endforeach %}
And you end up something like:
Catchy Title
Awesome story about code without bugs and where deadlines depend on how creative and well designed and implemented the solutions are
[read more]
and you ofcourse click on "read more" and end up on the url ~/article/2 because the article had an id of 2, your controller for that url receives a variable id in the request, you do a $id = $_GET['id']; and grab the article from the repository and send it to the template.
Hopefully this answered your question, I am very tiered so forgive me if i was confusing which I surely was.

Using repository class methods inside twig

In a Symfony2.1 project, how to call custom entity functions inside template? To elaborate, think the following scenario; there are two entities with Many-To-Many relation: User and Category.
Doctrine2 have generated such methods:
$user->getCategories();
$category->getUsers();
Therefore, I can use these in twig such as:
{% for category in categories %}
<h2>{{ category.name }}</h2>
{% for user in category.users %}
{{ user.name }}
{% endfor %}
{% endfor %}
But how can I get users with custom functions? For example, I want to list users with some options and sorted by date like this:
{% for user in category.verifiedUsersSortedByDate %}
I wrote custom function for this inside UserRepository.php class and tried to add it into Category.php class to make it work. However I got the following error:
An exception has been thrown during the rendering of
a template ("Warning: Missing argument 1 for
Doctrine\ORM\EntityRepository::__construct(),
It's much cleaner to retrieve your verifiedUsersSortedByDate within the controller directly and then pass it to your template.
//...
$verifiedUsersSortedByDate = $this->getYourManager()->getVerifiedUsersSortedByDate();
return $this->render(
'Xxx:xxx.xxx.html.twig',
array('verifiedUsersSortedByDate' => $verifiedUsersSortedByDate)
);
You should be very carefull not to do extra work in your entities. As quoted in the doc, "An entity is a basic class that holds the data". Keep the work in your entities as basic as possible and apply all the "logic" within the entityManagers.
If you don't want get lost in your code, it's best to follow this kind of format, in order (from Entity to Template)
1 - Entity. (Holds the data)
2 - Entity Repositories. (Retrieve data from database, queries, etc...)
3 - Entity Managers (Perform crucial operations where you can use some functions from your repositories as well as other services.....All the logic is in here! So that's how we can judge if an application id good or not)
4 - Controller(takes request, return responses by most of the time rendering a template)
5 - Template (render only!)
You need to get the users inside your controller via repository
$em = $this->getDoctrine()->getEntityManager();
$verifiedusers = $em->getRepository('MYBundle:User')->getVerifiedUsers();
return array(
'verifiedusers' => $verifiedusers,
);
}

writing doctrine query with symfony 2

i have two tables:
products products_images
-id -id
-name -product_id
-image_name
There is one to many relation from product to products_images table
I have created two entities with its relation defined as: Product and ProductImage
I need to get list of products and its images but the limiting the record of no of images to 1.
Currently, I did this :
$product = $this->getDoctrine()
->getRepository('TestBundle:Product');
Then in the twig template:
{% for image in product.images if loop.first %}
{% endfor %}
I used this loop to fetch one image for that product. I dont think this is efficient way to do since i have fetching all the images for that product.
What I want to do is just fetch only one image per product from the database? How can i do this ?
I'd add another method to the Product-entity, something like getThumbnail. This encapsulates the logic of which image is considered the thumbnail (i.e your view does not contain any logic of whether to display the first, last or any other product image, it just asks the product for its thumbnail):
in the view
{% if product.thumbnail %}
{{ // Output the product.thumbnail-entity }}
{% endif %}
In the entity
public function getThumbnail ()
{
return $this->getImages()->first();
}
Now, after profiling, if you're concerned that the full image collection is loaded when only a single image/product is shown, then I'd update the repository DQL to only fetch-join a single image, or make sure that the association to the images is EXTRA_LAZY

How do I output data from a related object in a Twig template?

I'm still very new to Symfony2 so please go easy on me. I'm trying to loop through a table of flights (for a flight ticket booking system), which have several related fields, such as airline, and airport. I'm using the following method in my custom repository:
public function getAllFlights($limit = 100)
{
$dql = 'SELECT f FROM Flightcase\BookingBundle\Entity\Flight f';
$query = $this->getEntityManager()->createQuery($dql);
$query->setMaxResults($limit);
return $query->getResult();
}
and the getAllFlights() is being passed to my Twig template like so:
$flights = $em->getRepository('FlightcaseBookingBundle:Flight')->getAllFlights();
return $this->render('FlightcaseBookingBundle:Flight:list.html.twig', array('flights' => $flights));
And the Twig template is simply looping through the items inside the $flights collection like this:
{% for flight in flights %}
<tr>
<td>{{ flight.airline }}</td>
<td>{{ flight.origin }}</td>
<td>{{ flight.destination }}</td>
<td>{{ flight.dateFrom }}</td>
<td>{{ flight.timeFrom }}</td>
<td>{{ flight.dateTo }}</td>
<td>{{ flight.timeTo }}</td>
</tr>
{% endfor %}
But I get a ugly, cryptic exception telling me "Object of class Proxies\FlightcaseBookingBundleEntityAirlineProxy could not be converted to string" which leads me to believe I need to fetch a specific property inside the Airline object such as the IATA code to output as string. But how can I access the $airline->getIataCode() inside the Twig template? Or is there a way in my repository to convert the related objects into strings?
I am assuming that Airline is a separate entity, which has an association to the Flight entity in Doctrine. Something like:
class Airline
{
private $id;
private $name;
private $flights;
...
}
Is that correct? If so, then that's the reason you're seeing that specific error. You're giving Twig an object, and telling it to print it out... but what does that mean, exactly?
Let's assume that your class looks like the above, and you're just trying to print out the name of the Airline.
You could do one of two things:
First, you could give your object a toString() method:
class Airline
{
public function toString()
{
return $this->getName();
}
}
Alternatively, you can give Twig something scalar to work with: Replace {{ flight.airline }} with {{ flight.airline.name }}.
Edit:
Just saw that your Airline object has a property called $IataCode. In that case, you'd render it in Twig using {{ flight.airline.IataCode }}.

Resources