Value won't be written into database - yii2-advanced-app

following value won't be written into database, although var_dump shows value correctly.
$model=new Bewerber();
$model->umkreis=5000;
$model->wunschgehalt_brutto=7777;
var_dump($model->umkreis)
shows up
int(5000)
but value won't be written into databse. How can this be?
Here is model:
<?php
namespace frontend\modules\bewerber\models\base;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\behaviors\BlameableBehavior;
use mootensai\behaviors\UUIDBehavior;
class Bewerber extends \yii\db\ActiveRecord {
use \mootensai\relation\RelationTrait;
public $avatar;
public function relationNames() {
return [
'person',
'abrechnungsweg',
'bewerberquelle',
'kanal',
'personRekrutiertVon',
'angelegtVon',
'aktualisiertVon',
'bewerbungVorschlags',
'eMatchingbegriffs',
'ePhases',
'eStatuses',
'user0',
'user1'
];
}
public function rules() {
return [
[['id_person', 'id_person_rekrutiert_von', 'id_abrechnungsweg', 'id_kanal', 'id_bewerberquelle', 'id_ba_xml_gelernter_beruf_1', 'id_ba_xml_gelernter_beruf_2', 'id_ba_xml_gelernter_beruf_3', 'umkreis', 'avgs', 'avgs_betrag', 'wunschgehalt_brutto', 'arbeitsumfang_vollzeit', 'arbeitsumfang_teilzeit', 'arbeitszeit_bueroueblich', 'arbeitszeit_vormittag', 'arbeitszeit_nachmittag', 'arbeitszeit_abend', 'arbeitszeit_nacht', 'arbeitszeit_wochenende', 'schichtbereitschaft', 'wochenstunden_minimum', 'wochenstunden_maximum', 'quereinsteiger', 'zeitarbeit', 'pkw', 'fuehrerschein_pkw', 'fuehrerschein_lkw', 'fuehrerschein_omnibus', 'reisebereitschaft', 'kandidat', 'veroeffentlichen_bewerberboerse', 'kontakt_halten', 'aktiv', 'angelegt_von', 'aktualisiert_von', 'optimistic_lock'], 'integer'],
[['ablaufdatum_avgs', 'verfuegbar_ab', 'kandidat_seit', 'zuletzt_deaktiviert_am', 'angelegt_am', 'arbeitsuchend_seit'], 'safe'],
[['beurteilung_fachlich', 'beurteilung_persoenlich', 'sonstiges', 'anschreiben'], 'string'],
[['gesuchte_positionen', 'bemerkung_intern'], 'string', 'max' => 255],
[['id_person', 'avgs', 'arbeitsumfang_vollzeit', 'arbeitszeit_bueroueblich', 'kandidat', 'veroeffentlichen_bewerberboerse', 'kontakt_halten', 'aktiv'], 'required'],
['avgs_betrag', 'default', 'value' => '2000'],
[['optimistic_lock'], 'default', 'value' => '0'],
[['optimistic_lock'], 'mootensai\components\OptimisticLockValidator'],
[['avatar'], 'file', 'skipOnEmpty' => false, 'maxFiles' => 3],
];
}
public static function tableName() {
return 'bewerber';
}
public function optimisticLock() {
return 'optimistic_lock';
}
public function attributeLabels() {
return [
'id' => Yii::t('app', 'ID'),
'id_person' => Yii::t('app', 'Bewerber'),
'id_person_rekrutiert_von' => Yii::t('app', 'Bewerber wurde rekrutiert von'),
'id_abrechnungsweg' => Yii::t('app', 'Abrechnungsweg'),
'id_kanal' => Yii::t('app', 'Kanal'),
'id_bewerberquelle' => Yii::t('app', 'Bewerberquelle'),
'id_ba_xml_gelernter_beruf_1' => Yii::t('app', 'Gelernter Beruf'),
'id_ba_xml_gelernter_beruf_2' => Yii::t('app', 'Alternativ Beruf'),
'id_ba_xml_gelernter_beruf_3' => Yii::t('app', 'ungelernte Tätigkeit'),
'umkreis' => Yii::t('app', 'Umkreis(km)'),
'arbeitsuchend_seit' => Yii::t('app', 'Arbeitsuchend seit'),
'avgs' => Yii::t('app', 'Avgs'),
'avgs_betrag' => Yii::t('app', 'Avgs-Betrag'),
'ablaufdatum_avgs' => Yii::t('app', 'Ablaufdatum(Avgs)'),
'wunschgehalt_brutto' => Yii::t('app', 'Wunschgehalt(brutto/€)'),
'beurteilung_fachlich' => Yii::t('app', 'Beurteilung(fachlich)'),
'beurteilung_persoenlich' => Yii::t('app', 'Beurteilung(persönlich)'),
'sonstiges' => Yii::t('app', 'Sonstiges'),
'verfuegbar_ab' => Yii::t('app', 'Verfügbar ab'),
'gesuchte_positionen' => Yii::t('app', 'Gesuchte Positionen'),
'anschreiben' => Yii::t('app', 'Anschreiben'),
'arbeitsumfang_vollzeit' => Yii::t('app', 'Arbeitsumfang(VZ)'),
'arbeitsumfang_teilzeit' => Yii::t('app', 'Arbeitsumfang(TZ)'),
'arbeitszeit_bueroueblich' => Yii::t('app', 'ArbZ/8-16pm.'),
'arbeitszeit_vormittag' => Yii::t('app', 'ArbZ(vorm.)'),
'arbeitszeit_nachmittag' => Yii::t('app', 'ArbZ(Nachm.)'),
'arbeitszeit_abend' => Yii::t('app', 'ArbZ(abds.)'),
'arbeitszeit_nacht' => Yii::t('app', 'ArbZ(nachts)'),
'arbeitszeit_wochenende' => Yii::t('app', 'ArbZ(WE)'),
'schichtbereitschaft' => Yii::t('app', 'schichtbereit'),
'wochenstunden_minimum' => Yii::t('app', 'WStd.(min.)'),
'wochenstunden_maximum' => Yii::t('app', 'WStd.(max.)'),
'bemerkung_intern' => Yii::t('app', 'interne Bemerkung'),
'quereinsteiger' => Yii::t('app', 'Quereinsteiger'),
'zeitarbeit' => Yii::t('app', 'Zeitarbeit'),
'pkw' => Yii::t('app', 'Pkw'),
'fuehrerschein_pkw' => Yii::t('app', 'FS(Pkw'),
'fuehrerschein_lkw' => Yii::t('app', 'FS(Lkw)'),
'fuehrerschein_omnibus' => Yii::t('app', 'FS(Bus)'),
'reisebereitschaft' => Yii::t('app', 'reisebereit'),
'kandidat' => Yii::t('app', 'Kandidat'),
'kandidat_seit' => Yii::t('app', 'Kandidat seit'),
'veroeffentlichen_bewerberboerse' => Yii::t('app', 'Bewerberbörse'),
'kontakt_halten' => Yii::t('app', 'Kontakt halten'),
'aktiv' => Yii::t('app', 'Aktiv'),
'zuletzt_deaktiviert_am' => Yii::t('app', 'Zuletzt deaktiviert am'),
'angelegt_am' => Yii::t('app', 'Angelegt am'),
'angelegt_von' => Yii::t('app', 'Angelegt von'),
'aktualisiert_am' => Yii::t('app', 'Aktualisiert am'),
'aktualisiert_von' => Yii::t('app', 'Aktualisiert von'),
'optimistic_lock' => Yii::t('app', 'Optimistic Lock'),
];
}
public function getPerson() {
return $this->hasOne(\common\modules\basis\models\Person::className(), ['id' => 'id_person']);
}
public function getAbrechnungsweg() {
return $this->hasOne(\common\modules\lookup\models\LAbrechnungsweg::className(), ['id' => 'id_abrechnungsweg']);
}
public function behaviors() {
return [
'timestamp' => [
'class' => TimestampBehavior::className(),
'createdAtAttribute' => 'angelegt_am',
'updatedAtAttribute' => 'aktualisiert_am',
'value' => new \yii\db\Expression('NOW()'),
],
/* das Blameable-Verhalten wurde in unsere Klasse ausgelagert */
'uuid' => [
'class' => UUIDBehavior::className(),
'column' => 'id',
],
];
}
public static function find() {
return new \frontend\modules\bewerber\models\BewerberQuery(get_called_class());
}
public function upload() {
$x=0;
if ($this->validate()) {
foreach ($this->avatar as $uploaded_file) {
$uploaded_file->saveAs(Yii::getAlias('#uploading') . '/' . $uploaded_file->baseName . '.' . $uploaded_file->extension);
$x++;
}
if($x>0)
return true;
}
return false;
}
}

Related

How to make a field that is an entity as hidden in the form with SonataAdmin?

I need to add entity field as a hidden in my form
In the admin form with sonata I have:
protected function configureFormFields(FormMapper $formMapper)
{
if ($this->getRoot()->getSubject()->getId()) {
$formMapper
->add('driverNight', 'hidden', array(), array('admin_code' => 'cab.admin.driver'))
->add('monday', 'checkbox', array('required' => false, "attr" => array('class' => 'checkbox-day'), 'label' => 'Monday', 'value' => '0'))
->add('tuesday', 'checkbox', array('required' => false, "attr" => array('class' => 'checkbox-day'), 'label' => 'Tuesday', 'value' => '0'))
->add('wednesday', 'checkbox', array('required' => false, "attr" => array('class' => 'checkbox-day'), 'label' => 'Wednesday', 'value' => '0'))
->add('thursday', 'checkbox', array('required' => false, "attr" => array('class' => 'checkbox-day'), 'label' => 'Thursday', 'value' => '0'))
->add('friday', 'checkbox', array('required' => false, "attr" => array('class' => 'checkbox-day'), 'label' => 'Friday', 'value' => '0'))
->add('saturday', 'checkbox', array('required' => false, "attr" => array('class' => 'checkbox-day'), 'label' => 'Saturday', 'value' => '0'))
->add('sunday', 'checkbox', array('required' => false, "attr" => array('class' => 'checkbox-day'), 'label' => 'Sunday', 'value' => '0'))
}
Actually, no value in the input (see the inspect image)
How to make the driverNight field as hidden knowing that it is of type entity?
You could use a data transformer as detailed here: data transformer
I suggest that you create a transformer class which transforms the entity to an int in the view layer and reverses from int to entity in the model layer and the use the addModelTransformer method in your config form.
Create the model Transformer class which implements Symfony\Component\Form\DataTransformerInterface and contains 2 methods transform and reverseTransform. This class could be constructed by passing 2 arguments: Entity manager and the user entity object that will be transformed to int.
.
class DriverToIntTransformer implements DataTransformerInterface {
private $manager;
private $driver;
public function __construct(ObjectManager $manager, $oUser)
{
$this->manager = $manager;
$this->driver = $oUser;
}
public function transform($user)
{
if (null === $user) {
return $this->driver->getId();
}
return $user->getId();
}
public function reverseTransform($driverNumber)
{
if (!$driverNumber) {
return;
}
$oDriver = $this->manager
->getRepository('YourUserBundle:User')
// query for the driver with this id
->find($driverNumber);
if (null === $oDriver) {
throw new TransformationFailedException(sprintf(
'An user with number "%s" does not exist!',
$driverNumber
));
}
return $oDriver;
}
2 call the transform method:
if ($this->getRoot()->getSubject()->getId()) {
$driver = $this->getRoot()->getSubject()->getId();
$em = $this->container->get('doctrine.orm.entity_manager');
$oDriver = $em->getRepository('YourUserBundle:User')->find($driver);
$formMapper
->add('driverNight', 'hidden', array(), array('admin_code' => 'cab.admin.driver'));
$formBuilder = $formMapper->getFormBuilder();
$formBuilder->get('driverNight')->addModelTransformer(new DriverToIntTransformer($em, $oDriver));
$formMapper
->add('monday', 'checkbox', array('required' => false, "attr" => array('class' => 'checkbox-day'), 'label' => 'Monday', 'value' => '0'));//.....
}

Prestashop HelperFrom/List - messy layout

I'm new to prestashop and I worked the whole day on creating a back office interface that allows the user to write, edit, and delete articles. It is sort of a blog. I used Prestashop's Helpers (Form and List) and everything works great. I also added a new tab in the back office to access this tool.
The problem is that the layout is messy and doesn't look like the other forms and listing pages. The layout is really not sexy. Maybe I should look at some css file, or add any function in my controller ? You'll find the source code of the latter here (I can't insert images, not enough reputation --'):
<?php
class Article extends ObjectModel
{
/** #var string Name */
public $id_article;
public $titre;
public $contenu;
public $url_photo;
/**
* #see ObjectModel::$definition
*/
public static $definition = array(
'table' => 'article',
'primary' => 'id_article',
'fields' => array(
'titre' => array(
'type' => self::TYPE_STRING,
'validate' => 'isGenericName',
'required' => true,
'class' => 'lg'
),
'contenu' => array(
'type' => self::TYPE_STRING,
'validate' => 'isGenericName',
'required' => true
),
'url_photo' => array(
'type' => self::TYPE_STRING,
'validate' => 'isGenericName',
'required' => false,
),
),
);
}
class AdminBlogController extends AdminController{
public function initContent(){
parent::initContent();
}
public function __construct(){
$this->table = 'article';
$this->className = 'Article';
$this->lang = false;
// Building the list of records stored within the "article" table
$this->fields_list = array(
'id_article' => array(
'title' => 'ID',
'align' => 'center',
'width' => 25
),
'titre' => array(
'title' => 'Titre',
'width' => 'auto'
),
'contenu' => array(
'title' => 'Contenu',
'width' => 'auto'
)
);
// This adds a multiple deletion button
$this->bulk_actions = array(
'delete' => array(
'text' => $this->l('Delete selected'),
'confirm' => $this->l('Delete selected items?')
)
);
parent::__construct();
}
// This method generates the list of results
public function renderList(){
// Adds an Edit button for each result
$this->addRowAction('edit');
// Adds a Delete button for each result
$this->addRowAction('delete');
return parent::renderList();
}
// This method generates the Add/Edit form
public function renderForm(){
// Building the Add/Edit form
$this->fields_form = array(
'tinymce' => true,
'legend' => array(
'title' => 'Article'
),
'input' => array(
array(
'type' => 'text',
'label' => 'Titre',
'name' => 'titre',
'class' => 'lg',
'required' => true,
//'desc' => 'Nom de l\'article',
),
array(
'type' => 'textarea',
'label' => 'Contenu',
'name' => 'contenu',
'class' => 'lg',
'required' => true,
'autoload_rte' => true,
//'desc' => 'Contenu de l\'article',
),
array(
'type' => 'file',
'label' => 'Photo',
'name' => 'url_photo',
'class' => 'lg',
'required' => true,
//'desc' => 'Contenu de l\'article',
)
),
'submit' => array(
'title' => $this->l('Save'),
'class' => 'button'
)
);
return parent::renderForm();
}
}
?>
Thank you.
I just needed to set $this->bootstrap = true

Yii2 multiple forms in a single action

Which is the right way to handle multiple forms in a single action?
Here is my models/MembersBans.php
<?php
namespace app\models;
use Yii;
use yii\behaviors\TimestampBehavior;
use app\models\Members;
class MembersBans extends \yii\db\ActiveRecord {
public $username;
public static function tableName() {
return '{{%members_bans}}';
}
public static function primaryKey() {
return array('ban_id');
}
public function behaviors() {
return [
[
'class' => TimestampBehavior::className(),
'createdAtAttribute' => 'date_added',
'updatedAtAttribute' => 'last_updated',
],
];
}
public function rules() {
return [
[['ban_id', 'ban_memberid', 'date_added', 'last_updated'], 'integer'],
[['username', 'end_date'], 'safe'],
['end_date', 'date', 'format' => 'yyyy-mm-dd'],
[['ban_ip'], 'string', 'max' => 40],
[['reason'], 'string', 'max' => 255]
];
}
public function attributeLabels() {
return [
'ban_id' => Yii::t('app', 'ID на бана'),
'ban_memberid' => Yii::t('app', 'Потребителско ID'),
'username' => 'Потребителско име',
'ban_ip' => Yii::t('app', 'IP адрес'),
'end_date' => Yii::t('app', 'Дата на изтичане'),
'reason' => Yii::t('app', 'Причина за бана'),
'date_added' => Yii::t('app', 'Дата на добавяне'),
];
}
public function getMemberBans() {
$bans = $this->find()->where('ban_memberid');
return $bans;
}
public function getIpBans() {
$bans = $this->find()->where('ban_ip');
return $bans;
}
public function getMember() {
return $this->hasOne(Members::className(), ['member_id' => 'ban_memberid']);
}
public function banMember() {
$memberInfo = Members::findByUsername($this->username);
if ($memberInfo) {
$this->ban_memberid = $memberInfo->member_id;
if ($this->save()) {
Yii::$app->session->setFlash('alert-success', 'Потребителят беше успешно блокиран.');
} else {
Yii::$app->session->setFlash('alert-error', 'Възникна грешка при блокирането на потребителя.');
}
} else {
Yii::$app->session->setFlash('alert-error', 'Не съществува потребител с това потребителско име.');
}
}
public function banIp() {
if ($this->save()) {
Yii::$app->session->setFlash('alert-success', 'IP адресът беше успешно блокиран.');
} else {
Yii::$app->session->setFlash('alert-error', 'Възникна грешка при блокирането на IP адреса.');
}
}
}
My controllers/MembersBansController.php:
public function actionList() {
$membersBans = new MembersBans();
if ($membersBans->load(Yii::$app->request->post('banMember'))) {
$membersBans->banMember();
}
if ($membersBans->load(Yii::$app->request->post('banIp'))) {
$membersBans->banIp();
}
return $this->render('list', [
'membersBans' => $membersBans,
]);
}
views/members-bans/list:
<div class="the-box">
<?php
$activeForm = ActiveForm::begin([
'id' => 'banMember',
'enableClientValidation' => true,
'enableAjaxValidation' => true,
'validateOnSubmit' => true,
'validateOnChange' => true,
'validateOnType' => true,
])
?>
<?= $activeForm->field($membersBans, 'username', [
'template' => '{label}{input}{hint}{error}'
])->textInput(['class' => 'form-control', 'placeholder' => 'Въведете потребителско име']);
?>
<?= $activeForm->field($membersBans, 'end_date', [
'template' => '{label}{input}{hint}{error}'
])->textInput(['class' => 'form-control datepicker', 'placeholder' => 'Въведете период на бана']);
?>
<?= $activeForm->field($membersBans, 'reason', [
'template' => '{label}{input}{hint}{error}'
])->textInput(['class' => 'form-control', 'placeholder' => 'Въведете причина за бана']);
?>
<div class="form-group">
<?= Html::submitButton('Добави', ['type' => 'submit', 'class' => 'btn btn-default']) ?>
</div>
<?php ActiveForm::end()?>
</div>
<div class="the-box">
<?php
$activeForm = ActiveForm::begin([
'id' => 'banIp',
'enableClientValidation' => true,
'enableAjaxValidation' => true,
'validateOnSubmit' => true,
'validateOnChange' => true,
'validateOnType' => true,
])
?>
<?= $activeForm->field($membersBans, 'ban_ip', [
'template' => '{label}{input}{hint}{error}'
])->textInput(['class' => 'form-control', 'placeholder' => 'Въведете IP адрес или цяла мрежа']);
?>
<?= $activeForm->field($membersBans, 'end_date', [
'template' => '{label}{input}{hint}{error}'
])->textInput(['class' => 'form-control datepicker', 'placeholder' => 'Въведете период на бана']);
?>
<?= $activeForm->field($membersBans, 'reason', [
'template' => '{label}{input}{hint}{error}'
])->textInput(['class' => 'form-control', 'placeholder' => 'Въведете причина за бана']);
?>
<div class="form-group">
<?= Html::submitButton('Добави', ['type' => 'submit', 'class' => 'btn btn-default']) ?>
</div>
<?php ActiveForm::end() ?>
</div>
And it doesn't seem to work. Any ideas?
Id in ActiveForm does't mean id in $_POST. You should use:
$membersBans->load(Yii::$app->request->post())
or
$membersBans->load(Yii::$app->request->post('MembersBans'))
for load attributes from form.
For example multiple forms from CeBe (http://www.yiiframework.com/forum/index.php/topic/53935-solved-subforms/page__p__248184#entry248184)
public function actionCreate()
{
$user = new User;
$profile = new Profile;
if ($user->load(Yii::$app->request->post()) && $profile->load(Yii::$app->request->post()) && Model::validateMultiple([$user, $profile])) {
$user->save(false); // skip validation as model is already validated
$profile->user_id = $user->id; // no need for validation rule on user_id as you set it yourself
$profile-save(false);
return $this->redirect(['view', 'id' => $user->id]);
} else {
return $this->render('create', [
'user' => $user,
'profile' => $profile,
]);
}
}
In your action you use one model. I think you should extends MembersBans to MembersBansIp class. And your action:
public function actionList() {
$membersBans = new MembersBans();
$membersBansIp = new MembersBansIp();
if ($membersBans->load(Yii::$app->request->post())) {
$membersBans->banMember();
}
if ($membersBansIp->load(Yii::$app->request->post())) {
$membersBansIp->banIp();
}
return $this->render('list', [
'membersBans' => $membersBans,
'membersBansIp' => $membersBansIp,
]);
}
In view:
<?php
$activeForm = ActiveForm::begin([
'id' => 'banMember',
])
?>
<?= $activeForm->field($membersBans, 'fieldMembersBans') ?>
<?= Html::submitButton('Login', ['class' => 'btn btn-primary']) ?>
<?php ActiveForm::end() ?>
<?php
$activeForm = ActiveForm::begin([
'id' => 'banMemberIp',
])
?>
<?= $activeForm->field($membersBansIp, 'usernameMembersBansIp') ?>
<?= Html::submitButton('Login', ['class' => 'btn btn-primary']) ?>
<?php ActiveForm::end() ?>
EDIT
I put your code. He is work. https://yadi.sk/i/y7PkwGUPekjPD https://yadi.sk/i/h8dCYQz3ekk2B
But I change controller to this
$membersBans = new MembersBans();
if ($membersBans->load(Yii::$app->request->post())) {
$membersBans->banMember();
}
if ($membersBans->load(Yii::$app->request->post())) {
$membersBans->banIp();
}
And in model change Members to User, because I have not Members objects:
$memberInfo = User::findByUsername($this->username);
if ($memberInfo) {
$this->ban_memberid = $memberInfo->id;
Resume: your code is worked. Change controller, how I written up.

MOODLE ROLES AND CAPABILITIES

I had developed a block in 2.5. I installed the block successfully..and gave permissions settings on front end to view this block only for one role users say 'Manager'. So, Manager/Admin can only view this block and no one else.
But this block is still visible for all. Could you please judge me.. where I went wrong.. Here is my leisure block code
Blocks/block_leisure/block_leisure.php
<?php
class block_leisure extends block_base
{
public function init()
{
global $CFG;
$this->title = get_string('leisure', 'block_leisure');
}
public function get_content()
{
global $COURSE, $DB, $PAGE, $CFG, $USER, $CFG, $SESSION, $OUTPUT;
if ($this->content !== null)
{
return $this->content;
}
$this->content = new stdClass;
$context = $PAGE->context;
$this->content->text = 'This is a leisure block content';
$this->content->footer = 'Footer here...';
return $this->content;
} // Function - get_content().
public function getmodules()
{
return true;
}
}
Blocks/block_leisure/db/access.php
<?php
defined('MOODLE_INTERNAL') || die;
$capabilities = array(
'block/leisure:myaddinstance' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_SYSTEM,
'archetypes' => array(
'user' => CAP_ALLOW
),
'clonepermissionsfrom' => 'moodle/my:manageblocks'
),
'block/leisure:addinstance' => array(
'riskbitmask' => RISK_SPAM | RISK_XSS,
'captype' => 'write',
'contextlevel' => CONTEXT_BLOCK,
'archetypes' => array(
'editingteacher' => CAP_ALLOW,
'manager' => CAP_ALLOW
),
'clonepermissionsfrom' => 'moodle/site:manageblocks'
),
'block/leisure:viewpages' => array(
'captype' => 'read',
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_ALLOW,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'manager' => CAP_ALLOW
)
),
'block/leisure:managepages' => array(
'captype' => 'read',
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'guest' => CAP_PREVENT,
'student' => CAP_PREVENT,
'teacher' => CAP_PREVENT,
'editingteacher' => CAP_ALLOW,
'coursecreator' => CAP_ALLOW,
'manager' => CAP_ALLOW
)
)
);
and as usual I have lang folder, version.php and read me file.
You need to do something with the capability you have defined, otherwise it will have no effect.
Check the capability within get_content, then return null if nothing should be displayed.

ZF2 - Binding Nested Fieldsets/Collections

I have two entities (Metaproduct and Options) that have Many-To-Many Unidirectional relation with entity Specification.
The relation between Metaproduct and Option is One-To-Many.
The code for the Fieldsets and Forms for Metaproduct is the following:
MetaproductFieldset.php
namespace Bundle\Fieldset;
class MetaproductFieldset extends EntityUsingFieldset implements InputFilterProviderInterface{
...
public function __construct(ObjectManager $objectManager)
{
$this->add(array(
'type' => 'Zend\Form\Element\Collection',
'name' => 'options',
'options' => array(
'label' => 'Options',
'count' => 1,
'allow_add' => true,
'allow_remove' => true,
'should_create_template' => true,
'target_element' => new OptionFieldset($objectManager),
),
'attributes' => array(
'id' => 'options',
),
));
$this->add(array(
'type' => 'Zend\Form\Element\Collection',
'name' => 'specifications',
'options' => array(
'label' => 'Specifications',
'count' => 1,
'allow_add' => true,
'allow_remove' => true,
'should_create_template' => true,
'target_element' => new SpecificationFieldset($objectManager),
),
'attributes' => array(
'id' => 'specifications',
),
));
OptionFieldset.php
namespace Bundle\Fieldset;
class OptionFieldset extends EntityUsingFieldset implements InputFilterProviderInterface{
public function __construct(ObjectManager $objectManager)
{
$this->setObjectManager($objectManager);
parent::__construct('option');
$this->setHydrator(new DoctrineHydrator($objectManager))->setObject(new \Bundle\Entity\Option());
$this->add(array(
'type' => 'Zend\Form\Element\Collection',
'name' => 'specifications',
'options' => array(
'label' => 'Specifications',
'count' => 1,
'allow_add' => true,
'allow_remove' => true,
'should_create_template' => true,
'target_element' => new SpecificationFieldset($objectManager),
),
'attributes' => array(
'id' => 'specifications',
),
));
SpecificationFieldset.php
namespace Bundle\Fieldset;
use Doctrine\Common\Persistence\ObjectManager;
use DoctrineModule\Stdlib\Hydrator\DoctrineObject as DoctrineHydrator;
use Zend\InputFilter\InputFilterProviderInterface;
class SpecificationFieldset extends EntityUsingFieldset implements InputFilterProviderInterface{
public function __construct(ObjectManager $objectManager)
{
$this->setObjectManager($objectManager);
parent::__construct('specification');
$this->setHydrator(new DoctrineHydrator($objectManager))->setObject(new \Bundle\Entity\Specification());
$this->add(array(
'type' => 'Zend\Form\Element\Hidden',
'name' => 'id'
));
$this->add(array(
'type' => 'DoctrineModule\Form\Element\ObjectSelect',
'name' => 'label',
'options' => array(
'label' => 'Label',
'object_manager' => $objectManager,
'target_class' => 'Bundle\Entity\Label',
'property' => 'value',
'empty_option' => '--- please choose ---'
),
));
$this->add(array(
'type' => 'Zend\Form\Element\Text',
'name' => 'value',
'options' => array(
'label' => 'Value'
)
));
}
Metaproduct.php
namespace Bundle\Form;
...
class Metaproduct extends Form {
public function __construct(ObjectManager $objectManager){
parent::__construct('metaproduct-form');
$this->setHydrator(new DoctrineHydrator($objectManager));
$mpFieldset = new MetaproductFieldset($objectManager);
$mpFieldset->setUseAsBaseFieldset(true);
...
But when I try to print bind an object on that form, the following Expection is throwed:
File
zendframework\library\Zend\Form\Fieldset.php:439
Message
Zend\Form\Fieldset::setObject expects an object argument; received "Array"
Trace
#0 C:\projects\acuradoria-zend\vendor\zendframework\zendframework\library\Zend\Form\Element\Collection.php(549): Zend\Form\Fieldset->setObject(Array)
#1 C:\projects\acuradoria-zend\vendor\zendframework\zendframework\library\Zend\Form\Fieldset.php(601): Zend\Form\Element\Collection->extract()
#2 C:\projects\acuradoria-zend\vendor\zendframework\zendframework\library\Zend\Form\Form.php(854): Zend\Form\Fieldset->extract()
#3 C:\projects\acuradoria-zend\vendor\zendframework\zendframework\library\Zend\Form\Form.php(292): Zend\Form\Form->extract()
#4 C:\projects\acuradoria-zend\module\Bundle\src\Bundle\Controller\Plugin\FormService.php(42): Zend\Form\Form->bind(Object(Bundle\Entity\Metaproduct))
Please see this issue:
Problems in nested collections and fieldsets
https://github.com/zendframework/zf2/issues/5640