ZF2: FieldSet getInputFilterSpecification() gets called twice - php

getInputFilterSpecification() read twice for a fieldset when used with fileprg Controller plugin.
Basically I have a simple form with a single fieldset:
The Form:
class CreateEditReward extends ProvideEventsForm
{
public function __construct($name = null, $options = array())
{
parent::__construct($name ?: 'Reward', $options);
$this->add(array(
'name' => 'submit',
'type' => 'submit'
));
$this->add(array(
'name' => 'cancel',
'type' => 'button'
));
}
public function init()
{
parent::init();
$this->add(array(
'name' => 'reward',
'type' => 'MyAchievement\Form\RewardFieldset',
'options' => array(
'use_as_base_fieldset' => true
)
));
if (($listener = $this->get('reward')) instanceof ListenerAggregateInterface) {
/** #var $listener ListenerAggregateInterface */
$this->getEventManager()->attachAggregate($listener);
}
}
}
The form extends the most basic EventsCapable implmentation and is not related to the problem.
The Fieldset:
class RewardFieldset extends Fieldset implements
InputFilterProviderInterface,
ListenerAggregateInterface
{
/**
* #var RewardService
*/
protected $rewardService;
/**
* #var WebPathResolver
*/
protected $webPathResolver;
protected $listeners = array();
public function __construct(RewardService $rewardService, WebPathResolver $webPathResolver, $name = null, $options = array())
{
parent::__construct($name ?: 'Reward', $options);
$this->rewardService = $rewardService;
$this->webPathResolver = $webPathResolver;
//...
$this->add(array(
'name' => 'thumb',
'type' => 'file',
'options' => array(
'label' => 'Thumb'
),
'attributes' => array(
'id' => 'thumb',
'data-rel' => null
)
));
// .. more elts
}
/**
* Should return an array specification compatible with
* {#link Zend\InputFilter\Factory::createInputFilter()}.
*
* #return array
*/
public function getInputFilterSpecification()
{
return array(
// ... other elts input filters
'thumb' => array(
'required' => false,
'filters' => array(
array(
'name' => 'fileRenameUpload',
'options' => array(
'target' => './data/upload',
'overwrite' => true,
'randomize' => true,
'use_upload_name' => true
)
)
),
'validators' => array(
array(
'name' => 'fileMimeType',
'options' => array(
'image',
'enableHeaderCheck' => true
)
)
)
)
);
}
public function addThumbPreview(FormEvent $e)
{
/** #var $object Reward */
if (! ($object = $e->getObject()) instanceof Reward) {
return;
}
if ($object->getThumb()) {
$this->get('thumb')
->setAttribute('data-rel', $this->webPathResolver->getPath($object, $object->getThumb()));
}
}
/**
* Attach one or more listeners
*
* Implementors may add an optional $priority argument; the Eve\ntManager
* implementation will pass this to the aggregate.
*
* #param EventManagerInterface $events
*
* #return void
*/
public function attach(EventManagerInterface $events)
{
$this->listeners[] = $events->attach(FormEvent::EVENT_POST_BIND, array($this, 'addThumbPreview'));
}
/**
* Detach all previously attached listeners
*
* #param EventManagerInterface $events
*
* #return void
*/
public function detach(EventManagerInterface $events)
{
foreach ($this->listeners as $i => $listener) {
if ($events->detach($listener)) {
unset($this->listeners[$i]);
}
}
}
}
My controller's edit action:
public function editAction()
{
/** #var $request Request */
$request = $this->getRequest();
$back = $request->getQuery('back', $this->url()->fromRoute('admin/reward'));
/** #var $reward Reward */
if (null === $reward = $this->rewardService->fetchById($id = $this->params()->fromRoute('id'))) {
return $this->redirect()->toUrl($back);
}
$form = $this->getCreateEditForm();
$form->bind($reward);
if (($prg = $this->fileprg($form)) instanceof ResponseInterface) {
return $prg;
}
if (is_array($prg)) {
try {
if ($form->isValid()) {
$this->rewardService->updateReward($reward);
$this->flashMessenger()->addSuccessMessage('Changes saved');
$this->redirect()->toRoute('admin/reward',
array('action' => 'edit', 'id' => $id),
array('query' => array('back' => $back)));
} else {
/** #var $rewardFieldset FieldsetInterface */
$rewardFieldset = $form->get('reward');
/** #var $thumbElt ElementInterface */
$thumbElt = $rewardFieldset->get('thumb');
if (! $thumbElt->getMessages()) {
$reward->setThumb($thumbElt->getValue());
$this->rewardService->updateReward($reward);
}
}
} catch (\Exception $e) {
$this->flashMessenger()->addErrorMessage('Changes could not be saved');
return $this->redirect()->toUrl($back);
}
}
return new ViewModel(array(
'form' => $form,
'reward' => $reward,
'back' => $back
));
}
My module conf for the form:
/**
* Expected to return \Zend\ServiceManager\Config object or array to
* seed such an object.
*
* #return array|\Zend\ServiceManager\Config
*/
public function getFormElementConfig()
{
return array(
'invokables' => array(
'MyAchievement\Form\CreateEditReward' => 'MyAchievement\Form\CreateEditReward',
),
'factories' => array(
'MyAchievement\Form\RewardFieldset' => function (FormElementManager $fm) {
/** #var $rewardService RewardService */
$rewardService = $fm->getServiceLocator()->get('MyAchievement\Service\Reward');
/** #var $webPathResolver WebPathResolver */
$webPathResolver = $fm->getServiceLocator()->get('Application\Service\WebPathResolver');
$fieldset = new RewardFieldset($rewardService, $webPathResolver);
$fieldset->setHydrator(new ClassMethods());
return $fieldset;
}
)
);
}
The problem is the getInputFilterSpecifications() is called twice, thus everytime I try to upload a picture with my form I get
Zend\Filter\Exception\RuntimeException:
File './data/upload/my-thumb_5249d42bd582b.jpg' could not be renamed. An error occurred while processing the file.
That is because my filters run twice on the same thumbnail, the first time it is successful (I can even see the file uploaded to the temp dir).
Thanks.

Related

Cannot get value from $form_state in custom Drupal 8 Webform Handler

I am working in Drupal 8 and am building a custom WebformHandler. I have an element with an ajax component. I cannot seem to access any form values via $form_state->getValue('key') within the ajax callback (nor anywhere for that matter). I have been bashing my head against the wall for a while.
I've followed every guide that I can find on the internet, but to no success. My code is provided below.
<?php
namespace Drupal\campaign_monitor_transactional\Plugin\WebformHandler;
use Drupal\Core\Form\FormStateInterface;
use Drupal\samlauth\Element\MultiValue;
use Drupal\webform\Plugin\WebformHandlerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Test Campaign Monitor webform handler
*
* #WebformHandler(
* id = "campaign_monitor_transactional",
* label = #Translation("Campaign Montior Transactional"),
* category = #Translation("Campaign Monitor"),
* description = #Translation("Trigger Campaign Monitor Transaction Emails"),
* cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_UNLIMITED,
* results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
*
* )
*/
class TransactionalWebformHandler extends WebformHandlerBase {
/**
* Logger service
*
* #var \Drupal\Core\Logger\LoggerChannelFactory
*/
protected $loggerFactory;
/**
* The Campaign Monitor RESTCLient
*
* #var \Drupal\CampaignMonitorRestClientFactory
*/
protected $campaignMonitorRESTClient;
/**
* {#inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition)
{
$instance = parent::create(
$container,
$configuration,
$plugin_id,
$plugin_definition
);
// TODO webform_campaign_monitor may not be correct
$instance->loggerFactory = $container
->get('logger.factory')
->get('webform_campaign_monitor');
$instance->campaignMonitorRESTClient = $container
->get('campaign_monitor_rest_client');
return $instance;
}
/**
* {#inheritdoc}
*/
public function buildConfigurationForm(array $form, FormStateInterface $form_state)
{
// Campaign monitor settings
$form['template_settings'] = [
'#type' => 'details',
'#title' => $this->t('Template settings'),
'#open' => TRUE
];
# I am just using this for testing purposes
$form['example_select'] = [
'#type' => 'select',
'#title' => $this->t('Select element'),
'#options' => [
'1' => $this->t('One'),
'2' => $this->t('Two'),
'3' => $this->t('Three'),
]
];
$form['template_settings']['email_template'] = [
'#type' => 'select',
'#title' => $this->t('Email Template'),
'#options' => $this->getTransactionEmailOptions(),
'#ajax' => [
'callback' => [$this, 'fetchParamsCallback'],
'wrapper' => 'cm-param-textarea',
'progress' => [
'type' => 'throbber',
'message' => $this->t('Loading params...')
]
]
];
$form['template_settings']['params'] = [
'#type' => 'textarea',
'#title' => $this->t('Campaign Monitor Params'),
'#disabled' => True,
'#prefix' => '<div id="cm-param-textarea">',
'#suffix' => '</div>'
];
return $form;
}
/**
* {#inheritdoc}
*/
public function submitConfigurationForm(array &$form, FormStateInterface $form_state)
{
parent::submitConfigurationForm($form, $form_state);
$this->applyFormStateToConfiguration($form_state);
}
/**
* Loads Campaign Monitor params based on selected email template
*/
public function fetchParamsCallback(array &$form, FormStateInterface $form_state)
{
$smart_email_id = $form_state->getValue('example_select');
### ISSUE IS HERE.... $SMART_EMAIL_ID is blank
return [
'#type' => 'textfield',
'#size' => '60',
'#disabled' => TRUE,
'#value' => 'SEI: ' . $smart_email_id,
'#prefix' => '<div id="edit-output">',
'#suffix' => '</div>',
];
}
/**
* Helper function producing sender dropdown options
* #return array
* Options for sender dropdown
*/
protected function getSenderOptions()
{
return array(
'you' => 'Your Email',
'custom' => 'Custom email address(es)',
'author' => 'Webform author',
'none' => 'None'
);
}
/**
* Helper function to fetch all active transactional emails
*
* #return array
* Options for transactional email dropdown
*/
protected function getTransactionEmailOptions()
{
$options = array();
# TODO client ID should not be hard coded
$clientID = 'XXX';
$params = [
'query' => [
'status' => 'all',
'clientID' => $clientID
]
];
$email_templates = $this->campaignMonitorRESTClient
->get('transactional/smartEmail', $params)
->getBody()
->getContents();
foreach(json_decode($email_templates) as $template) {
$options[$template->ID] = $template->Name;
}
return $options;
}
}

Drupal 8 Custom Field // Primitive error

I see text field and ckeditor field on node edit page, but when i try to save node i receive "This value should be of the correct primitive type. " error.
<?php
namespace Drupal\custom_field\Plugin\Field\FieldType;
use Drupal\Core\Field\FieldItemBase;
use Drupal\Core\Field\FieldItemInterface;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\TypedData\DataDefinition;
/**
* Plugin implementation of the 'Program' field type.
*
* #FieldType(
* id = "program",
* label = #Translation("Programmation"),
* description = #Translation("Stores a Program n date string in various format"),
* default_widget = "program_default",
* default_formatter = "program_default",
* )
*/
class ProgramItem extends FieldItemBase implements FieldItemInterface {
public static function schema(FieldStorageDefinitionInterface $field_definition) {
return array(
'columns' => array(
'date' => array(
'description' => 'Programmation du jour.(date)',
'type' => 'varchar',
'length' => 255,
'size' => 'normal',
),
'programmation' => array(
'description' => 'Programmation. (Concerts)',
'type' => 'varchar',
'length' => 5000,
'size' => 'normal',
),
),
);
}
public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
$properties['date'] = DataDefinition::create('string')
->setLabel(t('Date du jour'));
$properties['programmation'] = DataDefinition::create('string')
->setLabel(t('Programmation du jour'));
return $properties;
}
public function isEmpty() {
$value = $this->get('date')->getValue();
return empty($value);
}
public static function mainPropertyName() {
return 'date';
}
}
<?php
namespace Drupal\custom_field\Plugin\Field\FieldWidget;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Field\WidgetBaseInterface;
use Drupal\Core\Form\FormStateInterface;
/**
* Plugin implementation of the 'Program' widget.
*
* #FieldWidget(
* id = "program_default",
* label = #Translation("Programmation"),
* field_types = {
* "program"
* }
* )
*/
class ProgramWidget extends WidgetBase implements WidgetBaseInterface {
/**
* #param FieldItemListInterface $items
* #param int $delta
* #param array $element
* #param array $form
* #param FormStateInterface $form_state
* #return array
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$element['date'] = array(
'#type' => 'textfield',
'#title' => $this->t('Date'),
'#placeholder' => $this->getSetting('placeholder_date'),
'#default_value' => isset($items[$delta]->date) ? $items[$delta]->date : NULL,
'#required' => $element['#required'],
);
$element['programmation'] = array(
'#type' => 'text_format',
'#title' => $this->t('Programmation'),
'#placeholder' => $this->getSetting('placeholder_programmation'),
'#default_value' => isset($items[$delta]->programmation) ? $items[$delta]->programmation : NULL,
'#format' => 'full_html',
);
$element['field_widget_display']['#access'] = true;
$element['field_widget_display_settings']['#access'] = true;
die('ProgramWidget');
return $element;
}
}
I saw that I could use the massageFormValues () method in WidgetBase, but I do not know how to use it.
A little help would be welcome.
Thank you
finaly i add to ProgramWidget :
/**
* {#inheritdoc}
*/
public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
foreach ($values as &$value) {
if (count($value['programmation'])) {
$value['programmation'] = $value['programmation']['value'];
} else {
$value['programmation'] = $value['programmation'] !== '' ? $value['programmation'] : '0';
}
}
return $values;
}
}
And now it s working
it seems because of
$element['programmation'] = array(
'#type' => 'text_format',
'#title' => $this->t('Programmation'),
'#placeholder' => $this->getSetting('placeholder_programmation'),
'#default_value' => isset($items[$delta]->programmation) ? $items[$delta]->programmation : NULL,
'#format' => 'full_html',
);
but i don't know how override method massageFormValues ..?

Custom validator not found by ValidatorPluginManager

I'm struggling with getting my custom validator to work.
The thing is I have a custom form element that uses a custom validator.
But when field is being created the ValidatorPluginManager fails to find my custom validator.
Now I know that it's a scope issue but I can' resolve it.
Error message:
A plugin by the name "AliasExists" was not found in the plugin manager Zend\Validator\ValidatorPluginManager
Validator code:
class AliasExists
extends AbstractValidator
implements AdapterAwareInterface
{
use AdapterAwareTrait;
const NOT_UNIQUE = 'notUnique';
/**
* Validation failure message templates definition
*
* #var array
*/
protected $messageTemplates = [
self::NOT_UNIQUE => "Entry with alias %value% already exists",
];
/**
* #var string
*/
protected $table;
/**
* #var Select
*/
protected $select;
/**
* #var string
*/
protected $categoryField = 'category';
/**
* #var int
*/
protected $categoryValue;
public function __construct($options)
{
parent::__construct($options);
if ($options instanceof Traversable) {
$options = ArrayUtils::iteratorToArray($options);
} elseif ($options instanceof Adapter) {
$temp = [];
$temp['adapter'] = $options;
$options = $temp;
} else {
if (func_num_args() > 1) {
$options = func_get_args();
$firstArgument = array_shift($options);
if (is_array($firstArgument)) {
$temp = ArrayUtils::iteratorToArray($firstArgument);
} else {
$temp['table'] = $firstArgument;
}
if (!empty($options)) {
$temp['adapter'] = array_shift($options);
}
$options = $temp;
}
}
if (array_key_exists('table', $options)) {
$this->setTable($options['table']);
}
if (array_key_exists('adapter', $options)) {
$this->setAdapter($options['adapter']);
}
}
public function isValid($value, $context = null)
{
if (null === $this->adapter) {
throw new \RuntimeException('No database adapter set.');
}
if (empty($this->table)) {
throw new \RuntimeException('Table has not been set.');
}
$valid = true;
$this->setValue($value);
if ($context) {
// TODO
}
$result = $this->query($value);
if (!$result) {
$valid = false;
$this->error(self::NOT_UNIQUE);
}
return $valid;
}
public function getSelect()
{
if ($this->select instanceof Select) {
return $this->select;
}
$select = new Select();
$table = new TableIdentifier($this->table);
$select->from($table);
$select->where->equalTo(
'alias',
null
);
if (!empty($this->categoryField) && !empty($this->categoryValue)) {
$select->where->equalTo(
$this->categoryField,
$this->categoryValue
);
}
$select->columns(['id']);
$this->select = $select;
return $this->select;
}
/**
* Returns the set adapter
*
* #return Adapter
*/
public function getAdapter(): Adapter
{
return $this->adapter;
}
/**
* Sets a (new) DB adapter
*
* #param Adapter $adapter
* #return self Provides a fluent interface
*/
public function setAdapter(Adapter $adapter)
{
return $this->setDbAdapter($adapter);
}
/**
* Returns the set table
*
* #return string
*/
public function getTable(): string
{
return $this->table;
}
/**
* Sets a (new) table
*
* #param string $table
* #return self Provides a fluent interface
*/
public function setTable(string $table)
{
$this->table = $table;
$this->select = null;
return $this;
}
/**
* #return string
*/
public function getCategoryField(): string
{
return $this->categoryField;
}
/**
* #param string $categoryField
*/
public function setCategoryField(string $categoryField)
{
$this->categoryField = $categoryField;
}
/**
* #return int
*/
public function getCategoryValue(): int
{
return $this->categoryValue;
}
/**
* #param int $categoryValue
*/
public function setCategoryValue(int $categoryValue)
{
$this->categoryValue = $categoryValue;
}
protected function query($value)
{
$sql = new Sql($this->getAdapter());
$select = $this->getSelect();
$statement = $sql->prepareStatementForSqlObject($select);
$parameters = $statement->getParameterContainer();
$parameters['where1'] = (string)$value;
$result = $statement->execute();
return $result->current();
}
}
Validator factory:
class AliasExistsFactory implements FactoryInterface
{
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
$db = $container->get(AdapterInterface::class);
return new AliasExists($db);
}
}
Custom form element code:
class Alias
extends Text
implements InputProviderInterface
{
protected $attributes = [
'name' => 'alias',
'required' => 'required',
'class' => 'form-control',
];
protected $label = 'Alias';
public function __construct($name = null, array $options = [])
{
parent::__construct($name, $options);
$this->setAttribute('id', $this->getName());
}
public function getInputSpecification()
{
return [
'name' => $this->getName(),
'required' => true,
'filters' => [
['name' => 'StringTrim'],
['name' => 'StringToLower'],
],
'validators' => [
[
'name' => 'NotEmpty',
'options' => [
'type' => 'string'
],
],
[
'name' => 'Regex',
'options' => [
'pattern' => '/^[0-9a-zA-Z-_]+$/',
'messages' => [
Regex::NOT_MATCH => 'Only numbers, underscore, dash and characters from A to Z are allowed'
],
],
],
[
'name' => 'StringLength',
'options' => [
'min' => 1,
'max' => 255
],
],
[
'name' => 'AliasExists', <--- Custom validator
]
],
];
}
}
module.config.php
'form_elements' => [
'factories' => [
Form\Element\Alias::class => InvokableFactory::class,
],
],
'validators' => [
'factories' => [
Validator\AliasExists::class => Factory\AliasExistsFactory::class,
],
'aliases' => [
'AliasExists' => Validator\AliasExists::class,
]
]
Controller factory that instantiates form that has this custom field:
class EditControllerFactory implements FactoryInterface
{
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
$formManager = $container->get('FormElementManager');
$form = $formManager->get(ArticleForm::class);
return new EditController($form);
}
}
The only way I can get my custom validator to work is (as found in this answer Possible to create a factory to instantiate custom Form validators?) is to set validator chain in controller factory that instantiates form but its an overkill to have to do this in every controller factory that could possibly have a form that uses this field that has custom validator in it.

I want to Add attachment on ZendF2 Email but I cant understand what I do with following code?

Following is the code which I am using for sending email but tell me How I can add attachement with this ??Following is the code which I am using for sending email but tell me How I can add attachement with this ??
<?php
namespace Application\Controller;
use Application\Filter\DomainFilter;
use Application\Form\DomainForm;
use Application\Form\SendForm;
use Application\Model\AccountModel;
use Application\Model\CustomersModel;
use Application\Model\DomainModel;
use Application\Model\UploadModel;
use Application\Service\Demo;
use Zend\Crypt\BlockCipher;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
/**
* Class DomainController
* #package Application\Controller
*/
class DomainController extends AbstractActionController
{
/**
* #var DomainModel
*/
protected $_DomainModel;
/**
* #var DomainForm
*/
protected $_DomainForm;
/**
* #var SendForm
*/
protected $_SendForm;
/**
* #var AccountModel
*/
protected $_AccountModel;
/**
* #var UploadModel
*/
protected $_UploadModel;
/**
* #var CustomersModel
*/
protected $_CustomersModel;
/**
* #var SettingModel
*/
protected $_SettingModel;
/**
* #var Demo
*/
protected $_Demo;
/**
* #param \Application\Service\Demo $Demo
*/
public function setDemo($Demo)
{
$this->_Demo = $Demo;
}
/**
* #return \Application\Service\Demo
*/
public function getDemo()
{
return $this->_Demo;
}
/**
* #param \Application\Model\CustomersModel $CustomersModel
*/
public function setCustomersModel($CustomersModel)
{
$this->_CustomersModel = $CustomersModel;
}
/**
* #return \Application\Model\CustomersModel
*/
public function getCustomersModel()
{
return $this->_CustomersModel;
}
/**
* #param \Application\Model\UploadModel $UploadModel
*/
public function setUploadModel($UploadModel)
{
$this->_UploadModel = $UploadModel;
}
/**
* #return \Application\Model\UploadModel
*/
public function getUploadModel()
{
return $this->_UploadModel;
}
/**
* #param \Application\Form\DomainForm $DomainForm
*/
public function setDomainForm($DomainForm)
{
$this->_DomainForm = $DomainForm;
}
/**
* #return \Application\Form\DomainForm
*/
public function getDomainForm()
{
return $this->_DomainForm;
}
/**
* #param \Application\Model\DomainModel $DomainModel
*/
public function setDomainModel($DomainModel)
{
$this->_DomainModel = $DomainModel;
}
/**
* #return \Application\Model\DomainModel
*/
public function getDomainModel()
{
return $this->_DomainModel;
}
/**
* #param \Application\Model\AccountModel $AccountModel
*/
public function setAccountModel($AccountModel)
{
$this->_AccountModel = $AccountModel;
}
/**
* #return \Application\Model\AccountModel
*/
public function getAccountModel()
{
return $this->_AccountModel;
}
/**
* #return the $_SendForm
*/
public function getSendForm()
{
return $this->_SendForm;
}
/**
* #param field_type $_SendForm
*/
public function setSendForm($_SendForm)
{
$this->_SendForm = $_SendForm;
}
/**
* #param mixed $SettingModel
*/
public function setSettingModel($SettingModel)
{
$this->_SettingModel = $SettingModel;
}
/**
* #return mixed
*/
public function getSettingModel()
{
return $this->_SettingModel;
}
/**
* Domain
* #return array|ViewModel
*/
public function indexAction()
{
return new ViewModel(array(
'domain' => $this->getDomainModel()->getList(),
'message' => $this->flashMessenger()->getMessages()
));
}
/**
* Add Domain
* #return \Zend\Http\Response|ViewModel
*/
public function addAction()
{
$request = $this->getRequest();
$form = $this->getDomainForm();
$form->setData(array('expired' => date('d/m/Y', strtotime('+1 year'))));
$Adapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
$BC = $this->getServiceLocator()->get('block_cipher');
$blockCipher = BlockCipher::factory('mcrypt', array('algo' => $BC['algo']));
$blockCipher->setKey($this->ApiKey()->getApiKey());
if (true === $request->isPost()) {
$post = $request->getPost()->toArray();
$form->setData($post);
$form->setInputFilter(new DomainFilter($Adapter, 0));
if (true === $form->isValid()) {
$post['created'] = date('Y-m-d H:i:s');
$post['expired'] = date('Y-m-d', $this->FormatDates()->getDateToMkTime($post['expired']));
$post['pwd_ftp'] = $blockCipher->encrypt($post['pwd_ftp']);
$this->getDomainModel()->insert($post);
$this->flashMessenger()->addMessage(array('success', 1));
return $this->redirect()->toRoute('domain');
}
}
return new ViewModel(array(
'form' => $form
));
}
/**
* Edit Domain
* #return \Zend\Http\Response|ViewModel
*/
public function editAction()
{
$ID = (int)$this->params()->fromRoute('id', 0);
$row = $this->getDomainModel()->find(array('d.id' => $ID));
$Adapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
$BC = $this->getServiceLocator()->get('block_cipher');
$blockCipher = BlockCipher::factory('mcrypt', array('algo' => $BC['algo']));
$blockCipher->setKey($this->ApiKey()->getApiKey());
if (empty($row)) {
$this->getResponse()->setStatusCode(404);
return;
}
$request = $this->getRequest();
$form = $this->getDomainForm();
$row['pwd_ftp'] = $blockCipher->decrypt($row['pwd_ftp']);
$row['expired'] = date('d/m/Y', strtotime($row['expired']));
$form->setData($row);
if (true === $request->isPost()) {
$post = $request->getPost()->toArray();
$form->setData($post);
$form->setInputFilter(new DomainFilter($Adapter, $ID));
if (true === $form->isValid()) {
$post['expired'] = date('Y-m-d', $this->FormatDates()->getDateToMkTime($post['expired']));
$post['pwd_ftp'] = $blockCipher->encrypt($post['pwd_ftp']);
$this->getDomainModel()->update($ID, $post);
$this->flashMessenger()->addMessage(array('success', 1));
return $this->redirect()->toRoute('domain');
}
}
return new ViewModel(array(
'form' => $form
));
}
/**
* Delete Domain / Account
* #return \Zend\Http\Response
*/
public function deleteAction()
{
$ID = (int)$this->params()->fromRoute('id', 0);
$this->getDomainModel()->delete($ID);
$this->getAccountModel()->deleteAllByDomain($ID);
$this->getUploadModel()->deleteAllByDomain($ID);
$this->flashMessenger()->addMessage(array('success', 1));
return $this->redirect()->toRoute('domain');
}
/**
* Detaglio Domain
* #return ViewModel
*/
public function detailAction()
{
$ID = (int)$this->params()->fromRoute('id', 0);
$domain = $this->getDomainModel()->find(array('d.id' => $ID));
if (empty($domain)) {
$this->getResponse()->setStatusCode(404);
return;
}
return new ViewModel(array(
'domain' => $domain,
'account' => $this->getAccountModel()->getList(array('a.id_domain' => $ID)),
'upload' => $this->getUploadModel()->getList(array('id_domain' => $ID)),
'type_ftp' => $this->getServiceLocator()->get('type_ftp')
));
}
/**
* Send Domain
* #return \Zend\Http\Response|ViewModel
*/
public function sendAction()
{
$ID = (int)$this->params()->fromRoute('id', 0);
$domain = $this->getDomainModel()->find(array('d.id' => $ID));
$request = $this->getRequest();
$BC = $this->getServiceLocator()->get('block_cipher');
$blockCipher = BlockCipher::factory('mcrypt', array('algo' => $BC['algo']));
$blockCipher->setKey($this->ApiKey()->getApiKey());
if (empty($domain)) {
$this->getResponse()->setStatusCode(404);
return;
}
if (true === $request->isPost()) {
$post = $request->getPost()->toArray();
$array_email = array();
if (isset($post['info_domain'])) {
$array_email['info_domain'] = array(
'fullname' => $domain['fullname'],
'url' => $domain['url'],
'auth_code' => $domain['auth_code'],
'name_provider' => $domain['name_provider'],
'name_hosting' => $domain['name_hosting'],
'name_server' => $domain['name_server']
);
}
if (isset($post['hosting_info'])) {
$pwd_ftp = !empty($domain['pwd_ftp']) ? $blockCipher->decrypt($domain['pwd_ftp']) : '';
$array_email['hosting_info'] = array(
'fullname' => $domain['fullname'],
'url' => $domain['url'],
'pwd_ftp' => $pwd_ftp,
'port_ftp' => $domain['port_ftp'],
'name_hosting' => $domain['name_hosting'],
'name_server' => $domain['name_server']
);
}
if (isset($post['ftp'])) {
$pwd_ftp = !empty($domain['pwd_ftp']) ? $blockCipher->decrypt($domain['pwd_ftp']) : '';
$array_email['ftp'] = array(
'host_ftp' => $domain['host_ftp'],
'user_ftp' => $domain['user_ftp'],
'pwd_ftp' => $pwd_ftp,
'port_ftp' => $domain['port_ftp'],
);
}
if (isset($post['email_info'])) {
$array_email['email_info'] = array(
'fullname' => $domain['fullname'],
'url' => $domain['url']
);
}
if (isset($post['account']) && is_array($post['account'])) {
$cnt = 0;
foreach ($post['account'] as $key => $value) {
$info_account = $this->getAccountModel()->find(array(
'a.id' => $value
));
$pwd = !empty($info_account['pwd']) ? $blockCipher->decrypt($info_account['pwd']) : '';
$array_email['account'][$cnt] = array(
'name_type_account' => $info_account['name_type_account'],
'usermail' => $info_account['usermail'],
'pwd' => $pwd,
'info' => $info_account['info'],
);
$cnt++;
}
}
if (isset($post['note'])) {
$array_email['note'] = $post['note'];
}
$sm = $this->getServiceLocator()->get('ServiceManager');
$translate = $sm->get('ViewHelperManager')->get('translate');
$setting = $this->getSettingModel()->find(array(
'id' => $this->WebStudioAuthentication()->getIdentity()
));
$view = new ViewModel(array(
'data' => $array_email,
));
$view->setTerminal(true);
$view->setTemplate(sprintf('Application/view/email/send_data_%s', $setting['language']));
if ($this->getDemo()->getSendEmail() === true) {
$this->mailerZF2()->send(array(
'to' => $post['email'],
'cc' => $post['usermail'],
'subject' => $translate('label_86', null, $setting['language']),
), $view);
}
$this->flashMessenger()->addMessage(array('success', 1));
return $this->redirect()->toRoute('domain/default', array('action' => 'send', 'id' => $ID));
}
return new ViewModel(array(
'demo' => $this->getDemo()->getShowMessage(),
'domain' => $domain,
'datalist' => $this->getCustomersModel()->getList(),
'form' => $this->getSendForm(),
'account' => $this->getAccountModel()->getList(array('a.id_domain' => $ID)),
'message' => $this->flashMessenger()->getMessages()
));
}
}
Here is the send form Code
<?php
namespace Application\Form;
use Zend\Form\Form;
/**
* Class SendForm
* #package Application\Form
*/
class SendForm extends Form
{
/**
* #param string $name
*/
public function __construct($name = '')
{
parent::__construct($name);
$this->setAttribute('method', 'post');
$this->setAttribute('class', 'bottom-margin');
$this->setAttribute('autocomplete', 'off');
$this->setAttribute('id', 'validateForm');
$this->add(array(
'name' => 'email',
'type' => 'Zend\Form\Element\Text',
'attributes' => array(
'class' => 'form-control',
'required' => 'required',
'list' => 'customers',
),
));
$this->add(array(
'name' => 'note',
'type' => 'Zend\Form\Element\Textarea',
'attributes' => array(
'class' => 'form-control',
)
));
}
}

Unrecognized field: user_name, while querying Via Doctrine using ZF2

here is the snippet to my code when i try to query it like this
if ($request->isPost()) {
$form->setData($request->getPost());
if ($form->isValid()) {
//check authentication...
$this->getAuthService()->getAdapter()
->setIdentity($request->getPost('username'))
->setCredential($request->getPost('password'));
$username = $request->getPost('username');
$password = $request->getPost('password');
$result = $this->getAuthService()->authenticate();
$criteria = array("user_name" => $username,);
$results= $this->getEntityManager()->getRepository('Subject\Entity\User')->findBy($criteria);
print_r($results);
exit;
i get the following error
Unrecognized field: user_name
These are my includes
Use Doctrine\ORM\EntityManager,
Album\Entity\Album;
Edit: this is my Subject\Entity\User file
<?php
namespace Subject\Entity;
use Doctrine\ORM\Mapping as ORM;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\Factory as InputFactory;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;
/**
* #ORM\Entity
* #ORM\Table(name="users")
* #property string $username
* #property string $password
* #property int $id
*/
class User implements InputFilterAwareInterface {
protected $_username;
protected $_password;
/**
* #ORM\OneToMany(targetEntity="Subject\Entity\Subject", mappedBy="user")
* #var Collection
*/
private $subjects;
/** #ORM\Id() #ORM\Column(type="integer") #ORM\GeneratedValue(strategy="AUTO") #var int */
protected $_id;
public function __get($property) {
return $this->$property;
}
public function __set($property, $value) {
$this->$property = $value;
}
//Getters and setters
/** #return Collection */
public function getSubjects() {
return $this->subjects;
}
/** #param Comment $comment */
public function addSubject(Subject $subjects) {
$this->subjects->add($subjects);
$subjects->setUser($this);
}
public function __construct($subjects) {
//Initializing collection. Doctrine recognizes Collections, not arrays!
$this->subjects = new ArrayCollection();
}
public function getArrayCopy() {
return get_object_vars($this);
}
public function populate($data = array()) {
$this->_id = $data['id'];
$this->_username = $data['username'];
$this->_password = $data['password'];
}
public function setInputFilter(InputFilterInterface $inputFilter) {
throw new \Exception("Not used");
}
public function getInputFilter() {
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
$factory = new InputFactory();
$inputFilter->add($factory->createInput(array(
'name' => 'id',
'required' => true,
'filters' => array(
array('name' => 'Int'),
),
)));
$inputFilter->add($factory->createInput(array(
'name' => 'username',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 1,
'max' => 100,
),
),
),
)));
$inputFilter->add($factory->createInput(array(
'name' => 'password',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 1,
'max' => 100,
),
),
),
)));
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
//put your code here
}
?>
You are querying for the wrong field. The field is named _username in your entity class. Also check you annotations, _username and _password seem to not have any so they won't be created as database fields.
If you set up your entity correctly and all fields are in database you just need to query for your _username property:
if ($request->isPost()) {
$form->setData($request->getPost());
$repo = $this->getEntityManager()->getRepository('Subject\Entity\User');
if ($form->isValid()) {
// snip ...
$criteria = array("_username" => $username,);
$results= $repo->findBy($criteria);
print_r($results);
exit;
}
}
You user entity should look something like:
class User implements InputFilterAwareInterface {
/**
* #ORM\Column(name="username", type="string", length=64, unique=true)
*/
protected $_username;
/**
* #ORM\Column(name="password", type="string", length=64)
*/
protected $_password;
// snip ...
}
You may take a look at the PSR-2 standards. Underscores in method and variable names are discouraged by now.

Categories