A reference to the object element Symfony2 - symfony

I try to get to "content" from message entity.
This is my dump($messages):
http://s13.postimg.org/96ytd93vb/message.png
and my code in controller:
$em = $this->getDoctrine()->getEntityManager();
$messages = $em->getRepository('DashboardMainBundle:Message')->findBy(
array(
'receiver'=> $UserId,
'id' => $Id
),
array('createdAt' => 'ASC')
);
How can I take "content" from this array in controller?
It looks simple but I tried many methods but each failed...

For what you've currently shown, you got an array result. Currently your Message instance is being stored in $messages[0]. So you either have to iterate over your result (if you expect more than one record) or replace your findBy with findOneBy if you expect one record.

Related

Symfony2 findBy+indexBy

In query builder you can specify which field should be used as array index:
$qb = $em->createQueryBuilder();
$qb->select('s');
$qb->from('models\Settings', 's', 's.key'); // here the magic
$result = $qb->getQuery()->getResult();
//here $result[key] is entity
Anybody knows how to add indexBy(not in DB, but index of array of results) to the findBy method, or make findBy-like method for repository, something like:
$clients = $clientRepository->findBy(['id' => $clients], [indexBy=>id]);
OR
$clients = $clientRepository->myFindByWithIndexBy(['id' => $clients], 'id');
I need a method with filter criteria (where) and it should return entities indexed by id.
Second argument to findBy is for ordering results (indexing in database context is another thing).
$repo->findBy(['id'=>$clients], ['id'=>'asc']); // reverse by changing 'asc' to 'desc'

Method findBy() from Doctrine with DateTime

I have the following code, but this would not work:
$event= $this->getDoctrine()
->getRepository('AppBundle:Event')
->findBy(
array(
"datestart" => array(new \DateTime())
)
);
I need a list of the events, which are newer then now.
Where is my misstake?
Or isn't that able to get with the default findBy() function of doctrine ?
findBy only search for exactly matches while you need greater then. In this case and also many other cases you can write your own query. You could use DQL or the queryBuilder. If you want to be able to re-use your query on other places then you could place your query in a repository class which is a good practice too. (check the docs). Now here you find a DQL example that you can place into your controller:
$events = $this->getDoctrine()
->getManager()
->createQuery('SELECT e FROM AppBundle:Event e WHERE e.datestart > CURRENT_DATE()')
->getResult();
i changed your variabele to $events (with s) because you are expecting possible more than one event.

How does one have to call the function in this example for JMSPaymentCoreBundle?

How would detailsAction() have to be called in the example provided in the documentation for JMSPaymentCoreBundle?
It makes use of an order object, which in the function definition is passed as an argument.
public function detailsAction(Order $order)
{
$form = $this->getFormFactory()->create('jms_choose_payment_method', null, array(
'amount' => $order->getAmount(),
[...]
Am I right in assuming that the function can only work when passing an order object at the time it is being called? Are there any other ways of achieving this other than doing something like
return $this->forward('MyBundle:Payment:details', array(
'order' => $order,
));
Yes, you are right. The detailsAction requires an Order object in order to work. So, you will have to have one created by the time you get to this action, otherwise it will throw a 404 error (because the route without an order does not exists).
You should create your own Order entity, which then you can persist to the database (once it's started, that is, the submitted form is correct).
Good luck.

Illegal offset type in isset or empty in EntityChoiceList.php line 273

Within my Symfony2 project I've attempted to dynamically generate the entities used within my form type, by-passing the use of query builder etc.
To he entity choices property I am supplying an array of entities to be used. On page load everything seems fine and the correct content is displayed. However on form submission I get
Illegal offset type in isset or empty in EntityChoiceList.php line 273
at ErrorHandler ->handle ('2', 'Illegal offset type in isset or empty',
'..../Symfony/Bridge/Doctrine/Form/ChoiceList/EntityChoiceList.php', '273', array('key' => object(myEntity))) in ..../Symfony/Bridge/Doctrine/Form/ChoiceList/EntityChoiceList.php at line 273
.....
return isset($entities[$key]) ? $entities[$key] : null;
.....
What has me stumped is if I add var_dump(isset($this->entities[$key]));exit; above this line I am returned 'bool(true)' which to me means the key does exist.
As background I have attempted to extend the EntityType, for ease within my project and added:
public function getDefaultOptions(array $options)
{
$defaultOptions = array(
'em' => null,
'class' => 'Acme\TestBundle\Entity\myEntity',
'property' => null,
'query_builder' => null,
'choices' => $this->myEntityArray,
);
$options = array_replace($defaultOptions, $options);
$defaults = parent::getDefaultOptions($options);
return $defaults;
}
Has any one any ideas why I getting this error, or am I going about my issue all wrong anyway, with trying to pass an array of entities to choices?
If you're getting this while trying to remove an element from an ArrayCollection it's probably because you've typed:
$list->remove($item) instead of $list->removeElement($item)
I'm guessing you already solved this some other way, and this isn't a real answer either.
But I'm guessing either $entities isn't an array on that point, or $key isn't a scalar value.
For debugging you should use:
<?php
if (!is_array($entities) || !is_scalar($key)) {
var_dump($key, $entities));exit;
}
How you now tested this, it would stop on the first pass in that function. Symfony Forms use quit a lot of recursion, so an exit in any function usually doesn't help you.

Symfony2 Functional test: Passing form data directly

I am using phpunit to run functional tests but I am having a problem with a few of the forms. The problem is that phpunit is not aware of JS, and I have a form with a dynamically populated select box that needs jQuery.
So I need to pass the form data directly. The 'book' gives the following example:
// Directly submit a form (but using the Crawler is easier!)
$client->request('POST', '/submit', array('name' => 'Fabien'));
When I used this example the controller didn't receive any of the form data. Intially I saw that passing the array key 'name' wasn't correct in my situation as I needed the form name which was 'timesheet' in my code. So I tried something like:
$client->request('POST', '/timesheet/create', array('timesheet[project]' => '100'));
But this still didn't work. In the controller I tried to understand what was happening and what if anything was being received:
$postData = $request->request->get('timesheet');
$project = $postData['project'];
This didn't work and $project remained empty. However if I used the following code I got the value:
$project = $request->request->get('timesheet[project]');
But clearly that's not what I want. Atleast though I can see that there is some POST data. My last attempt was to try the following in the test method:
$this->crawler = $this->client->request('POST', '/timesheet/create/', array('timesheet' => array(project => '100'));
So I am trying to pass a 'timesheet' array as the first element of the request parameter array. But with this I get the error:
Symfony\Component\Form\Exception\UnexpectedTypeException: Expected argument of type "array", "string" given (uncaught exception) at /mnt/hgfs/pmt/src/vendor/symfony/src/Symfony/Component/Form/Form.php line 489
I would be very happy if someone can expand on what's in the 'book' about how I am supposed to get this working.
Form bind in controller:
if ($request->getMethod() == 'POST') {
$form->bindRequest($request);
if ($form->isValid()) {
$postData = $request->request->get('timesheet');
$project = $postData['project'];
$timesheetmanager = $this->get('wlp_pmt.timesheet_db_access');
$timesheetmanager->editTimesheet($timesheet);
return $this->redirect($this->generateUrl('timesheet_list'));
}
}
If you are wanting to know how to inject arrays of POST data using the test client...
In your test method, do something like
$crawler = $client->request('POST', '/foo', array(
'animal_sounds' => array(
'cow' => 'moo',
'duck' => 'quack'
)
); // This would encode to '/foo?animal_sounds%5Bcow%5D=moo&animal_sounds%5Bduck%5D=quack'
$this->assertTrue( ... );
In the controller, you would access your params like this:
$data = $request->request->get('animal_sounds');
$cowNoise = $data['cow'];
$duckNoise = $data['duck'];
Or you could just use the forms API if the test method was injecting valid form data...
do you have a $request parameter in your action?
that was the reason why my request->get() was empty:
//WRONG
public function projectAction()
{
$request = Request::createFromGlobals();
$project = $request->request->get('timesheet[project]');
//$project will be empty
}
//CORRECT
public function projectAction(Request $request)
{
$project = $request->request->get('timesheet[project]');
//$project is not empty
}
see
How do I create a functional test which includes a POST to a page with parameters?
Try to use $form->bind($clientData) instead of $form->bindRequest($request).

Resources