Skip to content

Commit 2d6c472

Browse files
committed
Add more tasks to README
1 parent 5d4a0a8 commit 2d6c472

File tree

1 file changed

+55
-1
lines changed

1 file changed

+55
-1
lines changed

README.md

Lines changed: 55 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -130,4 +130,58 @@ $ bin/console cache:clear
130130
return $this->>render('create-post.html.twig', ['form' => $form->createView()]);
131131
}
132132
```
133-
10. Now you can load your page and look at the form
133+
10. Now you can load your page and look at the form, have a play with the `PostType` class to see what you can change
134+
11. In order to save your `Post` to the database when the form is submitted, you need to use the `EntityManager`, so
135+
you inject it into the constructor of your Controller
136+
```php
137+
/** @var EntityManagerInterface **/
138+
private $entityManager;
139+
140+
public function __construct(EntityManagerInterface $entityManager)
141+
{
142+
$this->entityManager = $entityManagerInterface;
143+
}
144+
```
145+
12. Now you can save your `Post` to the database, but only if the form has been submitted and is valid
146+
```php
147+
$this->entityManager->persist($post);
148+
$this->entityManager->flush();
149+
```
150+
13. It's best practice to do a redirect after a form is successfully submitted because it prevents the user from
151+
accidentally submitting the form twice
152+
```php
153+
return $this->redirect('create');
154+
```
155+
14. Submit your form a few times, log into the database like we did in the previous task and check our your posts
156+
157+
158+
#### Querying the Entity Manager
159+
160+
1. Create a new twig template that iterates through a list of Posts and prints their title
161+
```twig
162+
<ul>
163+
{% for post in posts %}
164+
<li>{{ post.title }}</li>
165+
{% endfor %}
166+
</ul>
167+
```
168+
2. Create a new Controller action
169+
3. Get a list of all the Posts and pass them through to your twig template
170+
```php
171+
$posts = $this->entityManager->findAll(Post::class);
172+
```
173+
4. Load the page, you should see a list of all the Posts in your database
174+
5. Inject the `Request` into your action and get the `'title'` parameter from it (with a sensible default value of `''`)
175+
6. Create a `QueryBuilder` in order to search the database for specific Posts
176+
```php
177+
$posts = $this->entityManager->createQueryBuilder()
178+
->select('post')
179+
->from(Post:class, 'post')
180+
->where('post.title = :title')
181+
->setParameter('title', $title)
182+
->getQuery()
183+
->getResult()
184+
;
185+
```
186+
7. Now you can search for Posts by title!
187+
8. Have a play, try and the QueryBuilder doing a wildcard search with an SQL like

0 commit comments

Comments
 (0)