Adding property by hand to Base model in Symfony1.4 and Doctrine - php

I have added a new field to my table Empresa so I need to change my model. For not regenerate the whole things meaning model-forms-filters I decide to add it by hand (manually) so I'm trying to add a the property to BaseSdrivingEmpresa.class.php as follow:
<?php
/**
* BaseSdrivingEmpresa
*
* This class has been auto-generated by the Doctrine ORM Framework
*
* #property integer $umbralvoz
*
* #method integer getUmbralvoz() Returns the current record's "umbralvoz" value
* #method SdrivingEmpresa setUmbralvoz() Sets the current record's "umbralvoz" value
*
* #package isecurdriving
* #subpackage model
* #author Your name here
* #version SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $
*/
abstract class BaseSdrivingEmpresa extends sfDoctrineRecord {
public function setTableDefinition() {
$this->setTableName('sdriving_empresa');
$this->hasColumn('umbralvoz', 'integer', 11, array(
'type' => 'integer',
'notnull' => false,
'default' => 60,
'length' => 11,
));
}
}
But I get this error:
500 | Internal Server Error | Doctrine_Record_UnknownPropertyException
Any time I try to get the property to display it on a template:
$id_empresa = $this->getUser()->getGuardUser()->getSfGuardUserProfile()->getIdempresa();
$this->sdriving_configuracion = Doctrine_Core::getTable('SdrivingEmpresa')->createQuery('a')->where('a.idempresa = ?', $id_empresa)->execute();
<?php echo $sdriving_configuracion[0]->SdrivingEmpresa->getUmbralvoz() ?>
Where is my error?

First of all manual edit of your Base*.class.php is not a good idea as this class is meant to be generated automatically and will be overwritten by next model build. If you want to do anything manually you should do it in direct child of BaseSdrivingEmpresa.class.php which is SdrivingEmpresa.class.php.
Second thing is that better place for such modification is SdrivingEmpresaTable.class.php. I would suggest modifying getInstance method so it looks like:
public static function getInstance()
{
$this->setColumn('umbralvoz', 'integer', 11, array(
'type' => 'integer',
'notnull' => false,
'default' => 60,
'length' => 11,
));
return Doctrine_Core::getTable('SdrivingEmpresa');
}
Finally, I think that in this case best solution is just simply modify your schema.yml file, add your column and then use command
./symfony doctrine:build-model
which will rebuild your model without touching forms, filters which you mentioned.

Related

Symfony2.8: choices_as_values doesn't work

Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceList and Symfony\Component\Form\Extension\Core\ChoiceList\LazyChoiceList have been rewritten in Symfony2.8 (details in the post below).
After that, a validation error occurred in Symfony3 and the save of the author selected in the form failed.
I attributed it to the swapping of the Choice Type keys and values.
So, before raising Symfony, I specified chouces_as_values as Type and verified whether it works.
But it didn't work and the result was similar. In other words, can we think that this is not a replacement of key values?
It may be that the rewriting of ChoiceList has failed.
Also, I would like advice on where to debug so that you can understand what is the cause.
Symfony: Unable to reverse value for property path [...]: The choice [...] does not exist or is not unique
https://symfony.com/doc/2.8/reference/forms/types/choice.html#choices-as-values
ArticleType
$ChoiceList = new StaffChoiceLoader($this->staffService, $options['login_staff']);
//$ChoiceList = new StaffChoiceList($this->staffService, $options['login_staff']);
$builder->add("author", "entity", array(
"required" => true,
"class" => "AppBundle:Staff",
"choice_loader" => $ChoiceList,
//"choice_list" => $ChoiceList,
"empty_value" => "Please select",
//Add
"choices_as_values" => true,
));
ArticleEntity
/**
* author
*
* #ORM\ManyToOne(targetEntity="Staff")
* #ORM\JoinColumn(name="author_id", referencedColumnName="id", nullable=true)
*/
protected $author;

Lithium routes with different locales

I have a i18n route in Li3 that looks like:
Router::connect('/{:locale:[a-z]{2}/{:args}', [], [
'continue' => true,
'persist' => ['locale'],
]);
This way, when a user (or a crawler) enters my site with a language prefix, the locale is used to generate every link on the site.
For SEO purposes, I need to generate URLs in other locales such as:
GET /en/profile/john-doe
Canonical URL: https://www.example.com/en/profile/john-doe
Link hreflang for es: https://www.example.com/es/profile/john-doe
Link hreflang for pt: https://www.example.com/pt/profile/john-doe
My currency approach is cloning the current request, changing the locale, removing locale from the persist array, and using $request->to('url', ['absolute' => true]);.
But I can't get rid of the locale.
Any suggestions on how to address this?
I finally solved it extending HTML helper class:
use lithium\template\helper\Html as BaseHtml;
class Html extends BaseHtml
{
/**
* Returns href lang link for a locale for the current request.
*
* #param string $locale
* #return string <link />
*/
public function getHrefLinkForLocale($locale)
{
return $this->link(
'Canonical URL for ' . $locale,
compact('locale') + $this->getRequest()->params,
[
'absolute' => true,
'rel' => 'alternate',
'type' => 'alternate',
'hreflang' => $locale,
]
);
}
}

Changing default pagination in Yii to 50

Working with yii framework and was wondering if there was a way of changing the default pagination. Currently it's at 10 elements, and I would like to make it 50.
You can set pagination by
$dataProvider = new CActiveDataProvider('model name',
array('pagination' => array(
'pageSize' => 50,
),
)
);
CPagination->$pageSize Number of items in each page. http://www.yiiframework.com/doc/api/CPagination#pageSize-detail
In yii/framework/web/CPagination.php, change
const DEFAULT_PAGE_SIZE=20;
/**
* #var string name of the GET variable storing the current page index. Defaults to 'page'.
*/
to
const DEFAULT_PAGE_SIZE=50;
/**
* #var string name of the GET variable storing the current page index. Defaults to 'page'.
*/
This will adjust the page, and pagination accordingly.

Doctrine MongoDB: Embeded documents will not be saved if hydrating data into main document

im using the hydrate function of the document manager (zend framework 2 application) for hydrating array data into a document.
Unfortunately embeded sub documents will not be updated in the databse (but main document will do).
Hydrating of the data is correct, but changes of the sub documents are not "noticed" by Unit-Of-Work.
Example:
Request 1... (creating the document)
$user = new Document\User();
$user->setName('administrator');
$address = new Document\UserAddress();
$address->setCity('cologne');
$user->setAddress($address);
// will insert new document correctly
$documentManager->persist($user);
$documentManager->flush();
Request 2... (updating existing document)
$repository = $this->documentManager->getRepository('Document\User');
$user = $repository->findOneBy(
array('name' => 'administrator')
);
$documentManager->getHydratorFactory()->hydrate(
$user,
array(
'name' => 'administrator',
'address' => array(
'city' => 'bonn' // change "cologne" to "bonn"
)
)
// note: "address" array will be correctly hydrated to a "UserAddress" document
// this will update the "User" document, but not the embedded "UserAddress" document
$documentManager->persist($user);
$documentManager->flush();
For me a little bit strange, but detaching the sub-document will cause an update
// after detaching sub object the documents will be saved correctly
// (but this cant be the way it should be...?)
$documentManager->detach($user->getUserAddress());
$documentManager->persist($user);
$documentManager->flush();
Here are the annotations:
/*
* #ODM\Document(collection="Users")
*/
class User
{
/**
* #ODM\EmbedOne(targetDocument="Document\UserAddress")
*/
protected $address;
//...
/*
* #ODM\EmbeddedDocument()
*/
class UserAddress
{
/**
* #ODM\String
*/
protected $city;
// ...
What do i wrong? Or is this a bug? Or...is the hydrate function not for "external" use?
Hope someone can help me
Regards
Norman

Using CGridView to show another model's attributes

I have the database just like this
==== Group =====
id
name
==== Member ====
id
group_id
firstname
lastname
Now I can use Member member's table attributes in group controller just by using multimodel.
As I have done multimodel so I can easily make create update delete for both models from a single view page. Now my problem is when I am going to shoew both models in Group's admin view file I have to show both files in CGridView to show in a Grid. But my problem is in CGridView only first model can be seen.I want the second models to be shown on the CGridView. So how to do that?
I think you need to combine models using the Relational Active Record.
In the process of self learning I'm following, I hope I will shortly have an example to post here...
EDIT finally, I worked out an example. I've (maybe) found a bug in Yii, so what is an easy task, required more time than necessary...
I have two models, User e Persona, obtained from gii, previously unrelated. Then I add a Persona to User as optional attribute: in User.php
/**
* #return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'persona' => array(self::HAS_ONE,'Persona','id')
);
}
then the model for User automatically display selected fields from Persona, when bound to CGridView:
<hr><?php
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider' => new CActiveDataProvider('User'),
'columns' => array(
'username',
'password',
'email',
'persona.indirizzo'
),
));
?>
The bug I found (perhaps, need to investigate more): my Persona model has an attribute with an accented character in name, and if I use that instead I get an error: i.e. if
'columns' => array(
'username',
'password',
'email',
'persona.identità'
),
then the page can't be instanced:
The column must be specified in the format of "Name:Type:Label", where "Type" and "Label" are optional.
/home/carlo/public/yii-1.1.8.r3324/framework/zii/widgets/grid/CGridView.php(332)
320 foreach($this->columns as $column)
321 $column->init();
322 }
323
324 /**
325 * Creates a {#link CDataColumn} based on a shortcut column specification string.
326 * #param string $text the column specification string
327 * #return CDataColumn the column instance
328 */
329 protected function createDataColumn($text)
330 {
331 if(!preg_match('/^([\w\.]+)(:(\w*))?(:(.*))?$/',$text,$matches))
332 throw new CException(Yii::t('zii','The column must be specified in the format of "Name:Type:Label", where "Type" and "Label" are optional.'));
333 $column=new CDataColumn($this);
334 $column->name=$matches[1];
I think it's the regular expression that mismatch...
If you add getters for groupId and groupName to the Member model you can easily display the gridview for members and include their group data. It's not an extremely clean solution, but it's the easiest.
Define some function like 'getGroupNameById' in group model then call it as follows
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$dataProvider, //for members model
'columns'=>array(
'id',
'firstName',
'lastName',
array(
'name'=>'groupName'
'value'=>'getGroupNameById($data->group_id)',
//$data is members row accessible in gridview
),
),
));
Check this post for more details CGridView-Render-Customized-Complex-DataColumns

Categories