Laravel Eloquent: How to pass connection name to relationship model - eloquent

I have two models, one mongo model extending Jenssegers\Model and other sql model extending Illuminate\Model. This sql model doesn't have connection name defined as we're having multiple database connectivity have same table in each database.
Mongo Model Comment.php
<?php
namespace App\Models\Mongo;
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
class Comment extends Eloquent
{
/** #var string Mongo Connection Name */
protected $connection = 'mongodb';
/** #var string Mongo Collection Name */
protected $collection = 'comments';
/** #var bool Enable/Disable Timestamp */
public $timestamps = true;
/** #var date Date format */
protected $dateFormat = 'Y-m-d H:i:s';
public function userProfile()
{
return $this->belongsTo('\\App\\Models\\Sql\\UserDefaultProfile', 'created_by', 'user_code');
}
}
Sql Model UserProfile.php
<?php
namespace App\Models\Sql;
use Illuminate\Database\Eloquent\Model;
use Jenssegers\Mongodb\Eloquent\HybridRelations;
class UserDefaultProfile extends Model
{
use HybridRelations;
/** #var string Table Name */
protected $table = 'user_default_profile';
/** #var bool Enable/Disable Timestamp */
public $timestamps = false;
}
I have multiple database connection add to Capsule
try {
$getDatabaseList = StoreDatabaseCredential::all();
} catch (Exception $exception) {
}
foreach ($getDatabaseList as $database) {
if (strtolower($database->database_type) == 'mysql') {
$db->addConnection([
'driver' => 'mysql',
'host' => $database->database_router_read_host,
'port' => $database->database_router_read_port,
'database' => $database->database_name,
'username' => $database->database_user,
'password' => $database->database_password,
'charset' => 'utf8',
'collation' => 'utf8_general_ci',
'prefix' => '',
], $database->connection_name);
}
}
so multiple database connection are available
Now problem is when I called the eloquent with relation, am getting Database [Default] not configured. I'm getting this error because UserProfile Model doesn't have any connection defined. So, please someone who can tell how to pass connection name to relation model.
try {
$comments = Comment::where([
'in_reply_to_content_id' => $contentId,
'super_store_id' => $superStoreId,
'is_deleted' => 0
])->with([
'userProfile' => function ($query) use ($dbConnectionName) {
$query->select('id', 'user_code', 'mobile', 'name', 'profile_pic_url');
}
])->skip($offset)->take($itemsPerPage)->orderBy('created_at', 'desc')->get();
Utils::printData($contentComments);
exit();
} catch (\Throwable $exception) {
Utils::printData($exception->getMessage());
exit();
}
so, is it possible to do something like this with relation
with([
'userProfile' => function ($query) use ($dbConnectionName) {
$query->setConnection($dbConnectionName)->select(
'id', 'user_code', 'mobile', 'name', 'profile_pic_url'
);
}
])->skip($offset)->take($itemsPerPage)->orderBy('created_at', 'desc')->get();

You can extend the base Model class for your UserProfile model, override getConnectionName method and get connection name from a static class variable that you set with static method
for example:
use Illuminate\Database\Eloquent\Model;
class RelationWithChangingConnection extends Model
{
static $connectionName;
static public function setConnectionNameForRelation($connectionName)
{
static::$connectionName = $connectionName;
}
public function getConnectionName()
{
$this->connection = static::$connectionName;
return parent::getConnectionName();
}
}
class UserDefaultProfile extends RelationWithChangingConnection
{
//...
}
and then
with([
'userProfile' => function ($query) use ($dbConnectionName) {
UserDefaultProfile::setConnectionNameForRelation($dbConnectionName);
$query->setConnection($dbConnectionName)->select(
'id', 'user_code', 'mobile', 'name', 'profile_pic_url'
);
}
])...
However, this looks ugly.
Also you can switch database connections through switching configuration files as suggested here
UPD: Here I came across another possible solution, but haven't checked it yet - you can write your relation subquery like this:
...
->with([
'userProfile' => function ($query) use ($dbConnectionName) {
$query->from('[yourdatabase].[dbtable]')->select('id','user_code', 'mobile', 'name', 'profile_pic_url');
}
...
and it will connect to database and db table that you set.

Yes, its possible to set connection name if your model extends to Illuminate\Database\Eloquent\Model;
$profile = UserDefaultProfile::setConnection('your_connection_name_goes_here')->where('','')->select('');

Related

zend 3, graphQL - how to create model instance using factory in Types class

Currently I have such Types.php:
namespace Application\GraphQL;
use Application\GraphQL\Type\NodeType;
use Application\GraphQL\Type\QueryType;
use GraphQL\Type\Definition\NonNull;
use GraphQL\Type\Definition\Type;
use Application\GraphQL\Type\PersonType;
/**
* Class Types
*
* Acts as a registry and factory for your types.
*
* As simplistic as possible for the sake of clarity of this example.
* Your own may be more dynamic (or even code-generated).
*
* #package GraphQL\Examples\Blog
*/
class Types
{
private static $query;
private static $person;
private static $node;
public static function person()
{
return self::$person ?: (self::$person = new PersonType());
}
/**
* #return QueryType
*/
public static function query()
{
return self::$query ?: (self::$query = new QueryType());
}
/**
* #return NodeType
*/
public static function node()
{
return self::$node ?: (self::$node = new NodeType());
}
/**
* #return \GraphQL\Type\Definition\IDType
*/
public static function id()
{
return Type::id();
}
/**
* #return \GraphQL\Type\Definition\StringType
*/
public static function string()
{
return Type::string();
}
/**
* #param Type $type
* #return NonNull
*/
public static function nonNull($type)
{
return new NonNull($type);
}
}
In query() function it creates QueryType instance. I added to QueryType constructor PersonTable model class so that it could query persons from database.
QueryType.php
public function __construct(PersonTable $table)
{
$config = [
'name' => 'Query',
'fields' => [
'person' => [
'type' => Types::person(),
'description' => 'Returns person by id',
'args' => [
'id' => Types::nonNull(Types::id())
]
],
'hello' => Type::string()
],
'resolveField' => function($val, $args, $context, ResolveInfo $info) {
return $this->{$info->fieldName}($val, $args, $context, $info);
}
];
$this->table = $table;
parent::__construct($config);
}
I have set up factories in module\Application\src\Module.php:
/**
* #link http://github.com/zendframework/ZendSkeletonApplication for the canonical source repository
* #copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* #license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Application;
use Application\Model\PersonTable;
use Application\Model\Person;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
class Module
{
const VERSION = '3.0.2dev';
public function getConfig()
{
return include __DIR__ . '/../config/module.config.php';
}
// Add this method:
public function getServiceConfig()
{
return array(
'factories' => array(
'Application\Model\PersonTable' => function($sm) {
$tableGateway = $sm->get('PersonTableGateway');
$table = new PersonTable($tableGateway);
return $table;
},
'PersonTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Person());
return new TableGateway('album', $dbAdapter, null, $resultSetPrototype);
},
),
);
}
}
I am doing by this example which does not have any framework:
https://github.com/webonyx/graphql-php/tree/master/examples/01-blog
So the question is - how do I create queryType instance with injected PersonTable instance? I should somehow get from the factory the PersonTable instance but I do not understand how.
Update:
I decided to try to inject QueryType into the controller. Created such function:
public function __construct(QueryType $queryType)
{
$this->queryType = $queryType;
}
Now module\Application\src\Module.php getServiceConfig looks like this:
public function getServiceConfig()
{
return array(
'factories' => array(
'Application\Model\PersonTable' => function($sm) {
$tableGateway = $sm->get('PersonTableGateway');
$table = new PersonTable($tableGateway);
return $table;
},
'PersonTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Person());
return new TableGateway('album', $dbAdapter, null, $resultSetPrototype);
},
QueryType::class => function ($sm) {
return new QueryType($sm->get(PersonTable::class));
}
// when putting in namespace does not find??????????
//QueryType::class => Application\GraphQL\Type\Factories\QueryTypeFactory::class
//QueryType::class => \QueryTypeFactory::class
),
);
}
But I get error:
Catchable fatal error: Argument 1 passed to Application\Controller\IndexController::__construct() must be an instance of Application\GraphQL\Type\QueryType, none given, called in E:\projektai\php projektai\htdocs\graphQL_zend_3\vendor\zendframework\zend-servicemanager\src\Factory\InvokableFactory.php on line 32 and defined in E:\projektai\php projektai\htdocs\graphQL_zend_3\module\Application\src\Controller\IndexController.p
How can none be given if I configured in that function?
If I could inject into the controller, then I plan to do like this:
$schema = new Schema([
//'query' => Types::query()
'query' => $this->queryType
]);
So I would not need to call query() function which return the QueryType instance anyway.
And then PersonTable would be automatically injected into QueryType class.
Update:
I had created the factory, similar as in the asnswer:
class QueryTypeFactory implements FactoryInterface
{
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
return new QueryType($container->get(PersonTable::class));
}
}
In the IndexController I have constructor:
public function __construct(QueryType $queryType)
{
$this->queryType = $queryType;
}
In the Module.php I use this factory:
public function getServiceConfig()
{
return array(
'factories' => array(
'Application\Model\PersonTable' => function($sm) {
$tableGateway = $sm->get('PersonTableGateway');
$table = new PersonTable($tableGateway);
return $table;
},
'PersonTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Person());
return new TableGateway('album', $dbAdapter, null, $resultSetPrototype);
},
// QueryType::class => function ($sm) {
// //return new QueryType($sm->get(PersonTable::class));
//
// }
//QueryType::class => Application\GraphQL\Type\Factories\QueryTypeFactory::class
//QueryType::class => \QueryTypeFactory::class
QueryType::class => QueryTypeFactory::class
),
);
}
It simply does not work, I get error:
Catchable fatal error: Argument 1 passed to Application\Controller\IndexController::__construct() must be an instance of Application\GraphQL\Type\QueryType, none given, called in E:\projektai\php projektai\htdocs\graphQL_zend_3\vendor\zendframework\zend-servicemanager\src\Factory\InvokableFactory.php on line 32 and defined in E:\projektai\php projektai\htdocs\graphQL_zend_3\module\Application\src\Controller\IndexController.php on line
I also tried this way:
$queryTypeFactory = new QueryTypeFactory();
// GraphQL schema to be passed to query executor:
$schema = new Schema([
//'query' => Types::query()
//'query' => $this->queryType
// 'query' => $queryType
'query' => $queryTypeFactory()
]);
But the $queryTypeFactory() needs parameter $container. Which is not what I want, I guess. I should be able to create an instance without passing parameters.
I hope it is ok to use QueryType::class in the factories array as key. It will create with full name space which is set:
use Application\GraphQL\Type\QueryType;
And in index controller I also call that use statement.
<?php
namespace Application\Service\Factory;
use Interop\Container\ContainerInterface;
use Zend\ServiceManager\Factory\FactoryInterface;
use Application\Service\CurrencyConverter;
use Application\Service\PurchaseManager;
/**
* This is the factory for PurchaseManager service. Its purpose is to instantiate the
* service and inject its dependencies.
*/
class PurchaseManagerFactory implements FactoryInterface
{
public function __invoke(ContainerInterface $container,
$requestedName, array $options = null)
{
// Get CurrencyConverter service from the service manager.
$currencyConverter = $container->get(CurrencyConverter::class);
// Instantiate the service and inject dependencies.
return new PurchaseManager($currencyConverter);
}
}
In the code above we have the PurchaseManagerFactory class which implements the Zend\ServiceManager\Factory\FactoryInterface interface. The factory class has the __invoke() method whose goal is to instantiate the object. This method has the $container argument which is the service manager. You can use $container to retrieve services from service manager and pass them to the constructor method of the service being instantiated.

TYPO3 Repository query returns uid and pid but no other fields

I'm doing a query on a really simple table in a typo 3 task. However, only the fields "uid" and "pid" are returned, the other fields are NULL.
My Entity:
<?php
namespace Name\SampleExtension\Domain\Model;
use TYPO3\CMS\Extbase\DomainObject\AbstractEntity;
class MailAgent extends AbstractEntity
{
/**
* #var integer
*/
protected $uid;
/**
* #var string
*/
protected $customeremail;
/**
* #var string
*/
protected $searchparameters;
/**
* #var string
*/
protected $resultlist;
public function getUid()
{
return $this->uid;
}
public function setCustomerEmail($customeremail)
{
$this->customeremail = $customeremail;
}
public function getCustomerEmail()
{
return $this->customeremail;
}
public function setSearchParameters($searchparameters)
{
$this->searchparameters = $searchparameters;
}
public function getSearchParameters()
{
return $this->searchparameters;
}
public function setResultList($resultlist)
{
$this->resultlist = $resultlist;
}
public function getResultList()
{
return $this->resultlist;
}
}
?>
The Repository:
<?php
namespace Name\SampleExtension\Domain\Repository;
use TYPO3\CMS\Extbase\Persistence\Repository;
class MailAgentRepository extends Repository
{
public function findByUids($uids)
{
$query = $this->createQuery();
foreach ($uids as $uid) {
$constraints[] = $query->equals('uid', $uid);
}
return $query->matching(
$query->logicalOr(
$constraints
)
)->execute();
}
}
?>
And the query inside the task:
<?php
namespace Name\SampleExtension\Task;
use TYPO3\CMS\Scheduler\Task\AbstractTask;
use TYPO3\CMS\Extbase\Object\ObjectManager;
use TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager;
use Name\SampleExtension\Domain\Model\MailAgent;
use Name\SampleExtension\Domain\Repository\MailAgentRepository;
class MailAgentCheckup extends AbstractTask
{
public function execute() {
$objectManager = GeneralUtility::makeInstance(ObjectManager::class);
$this->MailAgentRepository = $objectManager->get(MailAgentRepository::class);
$query = $this->MailAgentRepository->createQuery();
$allCustomers = $this->MailAgentRepository->findAll();
foreach ($allCustomers as $customer) {
var_dump($customer);
}
return true;
}
}
?>
I have no idea why the other fields are not returned, but the uid and the pid are. My guess is that I need to declare the mapping somewhere else.
EDIT: Heres the content of my TCA, which is probably wrong or not enough, but since I'm working on a existing extension I was copying from the TCA's of the tables that work.
tx_sampleextension_domain_model_mailagent.php
return [
'columns' => [
'uid' => [],
'customer_email' => [],
'search_parameters' => [],
'result_list' => [],
],
'types' => [],
];
This is from another table for which querys etc work
return [
'columns' => [
'immovable' => [],
'type' => [],
'title' => [],
'path' => [],
'mark_to_delete' => [],
],
];
Give a try to inject your repository
<?php
namespace Name\SampleExtension\Task;
use TYPO3\CMS\Scheduler\Task\AbstractTask;
use TYPO3\CMS\Extbase\Object\ObjectManager;
use TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager;
use Name\SampleExtension\Domain\Model\MailAgent;
use Name\SampleExtension\Domain\Repository\MailAgentRepository;
use TYPO3\CMS\Extbase\Utility\DebuggerUtility;
class MailAgentCheckup extends AbstractTask
{
/**
* mailAgentRepository
*
* #var \Name\SampleExtension\Domain\Repository\MailAgentRepository
* #inject
*/
protected $mailAgentRepository = NULL;
public function injectMailAgentRepository(\Name\SampleExtension\Domain\Repository\MailAgentRepository $mailAgentRepository) {
$this->mailAgentRepository = $mailAgentRepository;
}
public function execute() {
$allCustomers = $this->mailAgentRepository->findAll();
DebuggerUtility::var_dump($allCustomers);exit;
// OR
$arguments = $this->request->getArguments();
$uid = $arguments['uid'];
$singleCustomer = $this->mailAgentRepository->findByUid(intval($uid));
DebuggerUtility::var_dump($singleCustomer);exit;
/*foreach ($allCustomers as $customer) {
var_dump($customer);
}*/
return true;
}
}
?>
I was missing the TCA file for the table. After adding it and declaring all the columns in there, the extbase domain object variables got filled.

Sonata admin don't save the many-to-many field

This is the common porblem.
There is the form with many checkbocks. Making the checkbocks are aviable and click save, fields corresponding checkbock-labels don't save.
PersonAdmin class contains
...
->add('books', 'sonata_type_model',
array('by_reference' => false, 'expanded' => true, 'multiple' => true, 'label' => 'Books'))
...
Entity class contains
/**
* #ORM\ManyToMany(targetEntity="Book", mappedBy="persons", cascade={"persist"})
* #ORM\JoinTable(name="person_book")
*/
protected $books;
....
public function __construct()
{
$this->books = new ArrayCollection();
}
public function addBook(Book $book)
{
$this->books[] = $book;
return $this;
}
and geters, seters...
I unsuccessfully searched for a solution. I have found that it is necessary to add
'by_reference' => false,
or
cascade={"persist"}
but I have all of this in my code.
As mentioned before you need to save relation in both sides. But I would prefer another way: to save relation in the add actions of your entities:
//In the Person entity:
public function addBook(Book $book)
{
$book->addPerson($this);
$this->books[] = $book;
return $this;
}
//In the Book entity (if you have the same problem for another side):
public function addPerson(Person $person)
{
$person->addBook($this);
$this->persons[] = $person;
return $this;
}
You have to save at both sides.
Override the default editAction and createAction in a custom crud controller.
e.g.:
It's an example of a many to many relationship between artists and events.
($object is the current object you are editing/creating in the action)
foreach ($form['selectArtists']->getData() as $key => $value) {
$artist = $em->getRepository('MyCompanyProjectBundle:Artist')->findOneById($value);
$object->addArtist($artist);
$artist->addEvent($object);
$em->persist($artist);
}
Use edit=>inline .
->add('books', 'sonata_type_collection',
array('by_reference' => false, 'label' => 'Books'),
array('edit'=>'inline','inline'=>'table'))
May be help you.

how to concat rules for the same AR model in Yii

I use Yii MVC.
I have to add new columns in a data table very often.
I want to use Gii and regenerate the model and keep the chnages that i made; changes like constants, variables, rules, relations, etc ...
So, let's take for example the url class model:
<?php
/**
* This is the model class for table "url".
*
* The followings are the` available columns in table 'url':
* #property string $id
* #property integer $instance_id
* #property integer $website_id
* #property string $link
* #property string $title
* #property integer $created
* #property integer $updated
* #property integer $status
*/
class Url extends CActiveRecord {
const ACTIVE = 1;
/**
* Returns the static model of the specified AR class.
* #param string $className active record class name.
* #return Url the static model class
*/
public static function model($className = __CLASS__) {
return parent::model($className);
}
/**
* #return string the associated database table name
*/
public function tableName() {
return 'url';
}
/**
* #return array validation rules for model attributes.
*/
public function rules() {
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('instance_id, website_id, link, title, created, updated, status', 'required'),
array('instance_id, website_id, created, updated, status', 'numerical', 'integerOnly' => true),
array('link, title', 'length', 'max' => 255),
array('link', 'unique'),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('id, instance_id, website_id, link, title, created, updated, status', 'safe', 'on' => 'search'),
);
}
/**
* #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(
);
}
/**
* #return array customized attribute labels (name=>label)
*/
public function attributeLabels() {
return array(
'id' => 'ID',
'instance_id' => 'Instance',
'website_id' => 'Website',
'link' => 'Link',
'title' => 'Title',
'created' => 'Created',
'updated' => 'Updated',
'status' => 'Status',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
* #return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
*/
public function search() {
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria = new CDbCriteria;
$criteria->compare('id', $this->id, true);
$criteria->compare('instance_id', $this->instance_id);
$criteria->compare('website_id', $this->website_id);
$criteria->compare('link', $this->link, true);
$criteria->compare('title', $this->title, true);
$criteria->compare('created', $this->created);
$criteria->compare('updated', $this->updated);
$criteria->compare('status', $this->status);
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
));
}
}
when I will regenerate the model, the const and the rule with unique will be lost
so, I created a new model class, UrlM, that extends the url model class, and this class keps all my enhancements:
<?php
class UrlM extends Url {
const ACTIVE = 1;
public function rules() {
return array(
array('link', 'unique'),
);
}
public function relations() {
return array(
);
}
}
how do i concat the rules from the url model class with the rules from the urlm model class?
the same answer should aply for future enhancements, like relations
Each function of the parent class - like rules(), relations() etc., returns array. So you may use call to the parent::rules() and then just join "array".
public function rules() {
$myParentRules=parent::rules();
$myConcatRules=$myParentRules + array(
array('link', 'unique'),
);
return $myConcatRules;
}
array_merge will help you.
public function rules() {
$myRules = array(
array('id', 'numerical', 'integerOnly'=>true),
);
return array_merge(parent::rules(),$myRules);
}

Zend_Validate_Db_RecordExists with Doctrine 2?

I'm using Doctrine 2 in a Zend Framework application and require functionality similar to Zend_Validate_Db_RecordExists and Zend_Validate_Db_NoRecordExists.
For example, when a user enters a new item, I need to validate that a duplicate entry doesn't already exist. This is easy to accomplish with Zend_Db by adding the Db_NoRecordExists validator on my forms.
I tried implementing the custom-validator solution proposed here, but I can't figure out how they are communicating with Doctrine to retrieve entities (I suspect this approach may no longer work post-Doctrine 1.x).
The FAQ section of the Doctrine manual suggests calling contains() from the client code, but this only covers collections, and if possible I'd like to handle all of my form validation consistently from within my form models.
Can anyone suggest a way to use these Zend validators with Doctrine 2 DBAL configured as the database connection/resource?
It's quite straightforward, really.
I have a few Zend_Validate-type validators that talk to Doctrine ORM, so I have an abstract class that they descend from.
Here's the abstract class:
<?php
namespace TimDev\Validate\Doctrine;
abstract class AbstractValidator extends \Zend_Validate_Abstract{
/**
* #var Doctrine\ORM\EntityManager
*/
private $_em;
public function __construct(\Doctrine\ORM\EntityManager $em){
$this->_em = $em;
}
public function em(){
return $this->_em;
}
}
Here's my NoEntityExists validator:
<?php
namespace TimDev\Validate\Doctrine;
class NoEntityExists extends AbstractValidator{
private $_ec = null;
private $_property = null;
private $_exclude = null;
const ERROR_ENTITY_EXISTS = 1;
protected $_messageTemplates = array(
self::ERROR_ENTITY_EXISTS => 'Another record already contains %value%'
);
public function __construct($opts){
$this->_ec = $opts['class'];
$this->_property = $opts['property'];
$this->_exclude = $opts['exclude'];
parent::__construct($opts['entityManager']);
}
public function getQuery(){
$qb = $this->em()->createQueryBuilder();
$qb->select('o')
->from($this->_ec,'o')
->where('o.' . $this->_property .'=:value');
if ($this->_exclude !== null){
if (is_array($this->_exclude)){
foreach($this->_exclude as $k=>$ex){
$qb->andWhere('o.' . $ex['property'] .' != :value'.$k);
$qb->setParameter('value'.$k,$ex['value'] ? $ex['value'] : '');
}
}
}
$query = $qb->getQuery();
return $query;
}
public function isValid($value){
$valid = true;
$this->_setValue($value);
$query = $this->getQuery();
$query->setParameter("value", $value);
$result = $query->execute();
if (count($result)){
$valid = false;
$this->_error(self::ERROR_ENTITY_EXISTS);
}
return $valid;
}
}
Used in the context of a Zend_Form (which has an em() method like the abstract class above):
/**
* Overrides superclass method to add just-in-time validation for NoEntityExists-type validators that
* rely on knowing the id of the entity in question.
* #param type $data
* #return type
*/
public function isValid($data) {
$unameUnique = new NoEntityExists(
array('entityManager' => $this->em(),
'class' => 'PMS\Entity\User',
'property' => 'username',
'exclude' => array(
array('property' => 'id', 'value' => $this->getValue('id'))
)
)
);
$unameUnique->setMessage('Another user already has username "%value%"', NoEntityExists::ERROR_ENTITY_EXISTS);
$this->getElement('username')->addValidator($unameUnique);
return parent::isValid($data);
}
Check out the RecordExists.php and NoRecordExists.php classes in my project:-
https://github.com/andyfenna/AJF-IT/tree/master/library/AJFIT/Validate
I hope these are some use to you.
Thanks
Andrew