Fuel PHP - to_array() method and multiple belongs_to relationships and eager loading - fuelphp

I am attempting to migrate some legacy data models/schemas to a fuel API, and have run into an odd issue with the to_array() method on a model that has two $_belongs_to properties.
When I load the model without the to_array() method, I properly receive both related items with eager loading, but as soon as I pass them through this function to convert the data to make it digestable by the new API, it will strip out the second $_belongs_to property. If I re-order the props in the $belongs_to array, it will show whichever item is first in the array.
My question is, how can I convert this data to an array without losing the second relationship?
Here are some cleaned up examples for ease of reference:
Transaction Model:
protected static $_belongs_to = array(
'benefactor' => array(
'key_from' => 'from_user_id',
'model_to' => 'Model\\Legacy\\User',
'key_to' => 'id',
),
'user' => array(
'key_from' => 'user_id',
'model_to' => 'Model\\Legacy\\User',
'key_to' => 'id',
),
);
Transaction Controller:
$result = array();
$id = $this->param('id');
if (!empty($id)) {
$transaction = Transaction::find($id, array('related' => array('user', 'benefactor',)));
if (!empty($transaction)) {
// Works -- both benefactor and user are returned
$result['transaction_works'] = $transaction;
// Does not work -- only the benefactor is returned
$result['transaction_doesnt_work'] = $transaction->to_array();
}
}
return $this->response($result);

For any googlers looking for help on this issue, I was seemingly able to return all relationships by simply executing the to_array() method before setting the return/results variable:
$result = array();
$id = $this->param('id');
if (!empty($id)) {
$transaction = Transaction::find($id, array('related' => array('user', 'benefactor',)));
if (!empty($transaction)) {
$transaction->to_array();
$result['transaction_works'] = $transaction;
}
}
return $this->response($result);
Good luck!

Related

Symfony5 handleRequest updating original collectionType objects

I cannot make my logic work when following the official Symfony docs here: https://symfony.com/doc/current/form/form_collections.html#allowing-tags-to-be-removed
Based on the example i need to get the originalTags and then compare them with the new tags after form has been handled.
In my case I have a Purchase entity, that can have a collection of PurchaseProducts(ManyToMany). In my case, when I change a PurchaseProduct I need to update the stock of the purchase that has been removed. However no matter how I get the original PurchaseProducts, after $form->handleRequest() they are updated with the new values and I lose any information about the original ones.
Fragments form my controller with the logic:
/** #var Purchase $purchase */
$purchase = $this->getDoctrine()
->getRepository(Purchase::class)
->find($id);
if (!$purchase) {
$this->addFlash('error', 'Purchase not found');
return $this->redirect($this->generateUrl('purchase_list'));
}
$originalProducts = new ArrayCollection();
foreach ($purchase->getPurchaseProducts() as $purchaseProduct) {
$originalProducts->add($purchaseProduct);
}
$form = $this->createForm(PurchaseType::class, $purchase);
if ($request->isMethod('POST')) {
dump($originalProducts); // Original entities are here
$form->handleRequest($request);
dump($originalProducts);die; // Original entities are updated with the new ones
...
// This will not work since originalProducts already has the new entities
foreach ($originalProducts as $purchaseProduct) {
if (false === $purchase->getPurchaseProducts()->contains($purchaseProduct)) {
// update stock here
}
}
I have tried many options, like cloning, querying the database and so on, but after handleRequest I always get the same updated entities. Why?
Explanation of Behavior
As you are referring to the "allow_delete" => true or "allow_add" => true concepts of the form processor. The entity property changes within the collection appearing in the copy when the Form is submitted is the expected behavior. However, the $originalProducts collection will NOT contain any new entities (new PurchaseProduct()).
This occurs because PHP passes the objects by-reference, namely the PurchaseProduct object to the ArrayCollection. Meaning any changes made to the embedded form object are applied to both the Purchase:::$purchaseProducts and the $originalProducts collections, since they are the same PurchaseProduct object (by-reference).
However, when they are removed from the Purchase:::$purchaseProducts collection after $form->handleRequest($request), the objects will still exist in the $originalProducts collection. Which allows for you to compare the two collections to remove them from the Entity Manager or your Entity collection in the event your Entity does not contain the necessary logic.
Example using ArrayObject and Foo objects: https://3v4l.org/oLZqO#v7.4.25
Class Foo
{
private $id;
public function __construct()
{
$this->id = uniqid('', false);
}
public function setId($id)
{
$this->id = $id;
}
}
//initial state of Purchase::$purchaseProducts
$foo1 = new Foo();
$foo2 = new Foo();
$a = new ArrayObject([$foo1, $foo2]);
//Create Copy as $originalProducts
$b = new ArrayObject();
foreach ($a as $i => $foo) {
$b->offsetSet($i, $foo);
}
//form submission
$foo1->setId('Hello World');
$a->offsetUnset(1);
Result
Initial state of Copy:
ArrayObject::__set_state(array(
0 =>
Foo::__set_state(array(
'id' => '6182c24b00a21',
)),
1 =>
Foo::__set_state(array(
'id' => '6182c24b00a28',
)),
))
-----------------------
Form Submitted ID Changed in Copy:
ArrayObject::__set_state(array(
0 =>
Foo::__set_state(array(
'id' => 'Hello World',
)),
1 =>
Foo::__set_state(array(
'id' => '6182c24b00a28',
)),
))
-----------------------
Source has foo2 entity removed:
ArrayObject::__set_state(array(
0 =>
Foo::__set_state(array(
'id' => 'Hello World',
)),
))
-----------------------
Copy still contains both entities:
ArrayObject::__set_state(array(
0 =>
Foo::__set_state(array(
'id' => 'Hello World',
)),
1 =>
Foo::__set_state(array(
'id' => '6182c24b00a28',
)),
))
Resolutions
Depending on your desired result, there are several approaches that can be used to detect and handle the changes, such as Change Tracking Policies.
Another way to determine what has changed for the entities, is the $em->getUnitOfWork()->getEntityChangeSet($entity) to retrieve the changes for an entity that was proposed to doctrine.
Code Suggestion
To ensure the request is not misinterpreted, you should always handle the form request (regardless of the request method) and verify that the form was submitted/valid. This is because the handleRequest method triggers multiple events depending on the request method.
/** #var Purchase $purchase */
$purchase = $this->getDoctrine()
->getRepository(Purchase::class)
->find($id);
if (!$purchase) {
$this->addFlash('error', 'Purchase not found');
return $this->redirect($this->generateUrl('purchase_list'));
}
$originalProducts = new ArrayCollection();
foreach ($purchase->getPurchaseProducts() as $purchaseProduct) {
$originalProducts->add($purchaseProduct);
}
$form = $this->createForm(PurchaseType::class, $purchase);
dump($originalProducts); // Original entities are here
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
dd($originalProducts); // dump+die as dd() - Original entities are updated with the new ones
//...
// This will not work since originalProducts already has the new entities
foreach ($originalProducts as $purchaseProduct) {
if (false === $purchase->getPurchaseProducts()->contains($purchaseProduct)) {
//remove original from the Purchase entity
}
}

Yii CJuiAutoComplete for Multiple values

I am a Yii Beginner and I am currently working on a Tagging system where I have 3 tables:
Issue (id,content,create_d,...etc)
Tag (id,tag)
Issue_tag_map (id,tag_id_fk,issue_id_fk)
In my /Views/Issue/_form I have added a MultiComplete Extension to retrieve multiple tag ids and labels,
I have used an afterSave function in order to directly store the Issue_id and the autocompleted Tag_ids in the Issue_tag_map table, where it is a HAS_MANY relation.
Unfortunately Nothing is being returned.
I wondered if there might be a way to store the autocompleted Tag_ids in a temporary attribute and then pass it to the model's afterSave() function.
I have been searching for a while, and this has been driving me crazy because I feel I have missed a very simple step!
Any Help or advices of any kind are deeply appreciated!
MultiComplete in Views/Issue/_form:
<?php
echo $form->labelEx($model, 'Tag');
$this->widget('application.extension.MultiComplete', array(
'model' => $model,
'attribute' => '', //Was thinking of creating a temporary here
'name' => 'tag_autocomplete',
'splitter' => ',',
'sourceUrl' => $this->createUrl('Issue/tagAutoComplete'),
// Controller/Action path for action we created in step 4.
// additional javascript options for the autocomplete plugin
'options' => array(
'minLength' => '2',
),
'htmlOptions' => array(
'style' => 'height:20px;',
),
));
echo $form->error($model, 'issue_comment_id_fk');
?>
AfterSave in /model/Issue:
protected function afterSave() {
parent::afterSave();
$issue_id = Yii::app()->db->getLastInsertID();
$tag; //here I would explode the attribute retrieved by the view form
// an SQL with two placeholders ":issue_id" and ":tag_id"
if (is_array($tag))
foreach ($tag as $tag_id) {
$sql = "INSERT INTO issue_tag_map (issue_id_fk, tag_id_fk)VALUES(:issue_id,:tag_id)";
$command = Yii::app()->db->createCommand($sql);
// replace the placeholder ":issue_id" with the actual issue value
$command->bindValue(":issue_id", $issue_id, PDO::PARAM_STR);
// replace the placeholder ":tag_id" with the actual tag_id value
$command->bindValue(":tag_id", $tag_id, PDO::PARAM_STR);
$command->execute();
}
}
And this is the Auto Complete sourceUrl in the Issue model for populating the tags:
public static function tagAutoComplete($name = '') {
$sql = 'SELECT id ,tag AS label FROM tag WHERE tag LIKE :tag';
$name = $name . '%';
return Yii::app()->db->createCommand($sql)->queryAll(true, array(':tag' => $name));
actionTagAutoComplete in /controllers/IssueController:
// This function will echo a JSON object
// of this format:
// [{id:id, name: 'name'}]
function actionTagAutocomplete() {
$term = trim($_GET['term']);
if ($term != '') {
$tags = issue::tagAutoComplete($term);
echo CJSON::encode($tags);
Yii::app()->end();
}
}
EDIT
Widget in form:
<div class="row" id="checks" >
<?php
echo $form->labelEx($model, 'company',array('title'=>'File Company Distrubution; Companies can be edited by Admins'));
?>
<?php
$this->widget('application.extension.MultiComplete', array(
'model' => $model,
'attribute' => 'company',
'splitter' => ',',
'name' => 'company_autocomplete',
'sourceUrl' => $this->createUrl('becomEn/CompanyAutocomplete'),
'options' => array(
'minLength' => '1',
),
'htmlOptions' => array(
'style' => 'height:20px;',
'size' => '45',
),
));
echo $form->error($model, 'company');
?>
</div>
Update function:
$model = $this->loadModel($id);
.....
if (isset($_POST['News'])) {
$model->attributes = $_POST['News'];
$model->companies = $this->getRecordsFromAutocompleteString($_POST['News']
['company']);
......
......
getRecordsFromAutocompleteString():
public static cordsFromAutocompleteString($string) {
$string = trim($string);
$stringArray = explode(", ", $string);
$stringArray[count($stringArray) - 1] = str_replace(",", "", $stringArray[count($stringArray) - 1]);
$criteria = new CDbCriteria();
$criteria->select = 'id';
$criteria->condition = 'company =:company';
$companies = array();
foreach ($stringArray as $company) {
$criteria->params = array(':company' => $company);
$companies[] = Company::model()->find($criteria);
}
return $companies;
}
UPDATE
since the "value" porperty is not implemented properly in this extension I referred to extending this function to the model:
public function afterFind() {
//tag is the attribute used in form
$this->tag = $this->getAllTagNames();
parent::afterFind();
}
You should have a relation between Issue and Tags defined in both Issue and Tag models ( should be a many_many relation).
So in IssueController when you send the data to create or update the model Issue, you'll get the related tags (in my case I get a string like 'bug, problem, ...').
Then you need to parse this string in your controller, get the corresponding models and assigned them to the related tags.
Here's a generic example:
//In the controller's method where you add/update the record
$issue->tags = getRecordsFromAutocompleteString($_POST['autocompleteAttribute'], 'Tag', 'tag');
Here the method I'm calling:
//parse your string ang fetch the related models
public static function getRecordsFromAutocompleteString($string, $model, $field)
{
$string = trim($string);
$stringArray = explode(", ", $string);
$stringArray[count($stringArray) - 1] = str_replace(",", "", $stringArray[count($stringArray) - 1]);
return CActiveRecord::model($model)->findAllByAttributes(array($field => $stringArray));
}
So now your $issue->tags is an array containing all the related Tags object.
In your afterSave method you'll be able to do:
protected function afterSave() {
parent::afterSave();
//$issue_id = Yii::app()->db->getLastInsertID(); Don't need it, yii is already doing it
foreach ($this->tags as $tag) {
$sql = "INSERT INTO issue_tag_map (issue_id_fk, tag_id_fk)VALUES(:issue_id,:tag_id)";
$command = Yii::app()->db->createCommand($sql);
$command->bindValue(":issue_id", $this->id, PDO::PARAM_INT);
$command->bindValue(":tag_id", $tag->id, PDO::PARAM_INT);
$command->execute();
}
}
Now the above code is a basic solution. I encourage you to use activerecord-relation-behavior's extension to save the related model.
Using this extension you won't have to define anything in the afterSave method, you'll simply have to do:
$issue->tags = getRecordsFromAutocompleteString($_POST['autocompleteAttribute'], 'Tag', 'tag');
$issue->save(); // all the related models are saved by the extension, no afterSave defined!
Then you can optimize the script by fetching the id along with the tag in your autocomplete and store the selected id's in a Json array. This way you won't have to perform the sql query getRecordsFromAutocompleteString to obtain the ids. With the extension mentioned above you'll be able to do:
$issue->tags = CJSON::Decode($_POST['idTags']);//will obtain array(1, 13, ...)
$issue->save(); // all the related models are saved by the extension, the extension is handling both models and array for the relation!
Edit:
If you want to fill the autocomplete field you could define the following function:
public static function appendModelstoString($models, $fieldName)
{
$list = array();
foreach($models as $model)
{
$list[] = $model->$fieldName;
}
return implode(', ', $list);
}
You give the name of the field (in your case tag) and the list of related models and it will generate the appropriate string. Then you pass the string to the view and put it as the default value of your autocomplete field.
Answer to your edit:
In your controller you say that the companies of this model are the one that you added from the Autocomplete form:
$model->companies = $this->getRecordsFromAutocompleteString($_POST['News']
['company']);
So if the related company is not in the form it won't be saved as a related model.
You have 2 solutions:
Each time you put the already existing related model in you autocomplete field in the form before displaying it so they will be saved again as a related model and it won't disapear from the related models
$this->widget('application.extensions.multicomplete.MultiComplete', array(
'name' => 'people',
'value' => (isset($people))?$people:'',
'sourceUrl' => array('searchAutocompletePeople'),
));
In your controller before calling the getRecordsFromAutocompleteString you add the already existing models of the model.
$model->companies = array_merge(
$model->companies,
$this->getRecordsFromAutocompleteString($_POST['News']['company'])
);

Zend form populate method

I have a Zend form below is the code
public function editAction()
{
try
{
$data = Zend_Auth::getInstance()->getStorage()->read();
$this->view->UserInfo = $data['UserInfo'];
$this->view->Account = $data['Account'];
$UserEditForm = $this->getUserEditForm();
$this->view->UserEditForm = $UserEditForm;
$params = $this->_request->getParams();
if ($params['user'])
{
$UserResult = $this->_user_model->getUserData($params['user']);
$UserAddressResult = $this->_user_model->getAddressData($params['user']);
$UserInfo = Array(
'UserId' => $UserResult['user_id'],
'EmailAddress' => $UserResult['email'],
'UserName' => $UserResult['username'],
'Title' => $UserResult['Title'],
'FirstName' => $UserResult['firstname'],
'LastName' => $UserResult['lastname'],
'Gender' => $UserResult['gender'],
'DateOfBirth' => date('m/d/Y', strtotime($UserResult['dateofbirth'])),
'AddressLine1' => $UserAddressResult['address_1'],
'AddressLine2' => $UserAddressResult['address_2'],
'City' => $UserAddressResult['city'],
'State' => $UserAddressResult['state_id'],
'PostalCode' => $UserAddressResult['postcode'],
'Country' => $UserAddressResult['country_id'],
'CompanyName' => $UserAddressResult['company'],
'WorkPhone' => $UserAddressResult['workphone'],
'HomePhone' => $UserAddressResult['homephone'],
'Fax' => $UserAddressResult['fax'],
'IsDashboardUser' => $UserResult['is_dashboard_user']
);
$UserEditForm->populate($UserInfo);
$this->view->UserEditForm = $UserEditForm;
}
if ($this->_request->isPost())
{
$values = $this->_request->getPost();
unset($values['Save']);
if ($UserEditForm->isValid($values))
{
$Modified_date = date('Y-m-d H:i:s');
$UserData = $this->_user_model->CheckEmail($values['EmailAddress']);
$UpdateData = $this->_user_model->UpdateUserData($UserData['user_id'], $values, $Modified_date, $data['UserId']);
if ($UpdateData != null)
{
return $this->_helper->redirector('userlist','index','user');
}
}
}
}
catch (Exception $exception)
{
echo $exception->getCode();
echo $exception->getMessage();
}
}
Because my form elements names are different then my table field names i have to declare a Array $UserAddressResult see above code to match the table field name with form element name.
Is there a another way to populate form without declaring this array.
Please don't suggest that i have to keep my table field name and form element name same. I cannot do that as per our naming convention standards.
Your naming convention is inconsistent. If it were consistent, you could perhaps use a simple regular expression to transform column names. But you can't, so you will have to do it manually one way or the other.
If you need to construct this array of values in more than one place in your code, you should consider moving the logic to the form itself (extend it with a public function populateFromUserAndResult($userResult, $userAddress)) or an action helper.
We decided to keep same name of form elements as per our table fields name. For now this is the only solutions i feel. if i come across any other solutions in future will update here...
Thanks for all your replies....

How do I populate a Zend Form from a Doctrine Model with Many To One relationships?

I have an entity setup called Lead which contains a car make, model, etc and this Lead is mapped by a Many to One relationship to a Client entity, which has forname, surname, etc.
i.e. A client may have many leads
I have created a toArray function which gets the data from the Lead,
public function toArray()
{
$record_data = get_object_vars($this);
$formatted_record_data = array();
foreach($record_data as $name=>$value){
if (is_object($value)){
if (get_class($value) == 'DateTime') {
$value = $this->datetimeToString($value);
} else {
$value = $value->toArray();
}
}
$formatted_record_data[$this->from_camel_case($name)] = $value;
}
return $formatted_record_data;
}
which then populates a Zend Form using:
$record = $this->_em->getRepository($this->_entity)->find($this->_primaryId);
$form->setDefaults($record->toArray());
This works fine for the fields for the Lead entity which are populated, but it does not populate the Client-based fields e.g. forname.
EDIT
I have fixed my problem by the following method:
1) Adding the following method to my Update Action.
$this->_record = $this->_em->getRepository($this->_entity)->find($this->_primaryId);
$this->_form->setRecord($this->_record);
$this->view->form = $this->_form;
2) Adding the following method to my Form Model
public function setRecord($record)
{
$data = array('registration' => $record->registration,
'make' => $record->make,
'model' => $record->model,
'pav' => $record->pav,
'salvage_value' => $record->salvageValue,
'forname' => $record->client->forname,
'surname' => $record->client->surname,
'vehicle_address1' => $record->vehicleAddress1,
'vehicle_address2' => $record->vehicleAddress2,
'vehicle_address3' => $record->vehicleAddress3,
'vehicle_address4' => $record->vehicleAddress4,
'vehicle_address5' => $record->vehicleAddress5,
'vehicle_postcode' => $record->vehiclePostcode,
'category' => $record->category,
'colour' => $record->colour
);
$this->setDefaults($data);
}
This way I can manually get the related data, in this case:
'forname' => $record->client->forname,
'surname' => $record->client->surname,
and add them to the form using:
$this->setDefaults($data);
try :
$leads = $record->toArray();
$client_info = array('name' => 'test', 'surname' => 'test 2'); // or if from db use what you did for the leads.
$defaults = array_merge($leads, $client_info);
$form->setDefaults($defaults);

$_referenceMap Relationships with Zend_Db_Table_Abstract creates too many queries

This is my first time using Zend Framework for an application and i don't know if I completely have by head around Models.
I have four tables: shopping_cart, product, product_unit, distributor.
shopping cart has an cart_id, product_id, unit_id and dist_id (shopping cart joins on the other tables with their corresponding id).
Before Zend I would create a class like this:
class ShoppingCart
{
function getItems()
{
$sql ="select * from shopping_cart, product, product_unit, distributor
where
shopping_cart.product_id = product.id AND
shopping_cart.unit_id = product_unit.id AND
shopping_cart.dist_id = distributor.id AND
cart_id = xxx";
$items = $this->db->getAll($sql);
}
One query to get all the information from the joined tables.
When I set up the relationship mapping in Zend_Db_Table_Abstract:
My Shopping Cart Model:
class Application_Model_ShoppingCart
{
function __construct()
{
$this->ShoppingCartTable = new Application_Model_DbTable_ShoppingCart();
}
function getItems()
{
$cart_items = $this->ShoppingCartTable->getItems($this->GetCartId());
return $cart_items;
}
}
class Application_Model_DbTable_ShoppingCart extends Zend_Db_Table_Abstract
{
protected $_name = 'shopping_cart';
protected $_rowClass = 'Application_Model_DbTable_ShoppingCart_Item';
protected $_referenceMap = array(
'Product' => array(
'columns' => 'product_id',
'refTableClass' => 'Application_Model_DbTable_Product',
'refColumns' => 'id'
),
'Distributor' => array(
'columns' => 'dist_id',
'refTableClass' => 'Application_Model_DbTable_Distributor',
'refColumns' => 'id'
),
'Unit' => array(
'columns' => 'unit_id',
'refTableClass' => 'Application_Model_DbTable_ProductUnit',
'refColumns' => 'id'
)
);
public function getItems($cart_id)
{
$where = $this->getAdapter()->quoteInto('cart_id = ?', $cart_id);
return $this->fetchAll($where);
}
}
In my controller:
$this->_shoppingCartModel = new Application_Model_ShoppingCart();
$items = $this->_shoppingCartModel->getItems();
IN my view :
foreach($this->items AS $item)
{
$item_product = $item->findParentRow('Application_Model_DbTable_Product');
$item_dist = $item->findParentRow('Application_Model_DbTable_Distributor');
$item_unit = $item->findParentRow('Application_Model_DbTable_ProductUnit');
}
when I have ten items in my cart the db profiler shows over sixty queries (WHOA) to view the cart items ( information across all four tables are displayed - product name, unit description, distributor name).
For each item it queries the shopping_cart, then querys the product table, then the product unit, then the distributor_table.
Is there a way to have this run as one query joining all the tables via Zend_Db_Table_Abstract relationships?
Will I have to go back to using db adapter in the my Application_Model_ShoppingCart class?
I want to abstract all data access to the table models (Application_Model_DbTable_ShoppingCart) and not have the Application_Model_ShoppingCart tied to a db handler.
Thanks in advance for advice, I love the Zend Framework but models are still hard for me to understand given the different conflicting ways people talk about using them.
In short, no, unfortunately it's not possible to get a set of table rows together with their relationships in a single query.
It's just that all methods dealing with relationships are defined for a row, not for a table.
But at least, you can form your sql with Zend_Db_Table_Select instead of writing it all manually.
Upd: Your code for fetching ShoppingCarts, in my opinion, should belong to the table (DbTable_ShoppingCart). So, the code you provided in the beginning could be transformed to the following:
class Application_Model_DbTable_ShoppingCart extends Zend_Db_Table_Abstract {
public function getItem($cart_id) {
$select = $this->select()
->from( array('sc' => 'shopping_cart'), array(Zend_Db_Select::SQL_WILDCARD) )
->join( array('p' => 'product'), 'sp.product_id = p.id', array(Zend_Db_Select::SQL_WILDCARD) )
->join( array('pu' => 'product_unit'), 'sp.unit_id = pu.id', array(Zend_Db_Select::SQL_WILDCARD) )
->join( array('d' => 'distributor'), 'sp.dist_id = d.id', array(Zend_Db_Select::SQL_WILDCARD) )
->where('sp.cart_id = ?', $cart_id)
->setIntegrityCheck(false);
return $this->fetchAll($select);
}
}