sfDoctrineGuard - how to ALWAYS join sfGuardProfile to sfGuardUser - join

I want to make it so that anytime the db is queried for an sfGuardUserProfile it is autmoatically joined and hydrated with its related sfGuardUser.
If i was using Propel 1.2 i would normally override the doSelectStmt method of the sfGuardUserProfilePeer class to inspect the Criteria and modify it as necessary as well as modifying the hydrate method of the sfGuardUserProfile class. Im not sure how to go about doing this in Doctrine though.

You could use Event Listeners. Read more about them in the doctrine documentation: Event Listeners
In symfony 1.4 sfGuardUser can be modified. It's by default in lib/model/doctrine/sfDoctrineGuardPLugin/sfGuardUser.class.php. You can add following preDqlSelect() method to modify the query. Note that it's not tested.
class sfGuardUser extends PluginsfGuardUser
{
public function preDqlSelect($event)
{
$params = $event->getParams();
$query = $event->getQuery();
$alias = $params['alias'] . '.Profile';
if ((!$query->isSubquery() || ($query->isSubquery() && $query->contains(' ' . $params['alias'] . ' '))) && !$query->contains($alias))
{
$query->innerJoin($alias);
}
}
}
To make it working you need to have DQL callbacks turned on. You can do it in your ProjectConfiguration class:
class ProjectConfiguration extends sfProjectConfiguration
{
public function configureDoctrine(Doctrine_Manager $manager)
{
$manager->setAttribute(Doctrine_Core::ATTR_USE_DQL_CALLBACKS, true);
}
}

Although I agree with Coronatus, I think what you're looking to do can be achieved with:
http://www.symfony-project.org/plugins/sfGuardPlugin
See "Customize the sfGuardUser model".
Basically, the profile needs to be called "sf_guard_user_profile" and the relation set up, and then you should be able to use:
$this->getUser()->getGuardUser()->getProfile();
I think the right profile model name is needed for some config file purposes but I may be wrong.

Related

typeorm table name specified more than once

I have the next query:
const foundDeal: any = await dealRepository.findOne({
where: { id: dealId },
relations: ['negotiationPointsDeals', 'chosenInventoryToSubtractQuantity',
'chosenInventoryToSubtractQuantity.inventoryItemType',
'chosenInventoryToSubtractQuantity.inventoryItemType.quality', 'negotiationPointsDeals.negotiationPointsTemplate',
'chosenInventoryToSubtractQuantity.addressOfOriginId', 'chosenInventoryToSubtractQuantity.currentLocationAddress',
'chosenInventoryToSubtractQuantity.labAttestationDocs',
'chosenInventoryToSubtractQuantity.labAttestationDocs.storage',
'chosenInventoryToSubtractQuantity.proveDocuments', 'chosenInventoryToSubtractQuantity.proveDocuments.storage',
'chosenInventoryToSubtractQuantity.inventoryItemSavedFields', 'chosenInventoryToSubtractQuantity.inventoryItemSavedFields.proveDocuments',
'chosenInventoryToSubtractQuantity.inventoryItemSavedFields.proveDocuments.storage',
'sellerBroker', 'sellerBroker.users',
'seller', 'seller.users',
'buyerBroker', 'buyerBroker.users',
'buyer', 'buyer.users',
'order', 'order.inventory', 'order.inventory.inventoryItemType',
'order.inventory.inventoryItemType.quality',
'order.inventory.addressOfOriginId', 'order.inventory.currentLocationAddress',
'order.inventory.inventoryItemSavedFields', 'order.inventory.inventoryItemSavedFields.proveDocuments',
'order.inventory.inventoryItemSavedFields.proveDocuments.storage',
'order.inventory.labAttestationDocs', 'order.inventory.labAttestationDocs.storage',
// 'postTradeProcessingDeal', 'postTradeProcessingDeal.postTradeProcessingStepsDeal',
'order.inventory.proveDocuments',
'order.inventory.proveDocuments.storage',
'negotiationPointsDeals.negotiationPointsTemplate.negotiationPointsTemplateChoices',
'postTradeProcessing',
],
});
So, the error is next:
error: table name "Deal__chosenInventoryToSubtractQuantity_Deal__chosenInventoryTo" specified more than once.
But I can't see any doubles in query.
I ran into this issue when switching to start using the snake case naming strategy.
I think somehow the aliases that TypeORM generates by default do not collide if you "re-join" to existing eagerly-loaded relations.
However, under the new naming strategy it threw an error if I tried to add in a relation that was already eagerly loaded.
The solution for me was to find and eliminate places where I was doing relations: ["foo"] in a query where foo was already eagerly loaded by the entity.
The issue is documented in this TypeORM issue.
After some digging, I realized this error is due to TypeORM creating some kind of variable when using eager loading that is longer than Postgres limit for names.
For example, if you are eager loading products with customer, typeorm will create something along the lines of customer_products, connecting the two. If that name is longer than 63 bytes (Postgres limit) the query will crash.
Basically, it happens when your variable names are too long or there's too much nesting. Make your entity names shorter and it will work. Otherwise, you could join the tables manually using queryBuilder and assign aliases for them.
It looks like you are using Nestjs, typeorm, and the snakeNamingStrategy as well, so I'll show how I fixed this with my system. I use the SnakeNamingStrategy for Typeorm which might be creating more issues as well. Instead of removing it, I extended it and wrote an overwriting function for eager-loaded aliases.
Here is my solution:
// short-snake-naming.strategy.ts
import { SnakeNamingStrategy } from "typeorm-naming-strategies";
import { NamingStrategyInterface } from "typeorm";
export class ShortSnakeNamingStrategy
extends SnakeNamingStrategy
implements NamingStrategyInterface
{
eagerJoinRelationAlias(alias: string, propertyPath: string): string {
return `${alias.replace(
/[a-zA-Z]+(_[a-zA-Z]+)*/g,
(w) => `${w[0]}_`
)}_${propertyPath}`;
}
}
// read-database.configuration.ts
import { TypeOrmModuleOptions, TypeOrmOptionsFactory } from "#nestjs/typeorm";
import { SnakeNamingStrategy } from "typeorm-naming-strategies";
import { ShortSnakeNamingStrategy } from "./short-snake-naming.strategy";
export class ReadDatabaseConfiguration implements TypeOrmOptionsFactory {
createTypeOrmOptions(): TypeOrmModuleOptions | Promise<TypeOrmModuleOptions> {
return {
name: "read",
type: "postgres",
...
namingStrategy: new ShortSnakeNamingStrategy(),
};
}
}
The ShortSnakeNamingStrategy Class takes each eager-loaded relationship and shortens its name from Product__change_log___auth_user___roles__permissions to P_____c____a___r__permissions
So far this has generated no collisions and kept it below the 63 character max index length.

Inject ServiceLocator in Validator

How can I inject the "normal" ServiceManger into a custom validator used for REST calls (Use without Form). ZF 2.2.7 Used to inject an instance of external library into an validator.
I have tried the following, and nothing works:
Inject it with the ValidationPluginManager, service not found
Inject it via factory, factory will not be loaded in validator chain
Inject it via validator options, not possible because the "ServiceManager" is an instance of ValidationPluginManager with the asme result as mentioned in #1
Is there any concept how to solve this problem, or do i have to give up and link all libraries statically?
Not tested this and have never done with with ValidationPluginManager but works with ControllerManager, FormElementManager etc
// GetServiceLocator call should return Instance of ServiceManager
// Then retrieve the service, Yay!
$validationPluginManager->getServiceLocator()->get('SomeService')
There has been a discussion on github about a somewhat similar problem here. They suggested to use Zend\Form\FormAbstractServiceFactory and tinker with dependencies there (weierophinney before closing the topic).
In your post you mention you are not using a form did you mean you are not using the form in a classic kind of way or are you bypassing the whole form in particular?
It simply seems off to me to use a validator if there isn't a form present. Could you elaborate more on that?
EDIT: To my understanding zf2 requires that your input filters have form elements like 'inputs' etc. You did not post any code and I simply do not know if/or your able to bypass this somehow. I still do not understand why you'd still want to use validators in combination of input filters. I would simply skip the input filters and write the custom validator.
My personal preferences is to write factories instead of anonymous functions within module.php files. But this also could work the anonymous function way.
I would then simply resolve the dependencies within the customValidatorFactory and get the factory within my controller or whatever place I would need it.
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use CustomValidator;
class CustomValidatorFactory implements FactoryInterface
{
/**
* Create Service Factory
*
* #param ServiceLocatorInterface $serviceLocator
*/
public function createService(ServiceLocatorInterface $serviceLocator)
{
$sm = $serviceLocator->getServiceLocator();
$customService = $sm->get('Application\Service\Geocoding');
$validator= new CustomValidator();
$validator->setCustomService($service);
return $validator;
}
}
// CustomValidator.php
class CustomValidator extends Zend\Validator\AbstractValidator
{
public function setCustomService($service)
{
$this->service = $service;
}
public function isValid($value)
{
$customService = $this->service;
if ($customService->customMethod() == true) {
return true;
}
return false;
}
}
//module-config.php
'service_manager' => array(
'factories' => array(
'custom\ValidatorFactory' => 'Namespace\To\CustomValidatorFactory',
),
),
//yourController or whatever.php will require access to the service manager
$customValidation = $sm->get('custom\ValidatorFactory');
// should return true or false now
$state = $customValidation->isValid($someValue);

ZfcUser extend User class with additional get function

I'm new to the Zend2 Framework and have installed ZfcUser with an added database column which I would like to access through:
<?php echo $this->zfcUserIdentity()->getOrg(); ?>
Any help on extending the User Class to access this variable would be greatly appreciated.
Ryan
Extend the ZfcUser user entity to include your new property and accessors. You'll need to do this in your own module, or if you're using the skeleton app, in the Application module will work.
<?php
namespace Application\Entity;
use ZfcUser\Entity\User;
class MyUser extends User
{
protected $org;
public function setOrg($org)
{
$this->org = $org;
return $this;
}
public function getOrg()
{
return $this->org;
}
}
Copy vendor/ZfcUser/config/zfcuser.global.php.dist to /config/autoload/zfcuser.global.php
Open the file you just copied in your editor, and find the section below
/**
* User Model Entity Class
*
* Name of Entity class to use. Useful for using your own entity class
* instead of the default one provided. Default is ZfcUser\Entity\User.
* The entity class should implement ZfcUser\Entity\UserInterface
*/
//'user_entity_class' => 'ZfcUser\Entity\User',
uncomment the line, and replace the value with the fully qualified class name of the MyUser entity you created
'user_entity_class' => 'Application\Entity\MyUser',
Then try accessing your method
<?php echo $this->zfcUserIdentity()->getOrg(); ?>

my own id in GORM

I tried to change the standard 'id' in grails:
calls Book {
String id
String title
static mapping {
id generator:'assigned'
}
}
unfortunately, I soon noticed that this breaks my bootstrap. Instead of
new Book (id:'some ISBN', title:'great book').save(flush:true, failOnError:true)
I had to use
def b = new Book(title:'great book')
b.id = 'some ISBN'
b.save(flush:true, failOnError:true)
otherwise I get an 'ids for this class must be manually assigned before calling save()' error.
but that's ok so far.
I then encountered the same problem in the save action of my bookController. But this time, the workaround didn't do the trick.
Any suggestions?
I known, I can rename the id, but then I will have to change all scaffolded views...
That's a feature of databinding. You don't want submitted data to be able to change managed fields like id and version, so the Map constructor that you're using binds all available properties except those two (it also ignores any value for class, metaClass, and a few others).
So there's a bit of a mismatch here since the value isn't managed by Hibernate/GORM but by you. As you saw the workaround is that you need to create the object in two steps instead of just one.
I can't replicate this problem (used Grails 2.0.RC1). I think it might be as simple as a missing equal sign on your static mapping = { (you just have static mapping {)
Here's the code for a domain object:
class Book {
String id
String name
static mapping = {
id generator:'assigned'
}
}
And inside BootStrap.groovy:
def init = { servletContext ->
new Book(name:"test",id:"123abc").save(failOnError:true)
}
And it works fine for me. I see the id as 123abc.
You need to set the bindable constraint to true for your id prop, e.g.
class Employee {
Long id
String name
static constraints = {
id bindable: true
}
}

How to serialize swfWidgetformChoice multiple options to single field in database in symfony 1.4

I am using symfony 1.4 in a project and i need to store multiple
options in a single field .
I am using sfWidgetFormChoice Set up loooks like this:
$status = Doctrine::getTable('Profile')->getStatuses();
$this->widgetSchema['status'] = new sfWidgetFormChoice(array(
'expanded'=>true,
'choices'=>$status,
'multiple'=>true
));
$this->validatorSchema['status'] = new sfValidatorChoice(
array('choices'=>array_keys($status),
'multiple'=>true, 'required'=>false
));
In my model I use the following to serialise multiple options into
single field.
public function setStatus($data) {
$data = serialize($data);
$this->_set('status', $data);
}
?>
Which works like a charm and save data as:
a:2:{i:0;s:7:"relaxed";i:1;s:8:"Inactive";}
However I'm am having difficulty retrieving the serialised string as
an array using the following in my model:
public function getStatus() {
return unserialize($this->status);
}
Am I missing something here? I get the following error:
Notice: Undefined property: Profile::$status in C:.../.././
Which doesnt make sense to me..
Doctrine has the "Array" type, which will automatically serialize/deserialize your array for you. Just specify the type of status as "Array" in your schema.yml file.
public function getStatus() {
return unserialize($this->_get('status'));
}
However, you can use a solution mentioned by #greg0ire

Resources