How can I print Google Books api description? - symfony

Hie I am trying to get the synopsis and other items like author and published date printed. But I am Able to achieve this only with certain search terms, an error occurs with other words or terms
Key "description" for array with keys "title, subtitle, authors, publishedDate, industryIdentifiers, readingModes, pageCount, printType, categories, maturityRating, allowAnonLogging, contentVersion, imageLinks, language, previewLink, infoLink, canonicalVolumeLink" does not exist.
I am using symfony and twig. this is what the twig file looks like :
{% for item in items %}
<article>
<img src="{{ item.volumeInfo.imageLinks.thumbnail}}"/>
<h4>{{ item.volumeInfo.title}}</h4>
{{ item.volumeInfo.description }}
<strong> {{ item.volumeInfo.publishedDate }}</strong><br/>
<b>{{ item.volumeInfo.authors | join }}</b>
</article>
What am I doing wrong? why does this work only sometimes ? how can I make it work correctly all the time?
class GoogleBooksController extends Controller
{
public function getVolumeAction($title)
{
$client =new client();
$response = $client- >get("https://www.googleapis.com/books/v1/volumes?q=$title");
$data=$response->json();
$items=$data['items'];
return $this->render('BookReviewBundle:GoogleBooks:volume.html.twig', array('items'=>$items
// ...
)); }
Thanks

I belive the description field is not mandatory, so you can do follow
{% if item.volumeInfo.description is defined %}
{{ item.volumeInfo.description }}
{% endif %}

Related

Print user role when submitting comments in Drupal 8

In my Drupal site, user profile has username, role and group Taxonomy term. There is a Article content type setup to take comments from users. Every time when a user comments, I would like to show as:
Submitted by: username, role, group
I tried to read the role and category fields through template_preprocess function as below:
function bartik_preprocess_comment(array &$variables) {
if (isset($variables['elements']['#view_mode'])) {
$variables['view_mode'] = $variables['elements']['#view_mode'];
}
else {
$variables['view_mode'] = 'default';
}
dd($variables);
}
But the dump does not show "group" field. Unsure what's missing.Rightnow, only the username is showing up. My comments.html.twig looks as below:
<div class="author-comments">
<p class="comment-submitted">{{ submitted }}</p>
<div{{ content_attributes.addClass('content') }}>
{% if title %}
{{ title_prefix }}
<h3{{ title_attributes }}>{{ title }}</h3>
{{ title_suffix }}
{% endif %}
{{ content }}
</div>
</div>
any help on how to pull out the role and category field and plug into the twig template? Thanks!
Alright, I'm able to figure this out. Below is my answer:
In mytheme.theme file:
/**
* Implements hook_preprocess_HOOK() for comment.html.twig.
*/
function mytheme_preprocess_comment(array &$variables) {
$user = \Drupal::currentUser();
$user_entity = \Drupal::entityTypeManager()
->getStorage('user')
->load($user->id());
$roles = $user->getRoles();
$variables['user_roles'] = $roles ;
}
This variable can be printed on comment.html.twig as: {{ user_roles }} as however needed.

Cannot write data to db in Flask

I am working on a small reading tracking app in Flask. I cannot seem to write data from one of my routes, below:
#app.route('/add_book', methods=['GET', 'POST'])
#login_required
def add_book():
form=BookForm()
if request.method=='POST':
if form.validate_on_submit():
book=Book(
title=form.title.data,
author=form.author.data,
# category=form.category.data,
# added_on=form.added_on.data,
# done=form.done.data,
user_id=current_user
)
db.session.add(book)
db.session.commit()
flash('Book added')
return redirect(url_for('books'))
else:
flash('ERROR. The book not added.')
return render_template('add_book.html', form=form)
This is the corresponding HTML:
{% extends "layout.html" %}
{% block content %}
{% if form %}
<form action="{{ url_for('add_book') }}" method="post">
{{ form.hidden_tag() }}
{{ form.title.label }}<br>
{{ form.title() }}<br>
{{ form.author.label }}<br>
{{ form.author(cols=32, rows=4) }}<br>
<!-- {{ form.category.label }}<br>
{{ form.category() }}<br> -->
{{ form.submit() }}
</form>
{% endif %}
{% endblock %}
When the page renders, the label and forms for the book and author appear, however on clicking Submit, the data does not get saved.
The code section is similar to that for registering a user and I am stuck on what to do because I cannot see any errors. I am using SQLite as a database.
Here is the book model:
class Book(db.Model):
__tablename__='books'
id=db.Column(db.Integer, primary_key=True)
title=db.Column(db.String(100))
author=db.Column(db.String(50))
# category=db.Column(db.String(50))
added_on=db.Column(db.DateTime, index=True, default=datetime.utcnow)
done=db.Column(db.Boolean, default=False)
user_id=db.Column(db.Integer, db.ForeignKey('users.id'))
def __init__(self, title, author, added_on, done, user_id):
self.title=title
self.author=author
self.added_on=added_on
self.done=done
self.user_id=user_id
def __repr__(self):
# return '<Book: Title - {0}, Author - {1}, Category - {2}>'.format(self.title, self.author, self.category)
return '<Book: Title - {0}, Author - {1}>'.format(self.title, self.author)
The current_user is a user proxy giving access to all user attributes or use something like this How to track the current user in flask-login?
a quick solution would be to change this line
user_id = current_user
into this
user_id = current_user.id
Update:
ok, I got it working. You need the following fixes, each of them leads to trouble with form validation and or committing to database:
- use current_user.id in your book object as I said earlier.
- removed the init method in books model. I'm not sure what the added value is at the moment, I'm getting error messages about fields added on and done which are not on the form. I haven't taken the time to look into it further.
- just go for if request.method=='POST' as you don't need both. The form will be checked for validation anyways.
tip: don't forget to create a requirements file (pip freeze --> requirements.txt), that makes it a lot easier to reinstall in a new virtual environment.

Get parent of term

I might have missed it in the Timber Docs but is there a possibility to get the parent terms of a given taxonomy?
two methods depending on Twig vs. PHP and what exactly you're looking to do.
Consider a post which as been assigned a category of "Politics" (which is a child category of "News")
Example 1: Get a parent term in a Twig file
<p>Find more posts in {{ post.category.name }} and {{ post.category.parent.name }}</p>
<!--- outputs as ... --->
<p>Find more posts in Politics and News</p>
Example 2: Get the top-level terms from a taxonomy
$context['parent_categories'] = Timber::get_terms(array('taxonomy' => 'category', 'parent' => 0));
Use in Twig like...
Top-level categories for my site are...
{% for term in parent_categories %}
<li>{{ term.name }}</li>
{% endfor %}
<!-- Outputs as... -->
<li>News</li>
<li>Sports</li>
<li>Opinion</li>
Let's say you are trying to use the parent of a category in a twig view. That was the case I tried to solve when stumbling upon this post.
In category.php you can get the parent category by getting the parent category ID of the currently viewed category:
$category = new TimberTerm();
$context['category'] = $category;
if ($category->parent) {
$context['parent_category'] = new TimberTerm($category->parent);
}
$category->parent corresponds to the ID of the parent category. It is null if the category doesn't have a parent. You can then use the resulting category in your template.
<a class="category_{{parent_category.slug|lower}}" href="{{parent_category.link}}">
{{parent_category.title}}
</a>

Fetching objects from database in Symfony 2.7.3

I'm trying to show some object properties stored on the database. I've got the controller, the Entity, and the view. I'get no excepctions but I can't see the object properties.
Controller:
/**
* #Route ("/ov", name="ov")
*/
public function select(){
$a=$this->getDoctrine()->getRepository('AppBundle:PC')->find(2);
if(!$a){
throw $this->createNotFoundExcepction('No PC');
}
return $this->render('PcDetailed.html.twig', array('pcs' => $a));
}
View:
{% extends 'master.html.twig' %}
{% block divCentral %}
<div class="row">
<p>Nom del pc</p>
<div class="small-6 small-centered columns">
{% for pc in pcs %}
<p>{{ pc.nom }}</p>
{% endfor %}
</div>
</div>
{% endblock %}
Edit:
Finally, like Chris says, the problem is 'cause on the View I'm using I'm trying to iterate is an object, not an array. That's why doesn't work.
That's the way I must do it:
return $this->render('PcDetailed.html.twig', array('pcs' => array($a)));
In your controller you get the PC with id 2 and pass it to the view.
In the view you are now trying to iterate over this object. I have no idea what TWIG does when you try to iterate over something that is not an array or a collection but maybe it just fails silently.
To fix it, change your controller code to send an array to the view:
return $this->render('PcDetailed.html.twig', array('pcs' => array($a)));

Using doctrine database object in a template

I am new to Symfony and am finally beginning to understand how to query a database using a Doctrine. However, I am lost as far understanding how to use the database object content in a Twig template.
Lets say my database object contains product Id's, names, prices, for 50 different products. After I am done querying the database in the controller, I do the following, to pass the database object into the Twig template:
public function searchAction($word)
{
//query database using the $word slug and prepare database object accordingly
$dataObject; // contains query results
return $this->render('GreatBundle:Default:search.html.twig', array('word' => $word));
}
This is where I am stuck. Now I have a Twig template, I would like to pass the DB object from the controller and then print out the database data in my Twig template.
I appreciate any suggestions as to how I can accomplish this.
Many thanks in advance!
I'll respond with an example (more easier for me to explain)
You want to search something with a slug (the var $word in your example). Let's say you want to find a article with that.
So your controller :
public function searchAction($word)
{
//query database using the $word slug and prepare database object accordingly
// Search the list of articles with the slug "$word" in your model
$articleRepository = $this->getDoctrine()->getRepositoy('GreatBundle:Article');
$dataObject = $articleRepository->findBySlug($word);
// So the result is in $dataObject and to print the result in your twig, your pass the var in your template
return $this->render('GreatBundle:Default:search.html.twig', array('result' => $dataObject));
}
The twig template 'GreatBundle:Default:search.html.twig'
{% for item in result %}
{{ item.title }} : {{ item.content }}
{% endfor %}
Just look the second example in the Symfony2 Book (Sf2 Book - templating), you have to use the function "for" to parse your object (like an array in php !)
Example in your twig template :
{% for item in word %}
{{ item.id }} - {{ item.name }} - {{ item.description }}{# etc... #}<br>
{% else %}
<h2>Aoutch ! No data !</h2>
{% endfor %}
Ah, and it's not the good var in your render method (but it's was for your example !)
public function searchAction($word)
{
//query database using the $word slug and prepare database object accordingly
$dataObject; // contains query results
return $this->render('GreatBundle:Default:search.html.twig', array('word' => $dataObject));
}

Resources