Under Symfony4.2, I have a Translate entity (id, gb_name, fr_name) and LocationCountry entity (id, ISO3166-2 name: GB,FR, DE…, translate_id)
I define a CSV file with 255 countries ("GB", "Great Britain", "Angleterre"…) and I want to push it in Translate and LocationCountry entities tables with DataFixture.
I read carefully https://symfony.com/doc/current/bundles/DoctrineFixturesBundle/index.html#sharing-objects-between-fixtures
and
php create fixtures with automatic relations
src/DataFixtures/TranslateFixtures.php:
if ($csv_handle) {
while ($item = fgetcsv($csv_handle, $csv_max_line_length, $csv_delimiter, $csv_enclosure)) {
$obj = new Translate();
$obj->setGbValue($item[1]);
$obj->setFrValue($item[2]);
$this->addReference('country'.$item[0], $obj);
$manager->persist($obj);
}
fclose($csv_handle);
}
$manager->flush();
I am not sure addReference should be before flush() ?
src/DataFixtures/LocationCountryFixtures.php:
if ($csv_handle) {
while ($item = fgetcsv($csv_handle, $csv_max_line_length, $csv_delimiter, $csv_enclosure)) {
$translate_country = $this->getReference('country'.$item[0]);
$obj = new LocationCountry();
$obj->setIso3166Name($item[0]);
$obj->setTranslate($translate_country);
$manager->persist($obj);
}
fclose($csv_handle);
}
$manager->flush();
}
public function getDependencies() {
return array(
Translate::class,
);
}
If I remove addReference Translate entity is well filled.
But with the code above, it returns error:
In SymfonyFixturesLoader.php line 76:
The "App\Entity\Translate" fixture class is trying to be loaded, but is not available. Make sure this class is defined as a service and tagged with "doctrine.fixture.orm".
I think to have the right Use:
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\DataFixtures\DependentFixtureInterface;
use App\Entity\LocationCountry;
use App\Entity\Translate;
Thank for your help
Doctrine loads the fixture files in alphabetical order; that's why you get an error. You can consider using function getOrder in your fixtures in order to set which one will be load first.
EDIT :
You get an error because you don't provide the right class in your getDependencies method :
public function getDependencies() {
return array(
TranslateFixtures::class,
);
}
In this case, I just remove src/DataFixtures/TranslateFixtures.php
and change src/DataFixtures/LocationCountryFixtures.php to do all job:
if ($csv_handle) {
while ($item = fgetcsv($csv_handle, $csv_max_line_length, $csv_delimiter, $csv_enclosure)) {
//$translate_country = $this->getReference('country'.$item[0]);
$country = new LocationCountry();
$translate_country = new Translate();
$translate_country->setGbValue($item[1]);
$translate_country->setFrValue($item[2]);
$country->setIso3166Name($item[0]);
$country->setTranslateCountry($translate_country);
$manager->persist($translate_country);
$manager->persist($country);
}
fclose($csv_handle);
}
$manager->flush();
Related
In my repositories, I have methods with too many arguments (for use in where) :
Example :
class ProchaineOperationRepository extends EntityRepository
{
public function getProchaineOperation(
$id = null, // Search by ID
\DateTime $dateMax = null, // Search by DateMax
\DateTime $dateMin = null, // Search by DateMin
$title = null // Search by title
)
In my controllers, I have differents action ... for get with ID, for get with ID and DateMin, for get ID and Title, ...
My method is too illegible because too many arguments ... and it would be difficult to create many methods because they are almost identical ...
What is the best practice ?
You have two main concerns in your question
You have too many arguments in your repository method which will be used in 'where' condition of the eventual query. You want to organize them in a better way
The repository method should be callable from the controller in a meaningful way because of possible complexity of arguments passed
I suggest you to write a Repository method like:
namespace AcmeBundle\Repository;
/**
* ProchaineOperationRepository
*
*/
class ProchaineOperationRepository extends \Doctrine\ORM\EntityRepository
{
public function search($filters, $sortBy = "id", $orderBy = "DESC")
{
$qb = $this->createQueryBuilder("po");
foreach ($filters as $key => $value){
$qb->andWhere("po.$key='$value'");
}
$qb->addOrderBy("po.$sortBy", $orderBy);
return $qb->getQuery()->getArrayResult();
}
}
The $filters variable here is an array which is supposed to hold the filters you are going to use in 'where' condition. $sortBy and $orderBy should also be useful to get the result in properly sequenced way
Now, you can call the repository method from your controller like:
class ProchaineOperationController extends Controller
{
/**
* #Route("/getById/{id}")
*/
public function getByIdAction($id)
{
$filters = ['id' => $id];
$result = $this->getDoctrine()->getRepository("AcmeBundle:ProchaineOperation")->search($filters);
//process $result
}
/**
* #Route("/getByTitle/{title}")
*/
public function getByTitleAction($title)
{
$filters = ['title' => $title];
$sortBy = 'title';
$result = $this->getDoctrine()->getRepository("AcmeBundle:ProchaineOperation")->search($filters, $sortBy);
//process $result
}
/**
* #Route("/getByIdAndDateMin/{id}/{dateMin}")
*/
public function getByIdAndDateMinAction($id, $dateMin)
{
$filters = ['id' => $id, 'dateMin' => $dateMin];
$sortBy = "dateMin";
$orderBy = "ASC";
$result = $this->getDoctrine()->getRepository("AcmeBundle:ProchaineOperation")->search($filters, $sortBy, $orderBy);
//process $result
}
}
Note that you are calling the same repository method for all controller actions with minor changes according to your parameters. Also note that $sortBy and $orderBy are optionally passed.
Hope it helps!
If your objective is only to query with an AND operator between each properties, the best way could be to use the method proposed by doctrine for that : findBy() cf : this part of the doc
for instance :
$results = $this
->getDoctrine()
->getRepository('AppBundle:ProchaineOperation')
->findBy(array('dateMax' => $myDate, 'title' => 'Hello world');
EDIT : after comment
Then use the same way as Doctrine do : Pass only an array with id, dateMax... as keys if these are set. This should be solve the method signature problem which gives you so much trouble. :)
I have devices being parts of brands and repairs being part of devices. Now I'm trying to get a simple AJAX call which will allow me to search for a device by either brand name or device name. Unfortunately, I get circular references. Even when I've written a handler for circular references to limit it to one, I still get too much information in my objects.
Consider the following return from serialize on my DQL query:
[{"0":{"id":1,"name":"iPhone
1","logo":"iPhone1","brand":{"id":2,"name":"Apple","logo":"apple","devices":["iPhone
1",{"id":2,"name":"iPhone","logo":"iphone","brand":"Apple","deletedAt":null,"repairs":[]}],"deletedAt":null},"deletedAt":null,"repairs":[]},"name":"Apple"},{"0":{"id":2,"name":"iPhone","logo":"iphone","brand":{"id":2,"name":"Apple","logo":"apple","devices":[{"id":1,"name":"iPhone
1","logo":"iPhone1","brand":"Apple","deletedAt":null,"repairs":[]},"iPhone"],"deletedAt":null},"deletedAt":null,"repairs":[]},"name":"Apple"}]
Here I don't even need repairs at all. However, since it is referenced in the PartEntity, I still get a bunch of unnecessary repair info. How can I limit the data I get out of an object?
my Controller code:
public function ajaxShowDevicesAction(Request $request) {
//if ($request->isXmlHttpRequest()) {
$data = $request->query->get('data');
$result = "";
if ($data) {
$result = $this->getDoctrine()->getManager()->getRepository('AppBundle:Device')->findAllByBrandOrName($data);
}
if ($result) {
$encoders = array(new XmlEncoder(), new JsonEncoder());
$normalizers = array(new GetSetMethodNormalizer());
$normalizers[0]->setCircularReferenceHandler(function ($object) {
return $object->getName();
});
$serializer = new Serializer($normalizers, $encoders);
$jsoncontent = $serializer->serialize($result, 'json');
$response = new Response($jsoncontent);
return $response;
}
// else { # unsure how to give a "no results" response
// $response = new Response(json_encode(array()));
// $response->headers->set('Content-Type', 'application/json');
// return $response;
// }
// } else {
// throw new HttpException(403, "Ajax access only");
// }
}
You can use
setCircularReferenceLimit()
method for normalizers.
Handling Circular References
I use Joomla 2.5 framework.
I have simple table such as:
int id
string itemid
Now I just want to load all 'itemid's to array using JTable. Is here possibility?
Everything about the JTable Class only deals with one row, as soon as multiple rows are involved, you have two options:
1) Use the solution you gave.
2) Override the load() function in your Table class. This can be done as under:
Put the following load() function in your Table class:
function load($key = null)
{
$db = $this->getDBO();
$query = $db->getQuery(true);
$query->select($key);
$query->from($this->getTableName());
$db->setQuery($query);
$row = $db->loadRowList();
if ($db->getErrorNum())
{
$this->setError($db->getErrorMsg());
return false;
}
// Check that we have a result.
if (empty($row))
{
return false;
}
//Return the array
return $row;
}
Now call the load() function with a single argument 'itemid', and get the array you want.
This worked for me, hope it helps you too.
Solution that I decided to use is inherit model class from JModelList:
class modelModelcomponent extends JModelList
{
protected function getListQuery()
{
// Create a new query object.
$db = JFactory::getDBO();
$query = $db->getQuery(true);
// Select some fields
$query->select('itemid');
// From the hello table
$query->from('#__table');
return $query;
}
}
I am using Docrine 1.2 with Zend Framework and trying to save a Doctrine Collection.
I am retrieving my collection from my table class with the following code.
public function getAll()
{
return $this->createQuery('e')
->orderBy('e.order ASC, e.eventType ASC')
->execute();
}
I also have the following class to reorder the above event records.
class Admin_Model_Event_Sort extends Model_Abstract
{
/**
* Events collection
* #var Doctrine_Collection
*/
protected $_collection = null;
public function __construct()
{
$this->_collection = Model_Doctrine_EventTypesTable::getInstance()->getAll();
}
public function save($eventIds)
{
if ($this->_collection instanceof Doctrine_Collection) {
foreach ($this->_collection as $record)
{
$key = array_search($record->eventTypeId, $eventIds);
if ($key !== false) {
$record->order = (string)$key;
}
}
return $this->_saveCollection($this->_collection);
} else {
return false;
}
}
}
The _saveCollection method above is as follows
/**
* Attempts to save a Doctrine Collection
* Sets the error message property on error
* #param Doctrine_Collection $collection
* #return boolean
*/
protected function _saveCollection(Doctrine_Collection $collection)
{
try {
$collection->save();
return true;
} catch (Exception $e) {
$this->_errorMessage = $e->getMessage();
OpenMeetings_Logger_ErrorLogger::write('Unable to save Doctrine Collection');
OpenMeetings_Logger_ErrorLogger::vardump($this->_errorMessage);
return false;
}
}
The event id's in the above save method is simply an enumerated array of event id's, I am using the keys of the array to set the sort order of the events using the order field. If I do a var_dump of the collection to an array ($this->_collection->toArray()) I get the correct data. However when I attempt to save the collection I get the following error.
"SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'order = '0' WHERE eventtypeid = '3'' at line 1"
Is there anyway I can get Doctrine to expand on this error, the full SQL statement would be a start, also if anyone knows as to why this error is occuring then that would be very helpful.
Many thanks in advance
Garry
EDIT
I have modified my above code to try to work one record at a time but I still get the same problem.
public function save($eventIds)
{
foreach ($eventIds as $key => $eventId) {
$event = Model_Doctrine_EventTypesTable::getInstance()->getOne($eventId);
$event->order = (string)$key;
$event->save();
}
}
Ok I have found the problem. I was using the MYSQL reserved word order as a field name thus the error, changed it to sortOrder and the problem went away.
Hope this helps someone with a similar issue.
Garry
Is there a way to retrieve the set-at-creations properties of an EmberJS object if you don't know all your keys in advance?
Via the inspector I see all the object properties which appear to be stored in the meta-object's values hash, but I can't seem to find any methods to get it back. For example object.getProperties() needs a key list, but I'm trying to create a generic object container that doesn't know what it will contain in advance, but is able to return information about itself.
I haven't used this in production code, so your mileage may vary, but reviewing the Ember source suggests two functions that might be useful to you, or at least worth reviewing the implementation:
Ember.keys: "Returns all of the keys defined on an object or hash. This is useful when inspecting objects for debugging. On browsers that support it, this uses the native Object.keys implementation." Object.keys documentation on MDN
Ember.inspect: "Convenience method to inspect an object. This method will attempt to convert the object into a useful string description." Source on Github
I believe the simple answer is: you don't find a list of props. At least I haven't been able to.
However I noticed that ember props appear to be prefixed __ember, which made me solve it like this:
for (f in App.model) {
if (App.model.hasOwnProperty(f) && f.indexOf('__ember') < 0) {
console.log(f);
}
};
And it seems to work. But I don't know whether it's 100% certain to not get any bad props.
EDIT: Adam's gist is provided from comments. https://gist.github.com/1817543
var getOwnProperties = function(model){
var props = {};
for(var prop in model){
if( model.hasOwnProperty(prop)
&& prop.indexOf('__ember') < 0
&& prop.indexOf('_super') < 0
&& Ember.typeOf(model.get(prop)) !== 'function'
){
props[prop] = model[prop];
}
}
return props;
}
Neither of these answers are reliable, unfortunately, because any keys paired with a null or undefined value will not be visible.
e.g.
MyClass = Ember.Object.extend({
name: null,
age: null,
weight: null,
height: null
});
test = MyClass.create({name: 'wmarbut'});
console.log( Ember.keys(test) );
Is only going to give you
["_super", "name"]
The solution that I came up with is:
/**
* Method to get keys out of an object into an array
* #param object obj_proto The dumb javascript object to extract keys from
* #return array an array of keys
*/
function key_array(obj_proto) {
keys = [];
for (var key in obj_proto) {
keys.push(key);
}
return keys;
}
/*
* Put the structure of the object that you want into a dumb JavaScript object
* instead of directly into an Ember.Object
*/
MyClassPrototype = {
name: null,
age: null,
weight: null,
height: null
}
/*
* Extend the Ember.Object using your dumb javascript object
*/
MyClass = Ember.Object.extend(MyClassPrototype);
/*
* Set a hidden field for the keys the object possesses
*/
MyClass.reopen({__keys: key_array(MyClassPrototype)});
Using this method, you can now access the __keys field and know which keys to iterate over. This does not, however, solve the problem of objects where the structure isn't known before hand.
I use this:
Ember.keys(Ember.meta(App.YOUR_MODEL.proto()).descs)
None of those answers worked with me. I already had a solution for Ember Data, I was just after one for Ember.Object. I found the following to work just fine. (Remove Ember.getProperties if you only want the keys, not a hash with key/value.
getPojoProperties = function (pojo) {
return Ember.getProperties(pojo, Object.keys(pojo));
},
getProxiedProperties = function (proxyObject) {
// Three levels, first the content, then the prototype, then the properties of the instance itself
var contentProperties = getPojoProperties(proxyObject.get('content')),
prototypeProperties = Ember.getProperties(proxyObject, Object.keys(proxyObject.constructor.prototype)),
objectProperties = getPojoProperties(proxyObject);
return Ember.merge(Ember.merge(contentProperties, prototypeProperties), objectProperties);
},
getEmberObjectProperties = function (emberObject) {
var prototypeProperties = Ember.getProperties(emberObject, Object.keys(emberObject.constructor.prototype)),
objectProperties = getPojoProperties(emberObject);
return Ember.merge(prototypeProperties, objectProperties);
},
getEmberDataProperties = function (emberDataObject) {
var attributes = Ember.get(emberDataObject.constructor, 'attributes'),
keys = Ember.get(attributes, 'keys.list');
return Ember.getProperties(emberDataObject, keys);
},
getProperties = function (object) {
if (object instanceof DS.Model) {
return getEmberDataProperties(object);
} else if (object instanceof Ember.ObjectProxy) {
return getProxiedProperties(object);
} else if (object instanceof Ember.Object) {
return getEmberObjectProperties(object);
} else {
return getPojoProperties(object);
}
};
In my case Ember.keys(someObject) worked, without doing someObject.toJSON().
I'm trying to do something similar, i.e. render a generic table of rows of model data to show columns for each attribute of a given model type, but let the model describe its own fields.
If you're using Ember Data, then this may help:
http://emberjs.com/api/data/classes/DS.Model.html#method_eachAttribute
You can iterate the attributes of the model type and get meta data associated with each attribute.
This worked for me (from an ArrayController):
fields: function() {
var doc = this.get('arrangedContent');
var fields = [];
var content = doc.content;
content.forEach(function(attr, value) {
var data = Ember.keys(attr._data);
data.forEach(function(v) {
if( typeof v === 'string' && $.inArray(v, fields) == -1) {
fields.push(v);
}
});
});
return fields;
}.property('arrangedContent')