Symfony (Doctrine) : accessing nestedset root element - symfony1

I'm trying to get the root element of a nested set tree.
Here is the scenario:
I have a category table wich act as a nested set
Category:
actAs:
NestedSet:
hasManyRoots: true
rootColumnName: root_id
columns:
name: { type: string(255), notnull: true, unique: false }
and a Video table
Video:
actAs: { Timestampable: ~ }
columns:
name: { type: string(255), notnull: true }
...
relations:
Categories:
class: Category
refClass: CategoryVideo
local: video_id
foreign: category_id
foreignAlias: Videos
Here is my problem: let's say a video is in the "Action" category and "Action" is a child of "Film", when I call getCategories() from my Video object, I only have the "Action" category, but I want to display "Film" (the Root category), I tryed something like
getAncestors()
with no luck.
Could someone please tell me how to get the root element of the nested set?
Thanks

Try this:
$this->categories = Doctrine::getTable('Categories')->getTree();
$q = Doctrine_core::getTable('Categories')->createQuery('q');
$q->leftJoin('q.Translation qt')->
addOrderBy('sort ASC')->
addOrderBy('qt.cat_name ASC');
$this->categories->setBaseQuery($q);
foreach($categories->fetchRoots() as $root)
{
$options = array(
'root_id' => $root->getCategoryId()
);
foreach($categories->fetchTree($options) as $node)
{
echo $node->getName();
}
}
Regards,
Max

Related

Adding multiple records to a relations table with symfony

I have setup 3 tables in symfony:
A flipbook table, A Skills table, and a relations table, to connect each skill id with each flipbook id.
WHen I built the model, symfony constructed everything correctly, and by default gave a drop-down menu for the skills, which had all skills from the skills table as options. You can select an option and it creates the appropriate relationships.
This is working (sort of). When you submit the form, it does not add the skill_id to the record. It just adds the auto-increment id to the skills relations table and neither the flipbook_id or skill_id. Aaaaaand, if you click more than one checkbox, you get this nice message:
invalid parameter number number of bound variables does not match number of tokens
Whaaaat does that mean? This has got to be a schema issue eh?
How about some code? yes.please.
Schema:
Flipbook:
tableName: flipbook
inheritance:
extends: SvaGeneric
type: concrete
columns:
title: { type: string(255) }
career_associations: { type: clob }
skills: { type: string(255) }
skills_associations: { type: clob }
program: { type: string(255) }
program_associations: { type: clob }
draft_id: { type: integer(10) }
FlipbookSkills:
tableName: flipbook_skills
columns:
title: { type: string(255) }
relations:
Flipbook:
foreignAlias: flipbook_skills
alias: skills
local: title
onDelete: SET NULL
FlipbookSkillRelations:
tableName: flipbook_skill_relations
actAs:
SoftDelete: ~
options:
columns:
flipbook_id: { type: integer(10), notnull: false }
skill_id: { type: integer(10), notnull: false }
relations:
Flipbook:
foreignAlias: flipbook_skills_flipbook
alias: flipbook
local: flipbook_id
onDelete: CASCADE
FlipbookSkills:
foreignAlias: flipbook_skills_skills
alias: flipbookskills
local: skill_id
onDelete: CASCADE
FlipbookSkillsRelationsForm.class.php:
$this->widgetSchema['flipbook_id'] = new sfWidgetFormInputText(array(), array('class' => 'text size-500'));
$this->widgetSchema['skill_id'] = new sfWidgetFormSelectCheckbox(array('choices' => "**WHAT GOES HERE??**"), array('class' => 'text size-500'));
$useFields = array(
'flipbook_id',
'skill_id',
);
$this->useFields($useFields);
Let me know if I should provide further code or explanation.
Here is the FlipbookSkillsTable.class generated in the model:
<?php
/**
* FlipbookSkillsTable
*
* This class has been auto-generated by the Doctrine ORM Framework
*/
class FlipbookSkillsTable extends Doctrine_Table
{
/**
* Returns an instance of this class.
*
* #return object FlipbookSkillsTable
*/
public static function getInstance()
{
return Doctrine_Core::getTable('FlipbookSkills');
}
public function retrieveForFilter()
{
$res = $this->createQuery('s')
->select('s.id, s.name')
->orderBy('s.name ASC')
->execute(array(), Doctrine_Core::HYDRATE_NONE);
// if you want an empty line
$rets = array('' => '');
foreach ($res as $ret)
{
$rets[$ret[0]] = $ret[1];
}
return $rets;
}
public function getAllFlipbookSkills() {
$allSkills = Doctrine_Query::create()
->from('FlipbookSkills')
->orderBy('title ASC')
->execute();
return $allSkills;
}
}
UPDATE
I believe the issue is it is trying to bind the multiple values in the same record. It should make a new record for each skill chosen, like this:
id flipbook_id skill_id
1 2 1
2 2 2
3 2 3
SO I still don't have the schema nailed down correctly, otherwise Doctrine would know how to handle the data correct? Should I explicitly put one to many relationship?
Also, when submitted, it is only adding the flipbook_id value to the record. The skill_id record is 0
FLipbookRelationsForm:
class FlipbookSkillRelationsForm extends BaseFlipbookSkillRelationsForm
{
public function configure()
{
$this->widgetSchema['skill_id'] =
new sfWidgetFormDoctrineChoice(array('model' =>
$this->getRelatedModelName('flipbookskills'),
'expanded' => true, 'multiple' => true, 'add_empty' => false));
$useFields = array(
'flipbook_id',
'skill_id',
);
$this->useFields($useFields);
}
}
Multiple issues (maybe this post can help: Embedded forms in symfony 1.4 not saving propperly)
Your n-m relations doesn't look well defined. Your entities should looks like:
FlipbookSkill:
tableName: flipbook_skill
columns:
title: { type: string(255) }
relations:
Flipbooks:
class: Flipbook
refClass: FlipbookSkillRelation
local: skill_id
foreign: flipbook_id
/* Not foreignAlias and onDelete behaviour defined */
Flipbook:
tableName: flipbook
inheritance:
extends: SvaGeneric
type: concrete
columns:
title: { type: string(255) }
career_associations: { type: clob }
skills: { type: string(255) } # why this????
skills_associations: { type: clob } # why this????
program: { type: string(255) }
program_associations: { type: clob }
draft_id: { type: integer(10) }
relations:
Skills:
class: FlipbookSkill
refClass: FlipbookSkillRelation
local: flipbook_id
foreign: skill_id
FlipbookSkillRelation:
tableName: flipbook_skill_relation
actAs:
SoftDelete: ~
options:
columns:
flipbook_id: { type: integer(10), notnull: false }
skill_id: { type: integer(10), notnull: false }
relations:
Flipbook:
foreignAlias: FlipbookSkills
local: flipbook_id
foreign: id
onDelete: CASCADE
FlipbookSkill:
foreignAlias: FlipbookSkills
local: skill_id
foreign: id
onDelete: CASCADE
Then, you methods/join allowed are:
$flipbookObject->getSkills(); Because flipbook entity n-m relation name "Skills", wich returns a FlipbookSkill DoctrineCollection. Or in query ('f.innerJoin Skills s')
$flipbookObject->getFlipbookSkills(); Because flipbookSkillRelation 1-n foreignAlias name, but probably you will never use this (because you don't really care about relations inself, instead you care about related skills).
... etc
If you have a well defined schema.yml, then your forms should work properly.
Plus:
why are you using and text input widget for an id field (flipbook_id) ????
And why are you using a sfWidgetFormSelectCheckbox if you are working with doctrine entities? You should use sfWidgetFormDoctrineChoice like the BaseEntity defines.
I hope this can help you.
Where are your validators ? Symfony forms don't work properly with missing validators or inappropriate ones. If your validator accept 1-1 relationship, and you send multiple values, it won't work.
Try this :
$this->validatorSchema->setOption('allow_extra_fields' , true);
$this->validatorSchema->setOption('filter_extra_fields' , false);
If your error disappear, then you have a problem with validators. Otherwise you can try to use a the sfEmbedded forms, you render an sfForm, and add multiple time your FlipbooSkillForm with selects. If i remeber well there is some tutorials showing how to add them in js.
http://nacho-martin.com/dynamic-embedded-forms-in-symfony

How to query and return the stored id and not the joined description

Perhaps an example would best describe my problem:
Schema:
Referral:
actAs: { timestampable: ~ }
columns:
id: { type: integer, primary: true, notnull: true, autoincrement: true, unique: true }
other_stuff: { type: string }
reasonCode: { type: integer }
relations:
ReasonCode: { local: reasonCode, foreign: id, foreignAlias: ReasonCodes }
ReasonCode:
columns:
id: { type: integer, primary: true, notnull: true, autoincrement: true, unique: true }
description: { type: string }
Query (referralTable.class.php):
public function getObjectByReferralId($id){
$q = Doctrine_Query::create()
->select('*')
->from('referral_submissions')
->where('referral_id=?', $id)
->fetchOne();
return $q;
}
Call in template:
<?php
$id = <source of id>;
echo Doctrine_Core::getTable('referral')->getObjectByReferralId($id)->getReasonCode();
?>
The above call in the template to get the reasoncode returns the "description" stored in the ReasonCode table, not the stored id in the Referral table. I need the actual id, not the joined description. What am I missing?
It's confusing because you named your foreign key with the name of your relation. So when you think you are getting the key, you fetch the relation. And I guess Doctrine do not retrieve the primary key since there is only one field in your ReasonCode table, so it returns the description field.
Try with :
Doctrine_Core::getTable('referral')
->getObjectByReferralId($id)
->get('reasonCode');
By the way, you also can retrieve the id using the relation:
Doctrine_Core::getTable('referral')
->getObjectByReferralId($id)
->getReasonCode()
->getId();
I think you should define your foreign key like : reason_code_id instead of reason_code. Then your schema will become:
Referral:
actAs: { timestampable: ~ }
columns:
id: { type: integer, primary: true, notnull: true, autoincrement: true, unique: true }
other_stuff: { type: string }
reasonCode_id: { type: integer }
relations:
ReasonCode: { local: reasonCode_id, foreign: id, foreignAlias: ReasonCodes }
And you will be able to retrieve the id using:
Doctrine_Core::getTable('referral')
->getObjectByReferralId($id)
->getReasonCodeId();

foreign key never save with embed relation

I take many hours to find a solution to save the foreign key in the mother table.
I'm trying to use embed relation with symfony 1.4 (i have ahDoctrineEasyEmbeddedRelationsPlugin too).
When i read the symfony documentation here
http://www.symfony-project.org/more-with-symfony/1_4/en/06-Advanced-Forms
the schema is :
Product:
columns:
name: { type: string(255), notnull: true }
price: { type: decimal, notnull: true }
ProductPhoto:
columns:
product_id: { type: integer }
filename: { type: string(255) }
caption: { type: string(255), notnull: true }
relations:
Product:
alias: Product
foreignType: many
foreignAlias: Photos
onDelete: cascade
the embedRelation looks like:
// lib/form/doctrine/ProductForm.class.php
public function configure()
{
// ...
$this->embedRelation('Photos');
}
In my case i can't do otherway, it's the contrary, the product have the relation keys, i have something like that:
Product:
columns:
name: { type: string(255), notnull: true }
price: { type: decimal, notnull: true }
photoid: { type: integer }
ownerid: { type: integer }
relations:
Photo:
local: photoid
foreign: id
type: one
Owner:
local: ownerid
foreign: id
type: one
Photo:
columns:
id : { type: integer }
filename: { type: string(255) }
caption: { type: string(255), notnull: true }
owner:
columns:
id : { type: integer }
firstname: { type: string(255) }
lastname: { type: string(255), notnull: true }
and the embedRelation:
// lib/form/doctrine/ProductForm.class.php
public function configure()
{
// ...
$this->embedRelation('Photo');
$this->embedRelation('Owner');
}
And there are not widget related to the product like name or price to update in the form but only informations coming from photo and owner table.
When i save the new form, photo and owner object are save in the table, and ids are created with sequences. The problem is that Product is never update. photoid and ownerid still stay to null.
It's like embedded form Photo and Owner are save after the root form.
Is it possible to use embedrelation in that case?
If then what is the correct way to save the foreign keys in Product table when the root form is save in the processForm?
What's the trick, thx for help.
In PhotoForm.class.php use:
$this->useFields(array('filename', 'caption'));
And read the documentation

properties of a n:m relation in doctrine

Hy guys
I've got the following schema for my objects:
Product:
columns:
name: { type: string(255) }
Basket:
columns:
current_status: { type: integer }
relations:
Products: { class: Product, refClass: BasketProducts, onDelete: CASCADE }
BasketProducts:
columns:
product_id: { type: integer, primary: true }
basket_id: { type: integer, primary: true }
quantity: { type: integer(4) }
relations:
Product: { local: product_id, onDelete: CASCADE }
Basket: { local: basket_id, onDelete: CASCADE }
Now in the frontend I try to show the users basket, getting the products by
foreach($basket->getProducts() as $product) {
echo $product->getId();
echo $product->getName();
}
The question now, how can i access the quantity field from the BasketProducts?
You will need to query the middle table directly in order to do this.
A good way to do this, is to add a function in your Basket.class.php that will retrieve the data you need based on a BasketID.
You could also create the function in your BasketTable.class.php if you'd like to include the data when fetching a particular basket (ie. getBasketWithProductQuantities())
I don't have any Doctrine code handy at this time.

Symfony Doctrine Schema Segmentation Fault

I'm setting up my first symfony project, and am having trouble with the schema. I'm not sure if I'm going about it the right way.
I'm having a problem with two of my classes. I have Clients, which can have many Contacts, one of the contacts needs to be selected as the invoice contact. This is my schema:
NativeClient:
actAs: { Timestampable: ~ }
columns:
name: { type: string(255), notnull: true }
address: { type: string(255) }
postcode: { type: string(9) }
tel: { type: string(50) }
fax: { type: string(50) }
website: { type: string(255) }
client_status_id: { type: integer, notnull: true, default: 0 }
priority: { type: boolean, notnull: true, default: 0 }
invoice_contact_id: { type: integer }
invoice_method_id: { type: integer }
relations:
NativeContact: { local: invoice_contact_id, foreign: id, foreignAlias: NativeInvoiceContacts }
NativeClientStatus: { local: client_status_id, foreign: id, foreignAlias: NativeContacts }
NativeInvoiceMethod: { local: invoice_method_id, foreign: id, foreignAlias: NativeClientStatuses }
NativeContact:
actAs: { Timestampable: ~ }
columns:
client_id: { type: integer, notnull: true }
name: { type: string(255), notnull: true }
position: { type: string(255) }
tel: { type: string(50), notnull: true }
mobile: { type: string(50) }
email: { type: string(255) }
relations:
NativeClient: { onDelete: CASCADE, local: client_id, foreign: id, foreignAlias: NativeClients }
NativeClientStatus:
actAs: { Timestampable: ~ }
columns:
name: { type: string(255), notnull: true }
NativeInvoiceMethod:
actAs: { Timestampable: ~ }
columns:
name: { type: string(255), notnull: true }
If i remove the following line (and associated fixtures) it works, otherwise I get a segmentation fault.
NativeContact: { local: invoice_contact_id, foreign: id, foreignAlias: NativeInvoiceContacts }
Could it be getting in a loop? Trying to reference the Client and the Contact over and over? Any help would be greatly appreciated! Thanks!
Darren
Old question I know, but heres a follow up solution. Sometimes Doctrine will throw this error for seemingly no reason whatsoever. Im sure there is an underlying reason, but we dont all have time to debug the entire Doctrine source.
Try specifying --env=[your env], and it may just work - has for me.
Darren, it seems like you're defining the relationship at both ends while using conflicting criteria...
NativeContact: { local: invoice_contact_id, foreign: id, foreignAlias: NativeInvoiceContacts }
...relationship is between "invoice_contact_id" and undeclared "id" PK in NativeContact.
NativeClient: { onDelete: CASCADE, local: client_id, foreign: id, foreignAlias: NativeClients }
... same relationship is between "client_id" and undeclared "id" PK in NativeClient.
I personally only define these in one end and let Doctrine handle the rest, but it depends on what you're trying to achieve here. If ONE client HAS MANY contacts, you could drop the second declaration and define the relationship in the clients table only and add "type: many, foreignType: one" to state that it's a one-to-many relationship.

Resources