For example:
I need to retrieve a set of male User's IDs, First Names, and Last Names, but nothing else.
So I have a function in UserMapper called fetchAllMaleUsers() that returns a set of User entities.
i.e:
public function fetchAllMaleUsers() {
$select = $this->getDbTable()
->select()
->from($this->getDbTable(),
array('ID', 'FirstName', 'LastName'))
->where('Gender = ?', 'M');
$resultSet = $this->getDbTable()->fetchAll($select);
$users = array();
foreach ($resultSet as $row) {
$user = new Application_Model_User();
$user->setId($row->ID)
->setFirstName($row->FirstName)
->setLastName($row->LastName);
$users[] = $user;
}
return $users;
}
Does this function belong in the mapper layer?
Is it ok to only set the Id, Firstname, and LastName of each User entity?
1) Perfectly fine for the mapper/Gateway or however you call it.
2) You can do but i highly disencourage this. Why? Later on in your application you can't tell from where you did get the model. So you'd have to check if a value is set in your model each time you're not sure if it is set or you'd need some autoloading stuff for missing values (which is as worse as missing stuff). Another reason is that you can't reuse the function for other porposes where you might need other properties of the user model. Last reason afaik is, that a model represents the complete entity at any time, not parts of it. And there's no real reason why not to load all fields (beside references to other entities why should be autoloaded anyways).
Along with Fge's reply I believe that $resultSet should already be returning values of type Application_Model_User. If not, you may need to set $_rowClass in Application_Model_DbTable_User.
Related
I'm using the "processDatamap_afterDatabaseOperations" hook within my extension to transfer content from a newly created News (tx_news_domain_model_news) to an API.
TYPO3 Version is 6.2.11 and if I var_dump or trying to access the category using $record->getCategories() it's empty. Same with related files, falmedia works. Here is my code:
public function processDatamap_afterDatabaseOperations($status, $table, $id, array $fieldArray, \TYPO3\CMS\Core\DataHandling\DataHandler &$pObj) {
if ($table == 'tx_news_domain_model_news' && $status == 'new') {
$objectManager = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\CMS\Extbase\Object\ObjectManager');
$news = $objectManager->get('GeorgRinger\News\Domain\Repository\NewsRepository');
$record = $news->findByUid($pObj->substNEWwithIDs[$id]);
Hope anybody knows what I'm doing wrong here. I've been trying this like forever and don't get it.
Thanks in advance for your help.
That's likely because "afterDatabaseOperations" is called for each record insertion/update in each table, and that the relation between the record and the categories has not been established yet.
Only after all insertions/updates have been done, the method processRemapStack is called by the DataHandler, that sets/fixes all the relations between the various records (e.g. wherever there was a "NEW.." relation in the datamap, the correct uids are set).
The only hook you can use, where alle records have the correct relations is the processDatamap_afterAllOperations hook, that you can find at the very end of the process_datamap in the DataHandler class.
That one only takes a single argument though (the DataHandler instance), so you probably have to try and get the inserted news records using the "datamap" property of the DataHandler reference.
My model was eager loading a lot of things with accessors. I want to change it to specify accessors in each case. How do I include such accessors with the query, so that I get the basic model data plus the accessor data
Accessors would previously be eager loaded with:
protected $appends = [
'status',
]
But if I get rid of eager loading, and I want to include this acccessor:
public function getStatusAttribute() {
return self::STATUS_ACTIVE;
}
Then I can do this according to the documentation:
$prod = \App\Product::find(736)->status;
That works but I don't get the basic model data.
I can't do: return $prod = \App\Product::find(736)->with('status')->first()
It gives error: Call to undefined relationship [status] on model
So how do I add such accessors to be included with the model data?
Edit:
As Staudenmeir commented, i can do \App\Product::find(736)->append('status');
That solves it for single results. But how do I append data for many results?
Neither append or appends work:
This: \App\Product::whereIn([34, 55])->appends('status');
results in "Method appends does not exist.",
I saw that you can use "appends" on "->paginate()"
$products = \App\Product::whereIn([34, 55])
->paginate(12)
->appends('status');
But that appends it as a query string to the url. Very strange - I want to append it in the same way as for a single result in the json response.
You have not fetched the collection first, and then access the attribute of result.
$prod = \App\Product::find(736);
$status = $prod->status;
I've found a technique to insert data in two entities with one form here:
http://forum.symfony-project.org/viewtopic.php?f=23&t=42011
My problem is that getData() return an array of objects and I can't use it with the persist() method because it expects an object. How can I fix it?
You might be looking for something like this:
$data = $form->getData();
foreach ($data as $object) {
$em->persist($object);
}
$em->flush();
I have a dropdown menu in my form and the form structure depends on its value. I have managed to solve the "form-update-issue" with event subscriber/listener class, where i am trying to update the main form according to dropdown's value.
The main problem is that i have to modify the form from values that persisted in the database.
My DB schema:
I have 4 table: Model, ModelCategory, ModelCategoryKey, ModelParameter.
ModelCategory 1--n Model 1--m ModelParameter
ModelCategory 1--n ModelCategoryKey
ModelCategoryKey 1--n ModelParameter
After the user choose a ModelCategory from the form's (form based on Model entity) dropdown i have to update the form with ModelParamater rows, but it's number and default values depends on ModelCategory 1--n ModelCategoryKey assocaiton.
I've tried to attach NEW ModelParameter entities to the main Model entity during the PRE_BIND event (also set their default values) and it seems working fine, but when i add the 'parameters' with a 'collection' typed element to the form i get the next error:
Entities passed to the choice field must be managed. Maybe persist them in the entity manager?
Clearly my entities can't be (and shouldn't be) persisted at this time.
All ideas are welcome!
UPDATE:
Modifying the form after preSubmit/preBind:
$form->add('parameters','collection',array(
'type' => new ModelParameterType(),
));
OR
$form->add(
$this->factory->createNamed('parameters','collection',null,
array(
'type' => new ModelParameterType()
))
);
where the 'factory' attribute is a FormFactoryInterface. The error message is the same.
UPDATE2:
Further investigation proved, that if i don't add "default" entities to the assocation. Then it works without error.
Here is the source of my form modifying method:
public function preSubmit(FormEvent $event) {
$form = $event->getForm();
$id = $event->getData()['modelCategory'];
$entity = $form->getData();
$categoryKeys = $this->em->getRepository('MyBundle:ModelCategoryKey')->findByModelCategory(
$this->em->getReference('MyBundle:modelCategory',$id)
);
foreach ($categoryKeys as $key) {
$param = new ModelParameter();
$param->setModel($entity);
$param->setKey($key);
$entity->addParameter($param);
}
$form->add(
$this->factory->createNamed('parameters','collection',null,
array(
'type' => new ModelParameterType(),
'allow_add' => true,
'cascade_validation' => true
))
);
}
SEEMS TO BE SOLVED BY
I have just commented out the $param->setModel($entity); line and it seems to be working fine. I will work this out more and will share the experience, if it realy works.
choice field accepts only managed entities, as the value is set to the entity after submit, and form posts only entities ID, so it must be saved beforehand.
You don't need choice field - you need collection of parameter subforms.
$formBuilder
->add('category', 'category_select')
->add('parameters', 'collection', array('type' => 'parameter'))
;
I'm assuming here that category_select is choice field with categories and parameter is subform with it's own values, depending on your parameter structure.
When you have category in your controller, you can bind the newly created entity with added Parameter entities with their key set, depending on ModelCategoryKey.
I've managed to solve my problem, so here it is what i've found out:
It is enough to add the newly created object by the adder function of the inverse side. I don't have to call the owning side's setter.
Inverse side adder function must be modified, that it calls the owning side's setter.
Inverse side adder function must check if the object is not in the collection already.
PRE_SET_DATA event happens, when the form is created. (so in new entities it is empty, and in old ones it is filled)
I'm trying to use a select object to filter the results of a many to many rowset. This call works great:
$articles = $this->model->findArticlesViaArticlesUsers();
This however does not:
$articles = new Default_Model_Articles();
$articleSelect = $articles->select();
$articleSelect->where("status = 'published'")
->order("date_published DESC")
->limit(1);
$articles = $this->model->findArticlesViaArticlesUsers($articleSelect);
That throws the following error:
exception 'Zend_Db_Select_Exception'
with message 'You cannot define a
correlation name 'i' more than once'
I can't figure out how to successfully get "articles that have the status of 'published'" using the magic many-to-many relationship (nor findManyToManyRowset). I'm at the end of my rope and thinking of just writing the sql manually. Any ideas?
When defining the select statement, you must use the same object that you call findManyToManyRowset (or whatever magic function you use) on.
Ex:
$articles = new Default_Model_Articles();
$user = $articles->find($userId)->current();
$select = $user->select();
$select->where('status = ?', 'published');
$articles = $user->findArticlesViaArticlesUsers($select);
Notice the select statement and findArticlesViaArticlesUsers are both extending $user. Thats the key.
I think you've misunderstood how the relationships work.
See this manual page - you should call the magic method, findArticlesViaArticlesUsers, on a Row object. In this case, I think you want to find a User, and then call findArticles... on that.