How can i create a relation beetwen two models and pass the model info on to the view through the controller? - eloquent

My Student Model
/**
* #return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function fathers()
{
return $this->belongsTo('App\Models\Father');
}
My StudentController
/**
* Display the specified resource.
*
* #param ManageStudentRequest $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show(ManageStudentRequest $request, $id)
{
$student = Student::with('fathers')->find($id);
return view('students.show')->withStudent($student);
}
And my Blade View
<tr>
<th>NOMBRE</th>
<td>{{ $student->father->first_name }} {{ $student->father->last_name }}</td>
</tr>
The thing is i get this mistake:
Trying to get property of non-object (View: C:\laragon\www\App\resources\views\students\partials\show\show-overview.blade.php) (View: C:\laragon\www\App\resources\views\students\partials\show\show-overview.blade.php)
Im in desperate need for help, anything is useful, tyvm.

You should setup your structure to have a many to many relationship between students and fathers if that's the logic you want, so:
public function fathers()
{
return $this->belongsToMany('App\Models\Father');
//Also define the inverse relationship on the Father model.
}
Now assuming you've done that then:
On this query $student = Student::with('fathers')->find($id); just append first() so it looks like this:
$student = Student::with('fathers')->find($id)->first();
Then in your view you can access them like this:
<td>{{ $student->father->first_name }} {{ $student->father->last_name }}</td>

Related

ZF3 Doctrine Object provided to Escape helper, but flags do not allow recursion

In my specialisme entity i want to join al column and display rows from specialisme with the joined column, but i get error: Object provided to Escape helper, but flags do not allow recursion
In specialisme entity:
/**
* #ORM\OneToOne(targetEntity="User\Entity\User")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
private $fullname;
//...
/**
* Returns fullname.
* #return string
*/
public function getFullName()
{
return $this->fullname;
}
In controller:
public function indexAction()
{
//Array met alle user samenstellen
$users = $this->entityManager->getRepository(Specialisme::class)->findBy([], ['id'=>'ASC']);
//Users doorgeven aan view model
return new ViewModel([
'users' => $users
]);
return new ViewModel();
}
View:
<tr>
<th>Naam</th>
<th>Specialisme</th>
<th>Sub-specialisme</th>
</tr>
<?php foreach ($users as $user): ?>
<tr>
<td>f</td>
<td><?= $this->escapeHtml($user->getId()); ?></td>
<td><?= $this->escapeHtml($user->getFullName()); ?></td>
</tr>
<?php endforeach; ?>
It gives back the object,so i have to use the method of the referencing object:
$user->getBeschikbaarheid()->getOpZoekNaar());

TYPO3 & tx_news need ViewHelper for show count of Entities in category

Task: in category menu show count of item in each category, like
Category_one (38)
Category_two (14)
Etc ...
I have try count by $demand but did'nt work
<?php
namespace HIT\huskytheme\ViewHelpers\News;
class CountCategoriesViewHelper extends \TYPO3\CMS\Fluid\Core\ViewHelper\AbstractViewHelper {
/**
* #var \GeorgRinger\News\Domain\Repository\NewsRepository
* #inject
*/
protected $newsRepository = null;
/**
*
* #param string $category
* #return string
*/
public function render($category) {
$demand = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('GeorgRinger\\News\\Domain\\Model\\Dto\\NewsDemand');
//$demand->setDateField('datetime');
$demand->setStoragePage(10, true);
// for example by id = 2
$demand->setCategories(2);
$demand->setCategoryConjunction('and');
$demand->setIncludeSubCategories('1');
//$demand->setArchiveRestriction($settings['archiveRestriction']);
$statistics = $this->newsRepository->countByCategories($demand);
\TYPO3\CMS\Core\Utility\DebugUtility::debug($statistics);
return $this->newsRepository->countByCategories($demand);
}
}
But get just 0, if call
{namespace s=HIT\huskytheme\ViewHelpers}
{s:news.countCategories(category: 2)}
Actualy i found way to get number of news in Category. Thx Georg Ringer and undko
My ViewHelper
<?php
namespace HIT\huskytheme\ViewHelpers\News;
class CountCategoriesViewHelper extends \TYPO3\CMS\Fluid\Core\ViewHelper\AbstractViewHelper {
/**
* #var \GeorgRinger\News\Domain\Repository\NewsRepository
* #inject
*/
protected $newsRepository = null;
/**
*
* #param \GeorgRinger\News\Domain\Model\Category $category
* #return string
*/
public function render($category) {
/* #var $demand \GeorgRinger\News\Domain\Model\Dto\NewsDemand */
$demand = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\GeorgRinger\News\Domain\Model\Dto\NewsDemand::class);
$demand->setCategories(array($category));
$demand->setCategoryConjunction('and');
$demand->setIncludeSubCategories(false);
return count($this->newsRepository->findDemanded($demand));
}
}
And in my tx_news Templates/Category/List.html
<!-- load my ViewHelper -->
{namespace s=HIT\huskytheme\ViewHelpers}
and here add count
...
<f:link.page title="{category.item.title}" class="current-item" pageUid="{settings.listPid}"
additionalParams="{tx_news_pi1:{overwriteDemand:{categories: category.item.uid}}}">{category.item.title}
<span class="postnum">({s:news.countCategories(category: category.item)})</span>
</f:link.page>
...
There is no method countByCategories which implements something like a demand object. Please just use a direct call to the DB.
Depending on the number of categories and the need to show this menu on uncached pages I‘d suggest to not go the view helper way but query DB (as Georg suggested) directly in the controller. Just connect a slot of yours to signal GeorgRinger\News\Controller\CategoryController : listAction. You‘ll get all categories there (in argument categories) and can launch a
SELECT COUNT(*) FROM sys_category_record_mm … GROUP BY uid_local
to fetch all counts in one go. Then simply add a new key to the array you return and use it in your template under that name.

__toString() must return a string value when submitting a form

I have an show view that I had to custom a little bit so we can edit things in it. Among these things there is a multi select that is the result of a query to filter schools I've done inside the controller, sent via the render method.
Before all that, I was using a many-to-many multi select form to select every schools ever saved in the database. Now I want to use it so I can use what's already working.
Since it's sent via the render and not the form, I managed to create an HTML form, to display it, and to get to see what has been selected when I submit the form, however I had several problems:
First of all, it wanted to be an instance of an object, and to be able to save an object instead of an array. I managed to do that by doing the following:
$object = new Ecole();
foreach ($ecolesDispo as $key => $value)
{
$object->$key = $value;
}
$mission->addEcolesDispo($object);
(Ecole is for schools)
The problem I'm now stuck with came right after it, because now it wants it to be converted to string, however, I can't manage to do so.
Here's how the concerned part of my entity looks like.
/**
* Constructor
*/
public function __construct()
{
$this->ecolesDispo = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* #return string
*/
public function __toString()
{
return (string) $this->addEcolesDispo($object);
//Not sure about that part though
}
/**
* Add ecolesDispo
*
* #param \EcoleBundle\Entity\Ecole $ecolesDispo
*
* #return Mission
*/
public function addEcolesDispo(\EcoleBundle\Entity\Ecole $ecolesDispo)
{
$this->ecolesDispo[] = $ecolesDispo;
return $this;
}
/**
* Remove ecolesDispo
*
* #param \EcoleBundle\Entity\Ecole $ecolesDispo
*/
public function removeEcolesDispo(\EcoleBundle\Entity\Ecole $ecolesDispo)
{
$this->ecolesDispo->removeElement($ecolesDispo);
}
/**
* Get ecolesDispo
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getEcolesDispo()
{
return $this->ecolesDispo;
}
How can I convert this to string?
Thank you in advance
Your __toString function should looks like :
public function __toString()
{
return $this->id; // Because __toString seems to be called to set your $key variable...
}
-> rely on a string property.
In your __toString() function, you use (string) which will implicitely call ... __toString() to convert $this to a string. That would be a circular call.
Try this if there's a string variable name in the entity where you were using __toString or use any string type property of that entity which specifies the entity itself.
public function __toString()
{
// Or change the property that you want to show
return $this->name;
}

Form post-processing in Symfony2

I am new of Symfony, and I am trying to create a form bound to an Entity User.
One field of this entity is of type ArrayCollection. It is actually a OneToMany relationship with objects of another class.
So, a little bit of code just to be clearer.
class User
{
\\...
/**
* #ORM\OneToMany(targetEntity="UserGoods", mappedBy="users")
* #ORM\JoinColumn(name="goods", referencedColumnName="id")
*/
private $goods;
public function __construct()
{
$this->goods = new ArrayCollection();
}
\\...
}
And the associated class
class UserGoods
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var \DateTime
*
* #ORM\Column(name="inserted_at", type="datetime")
*/
private $insertedAt;
/**
* #var float
*
* #ORM\Column(name="value", type="float")
*/
private $value;
/**
* #ORM\ManyToOne(targetEntity="User", inversedBy="goods")
*/
protected $users;
}
Now, I want to create a FormBuilder that does something extremely simple, yet I couldn't figure it out how to do it by myself.
I want just a field of type number, and if an object of type Goods with the current date exists, modify it, otherwise add a new object to the collection.
This could be easily done inside the controller, but I have a lot of instances of this form, and this would make my program impossible to maintain.
Is there a way to add some post-processing of submitted data inside the form builder?
I already tried with DataTransformers but these won't suffice, as at most they would transform a number to a UserGoods object, and the original ArrayCollection would not be preserved (and what about doctrine associations?).
In addition, if I declare the field type as collection of number types, all the items inside the ArrayCollection would be displayed when rendering the form, not just the last one.
Any idea on how to get out of this?
Thank you in advance for your help.
As suggested, use Form Events. Inside the event you will check if the Goods with the submitted date already exist (load them from database) and your will modify them with the post data. If they dont exist, you will be creating new ones. You can also make another method in your entity, getLastItemsInCollection(), where you can use Criteria, to only load the last one from the database (recommended), or get the last item from original ArrayCollection. You can make a field unmapped, and map the Goods manually in the FormEvent, as described above. I hope that helps and I hope I understood correctly.
I followed Cerad and tomazahlin suggestions and I came up with a solution.
I am sure that every year at least 2 people over the world share my same problem, so I'll take some time to post my outcome.
Feel free to correct, criticize or add me, in the end I am a newbie of Symfony!
First, how I defined my two classes in the end.
class User
{
//...
/**
* #ORM\ManyToMany(targetEntity="UserGoods", inversedBy="users", cascade={"persist", "remove"})
* #ORM\JoinColumn(name="goods", referencedColumnName="id")
*/
// Should have been a OneToMany relationship, but Doctrine requires the
// owner side to be on the Many side, and I need it on the One side.
// A ManyToMany relationship compensate this.
private $goods;
public function __construct()
{
$this->goods = new ArrayCollection();
}
//...
}
And the connected class
/**
* #ORM\HasLifecycleCallbacks()
**/
class UserGoods
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var \DateTime
*
* #ORM\Column(name="inserted_at", type="datetime")
*/
private $insertedAt;
/**
* #var float
*
* #ORM\Column(name="value", type="float", nullable=true)
*/
// I do not want this field to be null, but in this way when
// persisting I can look for null elements and remove them
private $value;
/**
* #ORM\ManyToMany(targetEntity="User", inversedBy="goods")
*/
protected $users;
/**
* #ORM\PrePersist()
* #ORM\PreUpdate()
*/
// This automatically sets InsertedAt value when inserting or
// updating an element.
public function setInsertedAtValue()
{
$date = new \DateTime();
$this->setInsertedAt( $date );
}
}
As I said, I wanted a FormBuilder to handle my array collection. The best form type for this purpose is... collection type.
This require a subform to be defined as its type.
<?php
namespace MyBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use MyBundle\Entity\UserGoods;
class UserType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('goods', 'collection', array(
'type' => new GoodsdataWithDateType(),
'required' => false,
)
);
\\ ...
And the subform.
Since I need only the today's value to be displayed, and not all of them, I also need to add a FormEvent clause to check which items to insert.
namespace MyBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Doctrine\ORM\EntityManager;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
class GoodsdataWithDateType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
// Here I add the event listener:
// Since I want only today's value to be displayed, I implement
// a check on this field of each element
$builder->addEventListener(
FormEvents::PRE_SET_DATA, function (FormEvent $event) {
$goods = $event->getData();
$form = $event->getForm();
$datetime1 = $goods->getInsertedAt();
$datetime2 = new \DateTime();
$datetime2->setTime(0, 0, 0);
if ($datetime1 > $datetime2)
{
$form->add('value', 'number', array(
'required' => false,
));
// I am setting this value with LifecycleCallbacks, and I do not
// want the user to change it, I am adding it commented just for
// completeness
// $form->add('insertedAt', 'date', array(
// 'widget' => 'single_text',
// 'format' => 'yyyy,MM,dd',
// ));
}
});
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'MyBundle\Entity\UserGoods',
));
}
public function getName()
{
return 'goodsdatawithdate';
}
}
This works fine, but is displayed very badly when rendered with something like {{ form(form) }} in twig files.
To make it more user-friendly, I customized how the form was presented, in order to remove some garbage and include only the labels that were necessary.
So in my twig:
{{ form_start(form) }}
{{ form_errors(form) }}
<div>
{{ form_label(form.goods) }}
{{ form_errors(form.goods) }}
<br>
{% for field in form.goods %}
{{ form_widget(field) }}
{% endfor %}
</div>
{{ form_end(form) }}
This is nice so far, but I also want to include new elements in my collection, in particular if today's good has not been inserted yet.
I can do this inside my FormBuilder, by manually add a new item in the array before calling the $builder.
class UserType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$thisuser = $builder->getData();
// I added the following function inside the User class.
// I use a for loop to scroll all the associated Goods to get the
// latest one.
$mygoods = $thisuser->getLatestGoods();
if ( $mygoods && null !== $mygoods->getId() ) {
// The Array contains already some elements
$datetime1 = $mygoods->getInsertedAt();
$datetime2 = new \DateTime();
$datetime2->setTime(0, 0, 0);
// Check when was the last one inserted
if ($datetime1 < $datetime2) // Nice way to compare dates
{
// If it is older than today, add a new element to the array
$newgoods = new UserGoods();
$thisuser->addGoods($newgoods);
}
} else {
// The array is empty and I need to create the firs element
$newgoods = new UserGoods();
$thisuser->addGoods($newgoods);
}
$builder->add('goods', 'collection', array(
'type' => new GoodsdataWithDateType(),
'required' => false,
'allow_add' => true, // this enables the array to be
// populated with new elements
)
);
But I also want that if a user removes an inserted value (i.e., inserts nothing in the form), the associated array element should be removed.
Allowing the user to remove elements is a little bit trickyer. I cannot rely on 'allow_delete' property, since by working only with the last item in the collection, all the previous ones would be removed when the form is submitted.
I cannot rely on LifecycleCallbacks neither, because the changes made to relationships are not persisted in the database.
Thankfully to open source, I found a post here that helped me.
What I needed was an EventListener on Doctrine Flush operations.
namespace MyBundle\EventListener;
use Doctrine\ORM\Event\OnFlushEventArgs;
use MyBundle\Entity\UserGoods;
class EmptyValueListener
{
public function onFlush(OnFlushEventArgs $args)
{
$em = $args->getEntityManager();
$uow = $em->getUnitOfWork();
$entities = array_merge(
$uow->getScheduledEntityInsertions(),
$uow->getScheduledEntityUpdates()
);
foreach ($entities as $entity) {
if ($entity instanceof UserGoods) {
if ($entity && null !== $entity )
{
if ( empty($entity->getValue()) )
{
$users = $entity->getUsers();
foreach ($users as $curruser)
{
$curruser->removeGoods($entity);
$em->remove($entity);
$md = $em->getClassMetadata('MyBundle\Entity\UserGoods');
$uow->computeChangeSet($md, $entity);
$em->persist($curruser);
$md = $em->getClassMetadata('MyBundle\Entity\User');
$uow->computeChangeSet($md, $curruser);
}
}
}
}
}
}
}
and registered it in my config.yml as
mybundle.emptyvalues_listener:
class: MyBundle\EventListener\EmptyValueListener
tags:
- { name: doctrine.event_listener, event: onFlush }

Creating multiple models

I'm using Zend Framework and implementing Domain Model. I have Models, Mappers and DbTables.
Suppose we should fetch multiple rows from database or fetch form data where we should create multiple models and populate that models from database rows or form.
Should I implement fetching and creation of models in Mapper and then call that method from Controller? Or I should implement this in Model?
Is it okay to initialize Mapper in Controller?
The short answer is YES!
If you need to get anything from the database you almost have use the mapper somewhere, because ideally the domain model should not be aware of the database at all or event hat a mapper exists really.
There are I'm sure many strategies and patterns for using and accessing domain models and mappers. I'm also sure that everyone will have differing opinions on how best to utilize these resources. The bottom line is that you have to use what you know how to use, you can always refactor later when you know more.
Just by way of example I'll include a base mapper and a base entity(domain) model.
<?php
/**
* Base mapper model to build concrete data mappers around.
* Includes identity map functionallity.
*/
abstract class My_Application_Model_Mapper
{
protected $_tableGateway = NULL;
protected $_map = array();
/**
* Will accept a DbTable model passed or will instantiate
* a Zend_Db_Table_Abstract object from table name.
*
* #param Zend_Db_Table_Abstract $tableGateway
*/
public function __construct(Zend_Db_Table_Abstract $tableGateway = NULL) {
if (is_null($tableGateway)) {
$this->_tableGateway = new Zend_Db_Table($this->_tableName);
} else {
$this->_tableGateway = $tableGateway;
}
}
/**
* #return Zend_Db_Table_Abstract
*/
protected function _getGateway() {
return $this->_tableGateway;
}
/**
* #param string $id
* #param object $entity
*/
protected function _setMap($id, $entity) {
$this->_map[$id] = $entity;
}
/**
* #param string $id
* #return string
*/
protected function _getMap($id) {
if (array_key_exists($id, $this->_map)) {
return $this->_map[$id];
}
}
/**
* findByColumn() returns an array of rows selected
* by column name and column value.
* Optional orderBy value.
*
* #param string $column
* #param string $value
* #param string $order
* #return array
*/
public function findByColumn($column, $value, $order = NULL) {
$select = $this->_getGateway()->select();
$select->where("$column = ?", $value);
if (!is_null($order)) {
$select->order($order);
}
$result = $this->_getGateway()->fetchAll($select);
$entities = array();
foreach ($result as $row) {
$entity = $this->createEntity($row);
$this->_setMap($row->id, $entity);
$entities[] = $entity;
}
return $entities;
}
/**
* findById() is proxy for find() method and returns
* an entity object. Utilizes fetchRow() because it returns row object
* instead of primary key as find() does.
* #param string $id
* #return object
*/
public function findById($id) {
//return identity map entry if present
if ($this->_getMap($id)) {
return $this->_getMap($id);
}
$select = $this->_getGateway()->select();
$select->where('id = ?', $id);
//result set, fetchRow returns a single row object
$row = $this->_getGateway()->fetchRow($select);
//create object
$entity = $this->createEntity($row);
//assign object to odentity map
$this->_setMap($row->id, $entity);
return $entity;
}
/**
* findAll() is a proxy for the fetchAll() method and returns
* an array of entity objects.
* Optional Order parameter. Pass order as string ie. 'id ASC'
* #param string $order
* #return array
*/
public function findAll($order = NULL) {
$select = $this->_getGateway()->select();
if (!is_null($order)) {
$select->order($order);
}
$rowset = $this->_getGateway()->fetchAll($select);
$entities = array();
foreach ($rowset as $row) {
$entity = $this->createEntity($row);
$this->_setMap($row->id, $entity);
$entities[] = $entity;
}
return $entities;
}
/**
* Abstract method to be implemented by concrete mappers.
*/
abstract protected function createEntity($row);
}
Here is the base domain object:
<?php
/**
* Base domain object
* includes lazy loading of foreign key objects.
*/
abstract class My_Application_Model_Entity_Abstract
{
protected $_references = array();
/**
* Accepts an array to instantiate the object, else use
* __set() when creating objects
* #param array $options
*/
public function __construct(array $options = NULL) {
if (is_array($options)) {
$this->setOptions($options);
}
}
/**
* #param array $options
* #return \My_Application_Model_Entity_Abstract
*/
public function setOptions(array $options) {
$methods = get_class_methods($this);
foreach ($options as $key => $value) {
$method = 'set' . ucfirst($key);
if (in_array($method, $methods)) {
$this->$method($value);
}
}
return $this;
}
/**
* Map the setting of non-existing fields to a mutator when
* possible, otherwise use the matching field
*/
public function __set($name, $value) {
$property = '_' . strtolower($name);
if (!property_exists($this, $property)) {
throw new \InvalidArgumentException("Setting the property '$property'
is not valid for this entity");
}
$mutator = 'set' . ucfirst(strtolower($name));
if (method_exists($this, $mutator) && is_callable(array($this, $mutator))) {
$this->$mutator($value);
} else {
$this->$property = $value;
}
return $this;
}
/**
* Map the getting of non-existing properties to an accessor when
* possible, otherwise use the matching field
*/
public function __get($name) {
$property = '_' . strtolower($name);
if (!property_exists($this, $property)) {
throw new \InvalidArgumentException(
"Getting the property '$property' is not valid for this entity");
}
$accessor = 'get' . ucfirst(strtolower($name));
return (method_exists($this, $accessor) && is_callable(array(
$this, $accessor))) ? $this->$accessor() : $this->$property;
}
/**
* Get the entity fields.
*/
public function toArray() {
//TODO
}
/**
* set and get for _references array, allows the potential to lazy load
* foreign objects.
*/
public function setReferenceId($name, $id) {
$this->_references[$name] = $id;
}
public function getReferenceId($name) {
if (isset($this->_references[$name])) {
return $this->_references[$name];
}
}
}
I have referenced many tutorials and books to finally get my head around these concepts and techniques.
The use of these objects is as needed, if you need to pull an object from the DB you call the mapper, if you need to build an object with form data (or some other data) you can call the object directly.
I hope this helps some. Good Luck!
I use the same architecture and design patterns in all my ZF work. Your mappers should be the only classes in your whole system that access the database. This ensures good Separation of Concerns.
I've toyed a bit with using thin wrapper methods in my Models, such as:
class Application_Model_Foo {
public function save() {
$mapper = $this->_getMapper();
$mapper->save($this);
}
}
This enables me to call something like:
$foo = new Application_Model_Foo();
$foo->setBar('baz-bum');
$foo->save();
But this makes testing more complicated and muddies the water when it comes to SoC. Lately I've been removing such occurrences from my code in favor of just calling up the mapper directly, as in:
$foo = new Application_Model_Foo();
$foo->setBar('baz-bum');
$mapper = new Application_Model_FooMapper();
$mapper->save($foo);
The latter example means one more line of code in my controller method, but for simplicity in testing I think it's worth it.