Yii PHP- Property is not defined - php

I'm managing a site built on the Yii Framework and very randomly started to get the following error. Not exactly sure how or why this started happening since the source hasn't been touch.
Appreciate any help. Thanks!
CException
Description
Property "feature.mobile_hero_img" is not defined.
Source File
/data/www.zoomiezoom.com/yii/framework/db/ar/CActiveRecord.php(106)
00094: */
00095: public function __get($name)
00096: {
00097: if(isset($this->_attributes[$name]))
00098: return $this->_attributes[$name];
00099: else if(isset($this->getMetaData()->columns[$name]))
00100: return null;
00101: else if(isset($this->_related[$name]))
00102: return $this->_related[$name];
00103: else if(isset($this->getMetaData()->relations[$name]))
00104: return $this->getRelated($name);
00105: else
00106: return parent::__get($name);
00107: }
00108:
00109: /**
00110: * PHP setter magic method.
00111: * This method is overridden so that AR attributes can be accessed like properties.
00112: * #param string property name
00113: * #param mixed property value
00114: */
00115: public function __set($name,$value)
00116: {
00117: if($this->setAttribute($name,$value)===false)
00118: {
Stack Trace
#0 /data/www.zoomiezoom.com/yii/framework/db/ar/CActiveRecord.php(106): CComponent->__get('mobile_hero_img')
#1 /data/www.zoomiezoom.com/yii/framework/web/helpers/CHtml.php(1624): CActiveRecord->__get('mobile_hero_img')
#2 /data/www.zoomiezoom.com/yii/framework/web/helpers/CHtml.php(1100): CHtml::activeInputField('text', Object(feature), 'mobile_hero_img', Array)
#3 /data/www.zoomiezoom.com/protected/views/feature/_form.php(74): CHtml::activeTextField(Object(feature), 'mobile_hero_img', Array)
#4 /data/www.zoomiezoom.com/yii/framework/web/CBaseController.php(119): require('/data/www.theax...')
#5 /data/www.zoomiezoom.com/yii/framework/web/CBaseController.php(88): CBaseController->renderInternal('/data/www.theax...', Array, true)
#6 /data/www.zoomiezoom.com/yii/framework/web/CController.php(732): CBaseController->renderFile('/data/www.theax...', Array, true)
#7 /data/www.zoomiezoom.com/protected/views/feature/create.php(14): CController->renderPartial('_form', Array)
#8 /data/www.zoomiezoom.com/yii/framework/web/CBaseController.php(119): require('/data/www.theax...')
#9 /data/www.zoomiezoom.com/yii/framework/web/CBaseController.php(88): CBaseController->renderInternal('/data/www.theax...', Array, true)
#10 /data/www.zoomiezoom.com/yii/framework/web/CController.php(732): CBaseController->renderFile('/data/www.theax...', Array, true)
#11 /data/www.zoomiezoom.com/yii/framework/web/CController.php(671): CController->renderPartial('create', Array, true)
#12 /data/www.zoomiezoom.com/protected/controllers/FeatureController.php(71): CController->render('create', Array)
#13 /data/www.zoomiezoom.com/yii/framework/web/actions/CInlineAction.php(32): FeatureController->actionCreate()
#14 /data/www.zoomiezoom.com/yii/framework/web/CController.php(300): CInlineAction->run()
#15 /data/www.zoomiezoom.com/yii/framework/web/filters/CFilterChain.php(129): CController->runAction(Object(CInlineAction))
#16 /data/www.zoomiezoom.com/yii/framework/web/filters/CFilter.php(41): CFilterChain->run()
#17 /data/www.zoomiezoom.com/yii/framework/web/CController.php(983): CFilter->filter(Object(CFilterChain))
#18 /data/www.zoomiezoom.com/yii/framework/web/filters/CInlineFilter.php(59): CController->filterAccessControl(Object(CFilterChain))
#19 /data/www.zoomiezoom.com/yii/framework/web/filters/CFilterChain.php(126): CInlineFilter->filter(Object(CFilterChain))
#20 /data/www.zoomiezoom.com/yii/framework/web/CController.php(283): CFilterChain->run()
#21 /data/www.zoomiezoom.com/yii/framework/web/CController.php(257): CController->runActionWithFilters(Object(CInlineAction), Array)
#22 /data/www.zoomiezoom.com/yii/framework/web/CWebApplication.php(320): CController->run('create')
#23 /data/www.zoomiezoom.com/yii/framework/web/CWebApplication.php(120): CWebApplication->runController('feature/create')
#24 /data/www.zoomiezoom.com/yii/framework/base/CApplication.php(135): CWebApplication->processRequest()
#25 /data/www.zoomiezoom.com/public_html/admin_tae/index.php(13): CApplication->run()
#26 {main}
schema for feature.php
<?php
class feature extends CActiveRecord
{
/**
* The followings are the available columns in table 'feature':
* #var integer $id
* #var integer $feature_name_id
* #var string $display_name
* #var integer $language_id
* #var string $long_blurb
* #var string $short_blurb
* #var string $subhead_text
* #var string $hero_img
* #var string $mobile_hero_img
* #var string $thumb_sm
* #var string $thumb_md
* #var string $thumb_lg
* #var string $link_url
* #var string $link_image
* #var string $link_text
* #var string $buyit_id
* #var string $seo_text
* #var string $meta_description
* #var string $meta_keywords
* #var integer $category_id
* #var integer $sub_cat_id
* #var string $deep_link
* #var string $tracking_id
* #var integer $weight
* #var integer $initial_rating
* #var string $active
* #var string $created
* #var string $modified
*/
/**
* Returns the static model of the specified AR class.
* #return CActiveRecord 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 'feature';
}
/**
* #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('feature_name_id', 'required'),
array('feature_name_id, language_id, category_id, sub_cat_id, weight, initial_rating', 'numerical', 'integerOnly'=>true),
array('active', 'length', 'max'=>1),
array('display_name, long_blurb, short_blurb, subhead_text, page_title, hero_img, mobile_hero_img, thumb_sm, thumb_md, thumb_lg, link_url, link_image, link_text, buyit_id, seo_text, meta_description, meta_keywords, deep_link, tracking_id, created', 'safe'),
);
}
/**
* #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.
// 'VarName'=>array('RelationType', 'ClassName', 'ForeignKey', ...additional options)
return array(
'feature_name' => array(self::BELONGS_TO, 'feature_name', 'feature_name_id', 'alias'=>'feature_name'),
'language' => array(self::BELONGS_TO, 'language', 'language_id', 'on'=>'t.language_id = language.id', 'alias'=>'language'),
'category' => array(self::BELONGS_TO, 'category', 'category_id', 'alias'=>'category'),
'sub_cat' => array(self::BELONGS_TO, 'sub_cat', 'sub_cat_id'),
'language_r' => array(self::BELONGS_TO, 'language', 'language_id', 'alias'=>'language'),
);
}
/**
* #return array Named Scopes.
*/
public function scopes()
{
return array(
'active'=>array(
'condition' => 't.active="y"',
'order' => 'feature_name.type_id DESC, category_id, sub_cat_id, t.weight ASC',
),
);
}
/**
* #return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'id' => 'Id',
'feature_name_id' => 'Feature Name ID',
'display_name' => 'Display Name',
'language_id' => 'Language',
'long_blurb' => 'Main Description',
'short_blurb' => 'Short Blurb',
'subhead_text' => 'Subhead Text',
'page_title' => 'Browser Title',
'hero_img' => 'Hero Img',
'mobile_hero_img' => 'Mobile Hero Img',
'thumb_sm' => 'Small Thumbnail',
'thumb_md' => 'Medium Thumbnail ',
'thumb_lg' => 'Large Thumbnail',
'link_url' => 'CTA Link Url',
'link_image' => 'CTA Link Image',
'link_text' => ' CTA Link Text',
'buyit_id' => ' BuyIt Link Product ID',
'seo_text' => 'SEO Copy',
'meta_description' => 'Meta Description',
'meta_keywords' => 'Meta Keywords',
'category_id' => 'Category',
'sub_cat_id' => 'Sub Category',
'deep_link' => 'Deep Link',
'tracking_id' => 'Tracking ID',
'weight' => 'Weight',
'initial_rating' => 'Initial Rating',
'active' => 'Active',
'created' => 'Created Date',
'modified' => 'Modified Date',
);
}
}

Here is your clue :
#3 /data/www.zoomiezoom.com/protected/views/feature/_form.php(74): CHtml::activeTextField(Object(feature), 'mobile_hero_img', Array)
You are pointing to a field in your feature model that does not exist.
It's there in the model. Is is in the feature table, and are you pointing to the correct model in the form.

I am guessing that you are trying to access a property of a model which extends CActiveRecord.
This means that:
Either you HAD defined this property (mobile_hero_img) and now it is removed
OR
You changed the database schema by dropping a column (mobile_hero_img) from a table (the table that your model class relates to).

It looks like an issue from your DB field.
Did you add a new input field "mobile_hero_img" in the form without adding the field it to the database? Please provide the schema of your "feature" table.

For everyone struggling with "Property is not defined" issue I have one suggestion: check your model's rules() definition and framework's version because there's a bug introduced in Yii (1.1.16) which leads to this error if there is additional space at the end of attributes' list:
// author_id WILL NOT WORK!!
array('app_id, group_id, author_id ', 'required'),
This is fixed in Yii 1.1.17.

The "Property n is not defined" issue can also occur if you have set (text) type of a field and in your model while defining a property, you may have defined it as a boolean or integer.
For example, the below is wrong for text type property.
* #property boolean $billing_address
The right definition will be
* #property string $billing_address
Sometimes there is a small mistake that takes hours to be traced.

I had a same issue. Everything was perfect in the Model class but the problem is still on. Restart the server or SQL does not help. At last, I clear the protected/runtime/cachexxxx.db file, then everything working fine.
I modified the tables with migrate file, and sometimes got error so maybe something is mixed.

My problem was solved when I upgraded to yii 1.1.17
Regards

Related

Trying to get property of non-object in Laravel 5 after upgrade

I created my first Laravel package out of some old PHP script for Teamspeak auth service. The main app was running Laravel 4, but has now been upgraded to Laravel 5. My package worked before, but now does not.
The error -
[2017-08-17 22:04:29] local.ERROR: ErrorException: Trying to get property of non-object in /apppath/vendor/eveseat/services/src/Settings/Settings.php:86
Stack trace:
#0 /apppath/vendor/eveseat/services/src/Settings/Settings.php(86): Illuminate\Foundation\Bootstrap\HandleExceptions->handleError(8, 'Trying to get p...', '/apppath/$
#1 /apppath/vendor/laravel/framework/src/Illuminate/Cache/Repository.php(349): Seat\Services\Settings\Settings::Seat\Services\Settings\{closure}()
#2 /apppath/vendor/laravel/framework/src/Illuminate/Cache/CacheManager.php(301): Illuminate\Cache\Repository->rememberForever('tHKT2R21Aa1VLKh...', Object(Closure))
#3 /apppath/bootstrap/cache/compiled.php(6468): Illuminate\Cache\CacheManager->__call('rememberForever', Array)
#4 /apppath/vendor/eveseat/services/src/Settings/Settings.php(101): Illuminate\Support\Facades\Facade::__callStatic('rememberForever', Array)
#5 /apppath/vendor/eveseat/services/src/Helpers/helpers.php(289): Seat\Services\Settings\Settings::get('main_character_...')
#6 /apppath/vendor/package/mypackage/src/Http/Controllers/Ts3Controller.php(33): setting('main_character_...')
#7 [internal function]: Seat\Ts3\Http\Controllers\Ts3Controller->getControls()
The offending function in Ts3Controller -
$APIcharacterID = $pheal->eveScope->CharacterID(array("names" => setting('main_character_name')));
The same call is made elsewhere in the parent package and still works, so the object still exists.
Pheal is not throwing errors and is completing API calls elswhere.
The Model being referenced -
namespace Seat\Services\Settings;
use Seat\Services\Models\UserSetting;
/**
* Class Profile.
* #package Seat\Services\Settings
*/
class Profile extends Settings
{
/**
* The options available for this Setting type.
*
* #var array
*/
public static $options = [
'sidebar' => ['sidebar-full', 'sidebar-collapse'],
'skins' => [
'skin-blue', 'skin-black', 'skin-purple', 'skin-green',
'skin-red', 'skin-yellow', 'skin-blue-light', 'skin-black-light',
'skin-purple-light', 'skin-green-light', 'skin-red-light',
'skin-yellow-light',
],
'thousand_seperator' => [' ', ',', '.'],
'decimal_seperator' => [',', '.'],
'mail_threads' => ['yes', 'no'],
];
/**
* #var string
*/
protected static $prefix = 'profile';
/**
* #var
*/
protected static $model = UserSetting::class;
/**
* #var string
*/
protected static $scope = 'user';
/**
* #var array
*/
protected static $defaults = [
// UI
'sidebar' => 'sidebar-full',
'skin' => 'skin-black',
'language' => 'en',
'mail_threads' => 'yes',
// Main Character
'main_character_id' => 1,
'main_character_name' => null,
// Numbers
'thousand_seperator' => ' ',
'decimal_seperator' => '.',
// Notifications
'email_notifications' => 'no',
// Multi factor authentication
'require_mfa' => 'no',
];
}
Which is referenced in my controller here -
use Seat\Services\Settings\Profile;

The class 'DoctrineModule\Stdlib\Hydrator\DoctrineObject' was not found in the chain configured namespaces

Help please.
I get this exception submiting my form.
I use Zend Framework 2 and DoctrineORMModule.
I generated my entities by means of next commands
php doctrine-module orm:convert-mapping annotation module/Globuserp/src/ --namespace="Globuserp\Entity\\" --from-database
php doctrine-module orm:generate-entities module/Globuserp/src/ --generate-annotations=true
Stack trace:
#0 /var/www/globus-erp.local/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/Driver/MappingDriverChain.php(113): Doctrine\Common\Persistence\Mapping\MappingException::classNotFoundInNamespaces('DoctrineModule\\...', Array)
#1 /var/www/globus-erp.local/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/ClassMetadataFactory.php(117): Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain->loadMetadataForClass('DoctrineModule\\...', Object(Doctrine\ORM\Mapping\ClassMetadata))
#2 /var/www/globus-erp.local/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/AbstractClassMetadataFactory.php(318): Doctrine\ORM\Mapping\ClassMetadataFactory->doLoadMetadata(Object(Doctrine\ORM\Mapping\ClassMetadata), NULL, false, Array)
#3 /var/www/globus-erp.local/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/AbstractClassMetadataFactory.php(211): Doctrine\Common\Persistence\Mapping\AbstractClassMetadataFactory->loadMetadata('DoctrineModule\\...')
#4 /var/www/globus-erp.local/vendor/doctrine/orm/lib/Doctrine/ORM/EntityManager.php(265): Doctrine\Common\Persistence\Mapping\AbstractClassMetadataFactory->getMetadataFor('DoctrineModule\\...')
#5 /var/www/globus-erp.local/vendor/doctrine/doctrine-module/src/DoctrineModule/Stdlib/Hydrator/DoctrineObject.php(119): Doctrine\ORM\EntityManager->getClassMetadata('DoctrineModule\\...')
#6 /var/www/globus-erp.local/vendor/doctrine/doctrine-module/src/DoctrineModule/Stdlib/Hydrator/DoctrineObject.php(102): DoctrineModule\Stdlib\Hydrator\DoctrineObject->prepare(NULL)
#7 /var/www/globus-erp.local/vendor/zendframework/zendframework/library/Zend/Form/Fieldset.php(591): DoctrineModule\Stdlib\Hydrator\DoctrineObject->hydrate(Array, NULL)
#8 /var/www/globus-erp.local/vendor/zendframework/zendframework/library/Zend/Form/Element/Collection.php(274): Zend\Form\Fieldset->bindValues(Array)
#9 /var/www/globus-erp.local/vendor/zendframework/zendframework/library/Zend/Form/Fieldset.php(584): Zend\Form\Element\Collection->bindValues(Array)
#10 /var/www/globus-erp.local/vendor/zendframework/zendframework/library/Zend/Form/Fieldset.php(584): Zend\Form\Fieldset->bindValues(Array)
#11 /var/www/globus-erp.local/vendor/zendframework/zendframework/library/Zend/Form/Form.php(364): Zend\Form\Fieldset->bindValues(Array)
#12 /var/www/globus-erp.local/vendor/zendframework/zendframework/library/Zend/Form/Form.php(513): Zend\Form\Form->bindValues()
#13 /var/www/globus-erp.local/module/Globuserp/src/Globuserp/Controller/IndexController.php(85): Zend\Form\Form->isValid()
#14 /var/www/globus-erp.local/vendor/zendframework/zendframework/library/Zend/Mvc/Controller/AbstractActionController.php(83): Globuserp\Controller\IndexController->addNewProjectAction()
#15 /var/www/globus-erp.local/module/Application/src/Application/Controller/BaseController.php(20): Zend\Mvc\Controller\AbstractActionController->onDispatch(Object(Zend\Mvc\MvcEvent))
#16 /var/www/globus-erp.local/module/Application/src/Application/Controller/BaseAdminController.php(17): Application\Controller\BaseController->onDispatch(Object(Zend\Mvc\MvcEvent))
#17 [internal function]: Application\Controller\BaseAdminController->onDispatch(Object(Zend\Mvc\MvcEvent))
#18 /var/www/globus-erp.local/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php(468): call_user_func(Array, Object(Zend\Mvc\MvcEvent))
#19 /var/www/globus-erp.local/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php(207): Zend\EventManager\EventManager->triggerListeners('dispatch', Object(Zend\Mvc\MvcEvent), Object(Closure))
#20 /var/www/globus-erp.local/vendor/zendframework/zendframework/library/Zend/Mvc/Controller/AbstractController.php(117): Zend\EventManager\EventManager->trigger('dispatch', Object(Zend\Mvc\MvcEvent), Object(Closure))
#21 /var/www/globus-erp.local/vendor/zendframework/zendframework/library/Zend/Mvc/DispatchListener.php(114): Zend\Mvc\Controller\AbstractController->dispatch(Object(Zend\Http\PhpEnvironment\Request), Object(Zend\Http\PhpEnvironment\Response))
#22 [internal function]: Zend\Mvc\DispatchListener->onDispatch(Object(Zend\Mvc\MvcEvent))
#23 /var/www/globus-erp.local/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php(468): call_user_func(Array, Object(Zend\Mvc\MvcEvent))
#24 /var/www/globus-erp.local/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php(207): Zend\EventManager\EventManager->triggerListeners('dispatch', Object(Zend\Mvc\MvcEvent), Object(Closure))
#25 /var/www/globus-erp.local/vendor/zendframework/zendframework/library/Zend/Mvc/Application.php(316): Zend\EventManager\EventManager->trigger('dispatch', Object(Zend\Mvc\MvcEvent), Object(Closure))
#26 /var/www/globus-erp.local/public/index.php(17): Zend\Mvc\Application->run()
#27 {main}
IndexController
namespace Globuserp\Controller;
use Application\Controller\BaseAdminController as BaseController;
use Globuserp\Form\AddNewEmployeeForm;
use Globuserp\Form\AddNewProjectForm;
use Globuserp\Entity\Projects;
use Zend\View\Model\ViewModel;
use Zend\Http\Response;
use DoctrineModule\Stdlib\Hydrator\DoctrineObject as DoctrineHydrator;
class IndexController extends BaseController
{
//...
public function addNewProjectAction()
{
$em = $this->getEntityManager();
$form = new AddNewProjectForm($em, 'addNewProject');
$request = $this->getRequest();
if($request->isPost())
{
$data = $request->getPost();
$newProject = new Projects();
$form->setHydrator(new DoctrineHydrator($em, '\Projects'));
$form->bind($newProject);
$form->setData($data);
if($form->isValid())
{
var_dump($newProject);
}
}
else
{
$result = new ViewModel(array('form' => $form));
$result->setTerminal(true);
return $result;
}
}
}
Basecontroller
namespace Application\Controller;
use Zend\Mvc\Controller\AbstractActionController;
class BaseController extends AbstractActionController
{
protected $entityManager;
public function onDispatch(\Zend\Mvc\MvcEvent $e){
$this->setEntityManager($this->getServiceLocator()->get("\Doctrine\ORM\EntityManager"));
return parent::onDispatch($e);
}
public function setEntityManager(\Doctrine\ORM\EntityManager $entity)
{
$this->entityManager = $entity;
}
public function getEntityManager()
{
return $this->entityManager;
}
}
AddNewProjectForm
namespace Globuserp\Form;
use Application\Form\BaseForm;
use Globuserp\Form\EmployeeFieldset;
use Globuserp\Form\ProjectFieldset;
use DoctrineModule\Stdlib\Hydrator\DoctrineObject as DoctrineHydrator;
class AddNewProjectForm extends BaseForm
{
public function createElements()
{
$this->setAttribute('method', 'post');
$this->setAttribute('enctype', 'multipart/form-data');
$projectFieldset = new ProjectFieldset('project', $this->objectManager, new DoctrineHydrator($this->objectManager, '\Globuserp\Entity\Projects'));
$this->add($projectFieldset);
$this->add(array(
'name' => 'submit',
'type' => 'Submit',
'attributes' => array(
'value' => 'Сохранить',
'id' => 'btn_submit',
'class' => 'btn btn-primary'
)
));
}
}
BaseForm
namespace Application\Form;
use Zend\Form\Form;
use DoctrineModule\Persistence\ObjectManagerAwareInterface;
use Doctrine\Common\Persistence\ObjectManager;
abstract class BaseForm extends Form implements ObjectManagerAwareInterface
{
protected $objectManager;
public function setObjectManager(ObjectManager $objectManager)
{
$this->objectManager = $objectManager;
}
public function getObjectManager()
{
return $this->objectManager;
}
public function __construct(ObjectManager $objectManager, $name=null)
{
parent::__construct($name);
$this->setObjectManager($objectManager);
$this->createElements();
}
abstract public function createElements();
}
EmployeeFieldset
namespace Globuserp\Form;
use Application\Form\BaseFieldset;
use Doctrine\Common\Persistence\ObjectManager;
use DoctrineModule\Stdlib\Hydrator\DoctrineObject as DoctrineHydrator;
class EmployeeFieldset extends BaseFieldset
{
public function __construct($name, ObjectManager $objectManager)
{
parent::__construct($name, $objectManager);
$this->setHydrator(new DoctrineHydrator($this->objectManager, '\Log'));
}
public function createElements()
{
$this->add(array(
'name' => 'employee',
'type' => 'DoctrineModule\Form\Element\ObjectSelect',
'options' => array(
'label' => 'Имя сотрудника',
'object_manager' => $this->objectManager,
'target_class' => 'Globuserp\Entity\Staff',
'property' => 'fullname',
'label_generator' => function($targetEntity)
{
return $targetEntity->getFullname();
}
),
'attributes' => array(
'class' => 'form-control',
'required' => 'required',
)
));
$this->add(array(
'name' => 'startTime',
'type' => 'Text',
'options' => array(
'min' => 3,
'max' => 100,
'label' => 'Время работы на проекте'
),
'attributes' => array(
'class' => 'form-control input-small',
'required' => 'required'
)
));
$this->add(array(
'name' => 'endTime',
'type' => 'Text',
'options' => array(
'min' => 3,
'max' => 100,
),
'attributes' => array(
'class' => 'form-control input-small input-small-last',
'required' => 'required'
)
));
}
}
ProjectFieldset
namespace Globuserp\Form;
use Application\Form\BaseFieldset;
use Doctrine\Common\Persistence\ObjectManager;
use DoctrineModule\Stdlib\Hydrator\DoctrineObject as DoctrineHydrator;
use Globuserp\Entity\Projects;
class ProjectFieldset extends BaseFieldset
{
public function __construct($name, ObjectManager $objectManager, DoctrineHydrator $hydrator)
{
parent::__construct($name, $objectManager);
$this->setHydrator($hydrator);
$project = new Projects();
$this->setObject($project);
}
public function createElements()
{
$this->add(array(
'name' => 'title',
'type' => 'Text',
'options' => array(
'min' => 3,
'max' => 100,
'label' => 'Наименование'
),
'attributes' => array(
'class' => 'form-control',
'required' => 'required'
)
));
$this->add(array(
'name' => 'color',
'type' => 'DoctrineModule\Form\Element\ObjectSelect',
'options' => array(
'label' => 'Цвет',
'object_manager' => $this->objectManager,
'target_class' => 'Globuserp\Entity\ProjectsColors',
'label_generator' => function($targetEntity)
{
return $targetEntity->getTitle() . "#". $targetEntity->getValue() ."";
}
),
'attributes' => array(
'class' => 'form-control color',
'required' => 'required',
)
));
$this->add(array(
'name' => 'description',
'type' => 'Textarea',
'options' => array(
'min' => 3,
'max' => 100,
'label' => 'Описание'
),
'attributes' => array(
'class' => 'form-control',
'required' => 'required'
)
));
$this->add(array(
'type' => 'Zend\Form\Element\Collection',
'name' => 'employee',
'options' => array(
'label' => 'Добавить сотрудника',
'should_create_template' => true,
'target_element' => new EmployeeFieldset('employee', $this->objectManager)
)
));
}
}
BaseFieldset
namespace Application\Form;
use Zend\Form\Fieldset;
use Doctrine\Common\Persistence\ObjectManager;
abstract class BaseFieldset extends Fieldset
{
protected $objectManager;
/**
* #param mixed $objectManager
*/
public function setObjectManager(ObjectManager $objectManager)
{
$this->objectManager = $objectManager;
}
/**
* #return mixed
*/
public function getObjectManager()
{
return $this->objectManager;
}
public function __construct($name, ObjectManager $objectManager)
{
parent::__construct($name);
$this->setObjectManager($objectManager);
$this->createElements();
}
abstract public function createElements();
}
Projects.php
namespace Globuserp\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Projects
*
* #ORM\Table(name="projects", indexes={#ORM\Index(name="projects_ibfk_1", columns={"color"})})
* #ORM\Entity
*/
class Projects
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=255, nullable=false)
*/
private $title;
/**
* #var string
*
* #ORM\Column(name="description", type="text", length=65535, nullable=true)
*/
private $description;
/**
* #var \Globuserp\Entity\ProjectsColors
*
* #ORM\ManyToOne(targetEntity="Globuserp\Entity\ProjectsColors")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="color", referencedColumnName="id")
* })
*/
private $color;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* #param string $title
* #return Projects
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set description
*
* #param string $description
* #return Projects
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set color
*
* #param \Globuserp\Entity\ProjectsColors $color
* #return Projects
*/
public function setColor(\Globuserp\Entity\ProjectsColors $color = null)
{
$this->color = $color;
return $this;
}
/**
* Get color
*
* #return \Globuserp\Entity\ProjectsColors
*/
public function getColor()
{
return $this->color;
}
}
Log.php
namespace Globuserp\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Log
*
* #ORM\Table(name="log", indexes={#ORM\Index(name="id_project", columns={"id_project"}), #ORM\Index(name="id_staff", columns={"id_staff"})})
* #ORM\Entity
*/
class Log
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var \DateTime
*
* #ORM\Column(name="start_time", type="datetime", nullable=false)
*/
private $startTime;
/**
* #var \DateTime
*
* #ORM\Column(name="end_time", type="datetime", nullable=false)
*/
private $endTime;
/**
* #var \Globuserp\Entity\Projects
*
* #ORM\ManyToOne(targetEntity="Globuserp\Entity\Projects")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="id_project", referencedColumnName="id")
* })
*/
private $idProject;
/**
* #var \Globuserp\Entity\Staff
*
* #ORM\ManyToOne(targetEntity="Globuserp\Entity\Staff")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="id_staff", referencedColumnName="id")
* })
*/
private $idStaff;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set startTime
*
* #param \DateTime $startTime
* #return Log
*/
public function setStartTime($startTime)
{
$this->startTime = $startTime;
return $this;
}
/**
* Get startTime
*
* #return \DateTime
*/
public function getStartTime()
{
return $this->startTime;
}
/**
* Set endTime
*
* #param \DateTime $endTime
* #return Log
*/
public function setEndTime($endTime)
{
$this->endTime = $endTime;
return $this;
}
/**
* Get endTime
*
* #return \DateTime
*/
public function getEndTime()
{
return $this->endTime;
}
/**
* Set idProject
*
* #param \Globuserp\Entity\Projects $idProject
* #return Log
*/
public function setIdProject(\Globuserp\Entity\Projects $idProject = null)
{
$this->idProject = $idProject;
return $this;
}
/**
* Get idProject
*
* #return \Globuserp\Entity\Projects
*/
public function getIdProject()
{
return $this->idProject;
}
/**
* Set idStaff
*
* #param \Globuserp\Entity\Staff $idStaff
* #return Log
*/
public function setIdStaff(\Globuserp\Entity\Staff $idStaff = null)
{
$this->idStaff = $idStaff;
return $this;
}
/**
* Get idStaff
*
* #return \Globuserp\Entity\Staff
*/
public function getIdStaff()
{
return $this->idStaff;
}
}
You try to hydrate NULL. So somehow you hydrate while you don't have an entity Check your stack trace for:
DoctrineModule\Stdlib\Hydrator\DoctrineObject->hydrate(Array, NULL)
So you need to look at that.
Maybe you forget to initialize your Collections or something?
Or you otherwise try to hydrate a NULL object.
I forget execute setObject method in EmployeeFildset constructor.
The correct version should be as follows
public function __construct($name, ObjectManager $objectManager)
{
parent::__construct($name, $objectManager);
$this->setHydrator(new DoctrineHydrator($this->objectManager, '\Log'));
$logEntry = new Log();
$this->setObject($logEntry);
}

The relationship field you supplied is not a valid relationship method name on the supplied Eloquent model

I have 2 tables: options and optionselections.
Here are the models:
use LaravelBook\Ardent\Ardent;
class Option extends Ardent
{
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'options';
// MASS ASSIGNMENT -------------------------------------------------------
// define which attributes are mass assignable (for security)
// we only want these 1 attribute able to be filled
protected $fillable = array('name');
public function selections()
{
return $this->hasMany('optionselection');
}
}
use LaravelBook\Ardent\Ardent;
class Optionselection extends Ardent
{
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'option_selections';
// MASS ASSIGNMENT -------------------------------------------------------
// define which attributes are mass assignable (for security)
// we only want these 1 attribute able to be filled
protected $fillable = array('option_id', 'name');
public function choice()
{
$this->belongsTo('option');
}
}
I'm trying to create the relationship in Laravel administrator like I've done so many times before, and I can't see why I'm getting the error: The 'choice' relationship field you supplied for optionselections is not a valid relationship method name on the supplied Eloquent model
return array(
/**
* Model title
*
* #type string
*/
'title' => 'Option Selections',
/**
* The singular name of your model
*
* #type string
*/
'single' => 'Option Selection',
/**
* The class name of the Eloquent model that this config represents
*
* #type string
*/
'model' => 'optionselection',
/**
* The columns array
*
* #type array
*/
'columns' => array(
'choice' => array(
'title' => 'Option',
'relationship' => 'choice',
'select' => 'name',
),
'selection' => array(
'title' => 'Selection'
),
),
'edit_fields' => array(
'choice' => array(
'title' => 'Option',
'type' => 'relationship',
'name_field' => 'name',
),
'name' => array(
'title' => 'Selection Name',
'limit' => 30,
),
),
'action_permissions'=> array(
),
)
I know that the method/relationship field actually does exist and is recognized outside of Laravel Administrator, because this works:
$optsel = new Optionselection();
// var_dump($svcloc);
if (method_exists($optsel, "choice")) {
echo '<br/>Recognizes!';
} else {
echo '<br/>Problem!';
}
Why I'm getting the error?
Missing the return inside the relationship method. Closed

form select parent hydration

I have a zf2 application that works with doctrine.
I have the following entity:
class Role
{
/**
* #var int
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
* #ORM\Column(type="string", length=255, unique=true, nullable=true)
*/
protected $name;
/**
* #var ArrayCollection
* #ORM\OneToMany(targetEntity="YrmUser\Entity\Role", mappedBy="parent")
*/
protected $children;
/**
* #var Role
* #ORM\ManyToOne(targetEntity="YrmUser\Entity\Role", inversedBy="children", cascade={"persist"})
* #ORM\JoinColumn(name="parent_id", referencedColumnName="id")
*/
protected $parent;
}
for this entity i have a form:
class RoleForm extends Form
{
/**
* [init description]
*
* #return void
*/
public function init()
{
$this->setHydrator(
new DoctrineHydrator($this->objectManager, 'YrmUser\Entity\Role')
)->setObject(new Role());
$this->setAttribute('method', 'post');
$this->add(
array(
'name' => 'name',
'attributes' => array(
'type' => 'text',
'placeholder' =>'Name',
),
'options' => array(
'label' => 'Name',
),
)
);
$this->add(
array(
'type' => 'DoctrineModule\Form\Element\ObjectSelect',
'name' => 'parent',
'attributes' => array(
'id' => 'parent_id',
),
'options' => array(
'label' => 'Parent',
'object_manager' => $this->objectManager,
'property' => 'name',
'is_method' => true,
'empty_option' => '-- none --',
'target_class' => 'YrmUser\Entity\Role',
'is_method' => true,
'find_method' => array(
'name' => 'findBy',
'params' => array(
'criteria' => array('parent' => null),
),
),
),
)
);
}
}
The hydration for the select in the form works as it only shows other roles that don't have a parent.
But when editing a existing entity it shows itself in the select so i can select itself as its parent.
I figured if i would have the id of current entity inside the form i can create a custom repo with a method that retrieves all roles without a parent and does not have the current entity id.
But i cant figure out how to get the id of the currently edited entity from inside the form.
Any help is appreciated.
Cheers,
Yrm
You can fetch the bound entity within the form using $this->getObject().
You have actually already set this with setObject(new Role());. Unfortunately this means that it was not loaded via Doctine and you will have the same issue, no $id to work with.
Therefore you will need to add the 'parent role' options (value_options) after you have bound the role loaded via doctrine.
From within the controller, I normally request the 'edit' form from a service class and pass in the entity instance or id that is being edited. Once set you can then modify existing form elements before passing it back to the controller.
// Controller
class RoleController
{
public function editAction()
{
$id = $this->params('id'); // assumed id passed as param
$service = $this->getRoleService();
$form = $service->getRoleEditForm($id); // Pass the id into the getter
// rest of the controller...
}
}
By passing in the $id when you fetch the form you can then, within a service, modify the form elements for that specific role.
class RoleService implements ObjectManagerAwareInterface, ServiceLocatorAwareInterface
{
protected function loadParentRolesWithoutThisRole(Role $role);
public function getRoleEditForm($id)
{
$form = $this->getServiceLocator()->get('Role\Form\RoleEditForm');
if ($id) {
$role = $this->getObjectManager()->find('Role', $id);
$form->bind($role); // calls $form->setObject() internally
// Now the correct entity is attached to the form
// Load the roles excluding the current
$roles = $this->loadParentRolesWithoutThisRole($role);
// Find the parent select element and set the options
$form->get('parent')->setValueOptions($roles);
}
// Pass form back to the controller
return $form;
}
}
By loading the options after the form has initialized you do not need the current DoctrineModule\Form\Element\ObjectSelect. A normal Select element that has no default value_options defined should be fine.

Property "Alerts.alert_status_id" is not defined in Yii application

Here is my Alerts model:
<?php
/**
* This is the model class for table "alerts".
*
* The followings are the available columns in table 'alerts':
* #property string $id
* #property string $alert_status_id
* #property string $cmas_regions
* #property string $alert_type_id
* #property string $agency_id
* #property string $incident_at
* #property string $entered_by_given_name
* #property string $entered_by_surname
* #property integer $incident_location_state_reference_code
* #property string $incident_location_county
* #property string $incident_location_city
* #property string $incident_location_latitude
* #property string $incident_location_longitude
* #property string $incident_location_address1
* #property string $incident_location_address2
* #property string $incident_location_postal_code
* #property integer $cap_expiration_interval
* #property string $audio_url
* #property string $wordpress_post_id
* #property string $incident_summary
* #property string $ncic_case_number
* #property string $local_case_number
* #property string $information_provider_given_name
* #property string $information_provider_surname
* #property string $activation_authorization_officer_given_name
* #property integer $activation_authorization_officer_surname
* #property string $activation_authorization_officer_given_rank
* #property string $activation_authorization_officer_badge_number
* #property string $activated_at
* #property string $cancellation_authorization_officer_first_name
* #property string $cancellation_authorization_officer_surname
* #property string $cancellation_authorization_officer_rank
* #property string $cancellation_authorization_officer_badge_number
*
* The followings are the available model relations:
* #property AlertLog[] $alertLogs
* #property AlertPersons[] $alertPersons
* #property AlertVehicles[] $alertVehicles
* #property AlertTypes $alertType
* #property AlertStatuses $alertStatus
* #property StatesReference $incidentLocationStateReferenceCode
* #property Agencies $agency
* #property CapRegions[] $capRegions
* #property DistributionLists[] $distributionLists
* #property SharedAlertRequests[] $sharedAlertRequests
* #property SharedAlerts[] $sharedAlerts
*/
class Alerts extends CActiveRecord
{
/**
* Returns the static model of the specified AR class.
* #param string $className active record class name.
* #return Alerts 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 'alerts';
}
/**
* #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('alert_status_id, alert_type_id, agency_id, incident_at, entered_by_given_name, entered_by_surname, incident_summary', 'required'),
array('incident_location_state_reference_code, cap_expiration_interval, activation_authorization_officer_surname', 'numerical', 'integerOnly'=>true),
array('alert_status_id, alert_type_id, agency_id, incident_location_postal_code, wordpress_post_id, ncic_case_number', 'length', 'max'=>10),
array('entered_by_given_name, entered_by_surname, incident_location_county, incident_location_city, incident_location_address1, incident_location_address2, information_provider_given_name, information_provider_surname, activation_authorization_officer_given_name, activation_authorization_officer_given_rank, activation_authorization_officer_badge_number, cancellation_authorization_officer_first_name, cancellation_authorization_officer_surname, cancellation_authorization_officer_rank, cancellation_authorization_officer_badge_number', 'length', 'max'=>63),
array('incident_location_latitude', 'length', 'max'=>11),
array('incident_location_longitude, local_case_number', 'length', 'max'=>12),
array('cmas_regions, audio_url', 'length', 'max'=>255),
array('activated_at', 'safe'),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('id, alert_status_id, alert_type_id, agency_id, incident_at, entered_by_given_name, entered_by_surname, incident_location_state_reference_code, incident_location_county, incident_location_city, incident_location_latitude, incident_location_longitude, incident_location_address1, incident_location_address2, incident_location_postal_code, cmas_regions, cap_expiration_interval, audio_url, wordpress_post_id, incident_summary, ncic_case_number, local_case_number, information_provider_given_name, information_provider_surname, activation_authorization_officer_given_name, activation_authorization_officer_surname, activation_authorization_officer_given_rank, activation_authorization_officer_badge_number, activated_at, cancellation_authorization_officer_first_name, cancellation_authorization_officer_surname, cancellation_authorization_officer_rank, cancellation_authorization_officer_badge_number', '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(
'alertLogs' => array(self::HAS_MANY, 'AlertLog', 'alert_id'),
'alertPersons' => array(self::HAS_MANY, 'AlertPersons', 'alert_id'),
'alertVehicles' => array(self::HAS_MANY, 'AlertVehicles', 'alert_id'),
'alertType' => array(self::BELONGS_TO, 'AlertTypes', 'alert_type_id'),
'alertStatus' => array(self::BELONGS_TO, 'AlertStatuses', 'alert_status_id'),
'incidentLocationStateReferenceCode' => array(self::BELONGS_TO, 'StatesReference', 'incident_location_state_reference_code'),
'agency' => array(self::BELONGS_TO, 'Agencies', 'agency_id'),
'capRegions' => array(self::MANY_MANY, 'CapRegions', 'alerts_has_cap_regions(alerts_id, cap_regions_id)'),
'distributionLists' => array(self::MANY_MANY, 'DistributionLists', 'alerts_has_distribution_lists(alert_id, distribution_list_id)'),
'sharedAlertRequests' => array(self::HAS_MANY, 'SharedAlertRequests', 'alert_id'),
'sharedAlerts' => array(self::HAS_MANY, 'SharedAlerts', 'alert_id'),
);
}
public function getHour()
{
return date('H',strtotime($this->incident_at));
}
public function getMinute()
{
return date('i',strtotime($this->incident_at));
}
public function getDate()
{
return date('Y-m-d',strtotime($this->incident_at));
}
/**
* #return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'id' => 'ID',
'alert_status_id' => 'Alert Statuses',
'cmas_regions' => 'Cmas Regions',
'alert_type_id' => 'Alert Type',
'agency_id' => 'Agency',
'incident_at' => 'Incident At',
'entered_by_given_name' => 'First Name',
'entered_by_surname' => 'Last Name',
'incident_location_state_reference_code' => 'State',
'incident_location_county' => 'County',
'incident_location_city' => 'City',
'incident_location_latitude' => 'Latitude',
'incident_location_longitude' => 'Longitude',
'incident_location_address1' => 'Address1',
'incident_location_address2' => 'Address2',
'incident_location_postal_code' => 'Postal Code',
'min'=> 'Minute',
'cmas_regions' => 'Cmas Regions',
'cap_expiration_interval' => 'Cap Expiration Interval',
'audio_url' => 'Audio Url',
'wordpress_post_id' => 'Wordpress Post',
'incident_summary' => 'Incident Summary',
'ncic_case_number' => 'Ncic Case Number',
'local_case_number' => 'Local Case Number',
'information_provider_given_name' => 'First Name',
'information_provider_surname' => 'Last Name',
'activation_authorization_officer_given_name' => 'First Name',
'activation_authorization_officer_surname' => 'Last Name',
'activation_authorization_officer_given_rank' => 'Officer Rank',
'activation_authorization_officer_badge_number' => 'Officer Badge Number',
'activated_at' => 'Activated At',
'cancellation_authorization_officer_first_name' => 'First Name',
'cancellation_authorization_officer_surname' => 'Last Name',
'cancellation_authorization_officer_rank' => 'Officer Rank',
'cancellation_authorization_officer_badge_number' => 'Officer Badge Number',
);
}
/**
* 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('alert_status_id',$this->alert_status_id,true);
$criteria->compare('cmas_regions',$this->cmas_regions,true);
$criteria->compare('alert_type_id',$this->alert_type_id,true);
$criteria->compare('agency_id',$this->agency_id,true);
$criteria->compare('incident_at',$this->incident_at,true);
$criteria->compare('entered_by_given_name',$this->entered_by_given_name,true);
$criteria->compare('entered_by_surname',$this->entered_by_surname,true);
$criteria->compare('incident_location_state_reference_code',$this->incident_location_state_reference_code);
$criteria->compare('incident_location_county',$this->incident_location_county,true);
$criteria->compare('incident_location_city',$this->incident_location_city,true);
$criteria->compare('incident_location_latitude',$this->incident_location_latitude,true);
$criteria->compare('incident_location_longitude',$this->incident_location_longitude,true);
$criteria->compare('incident_location_address1',$this->incident_location_address1,true);
$criteria->compare('incident_location_address2',$this->incident_location_address2,true);
$criteria->compare('incident_location_postal_code',$this->incident_location_postal_code,true);
$criteria->compare('cmas_regions',$this->cmas_regions,true);
$criteria->compare('cap_expiration_interval',$this->cap_expiration_interval);
$criteria->compare('audio_url',$this->audio_url,true);
$criteria->compare('wordpress_post_id',$this->wordpress_post_id,true);
$criteria->compare('incident_summary',$this->incident_summary,true);
$criteria->compare('ncic_case_number',$this->ncic_case_number,true);
$criteria->compare('local_case_number',$this->local_case_number,true);
$criteria->compare('information_provider_given_name',$this->information_provider_given_name,true);
$criteria->compare('information_provider_surname',$this->information_provider_surname,true);
$criteria->compare('activation_authorization_officer_given_name',$this->activation_authorization_officer_given_name,true);
$criteria->compare('activation_authorization_officer_surname',$this->activation_authorization_officer_surname);
$criteria->compare('activation_authorization_officer_given_rank',$this->activation_authorization_officer_given_rank,true);
$criteria->compare('activation_authorization_officer_badge_number',$this->activation_authorization_officer_badge_number,true);
$criteria->compare('activated_at',$this->activated_at,true);
$criteria->compare('cancellation_authorization_officer_first_name',$this->cancellation_authorization_officer_first_name,true);
$criteria->compare('cancellation_authorization_officer_surname',$this->cancellation_authorization_officer_surname,true);
$criteria->compare('cancellation_authorization_officer_rank',$this->cancellation_authorization_officer_rank,true);
$criteria->compare('cancellation_authorization_officer_badge_number',$this->cancellation_authorization_officer_badge_number,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
}
I am calling it in controller by following line :
$alert_model = new Alerts;
$this->performAjaxValidation(array(
$alert_model, $agency_model, $victim_model, $suspect_model, $vehicle_model
));
$status = AlertStatuses::model()->find("name='created'");
$alert_model->alert_status_id = $status->id;
This is the error message:
Error: Property "Alerts.alert_status_id" is not defined.
Any help is much appreciated!
Check your alerts table, it most definitely does not contain alert_status_id column.
This "Property n is not defined" issue can also occur if you have set (text) type of a field and in your model while defining a property, you may have defined it as a boolean or integer.
For example: The below is wrong for text type property.
* #property boolean $billing_address
The right definition will be
* #property string $billing_address
Sometimes there is a small mistake that takes hours to be traced.

Categories