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;
}
}
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',
)
));
}
}
I am using zendframework 2 and doctrine 2. My addAction doesn't work i don't have any error but when i valid my form no row created in my database !!
i think that i have problem in populating foreign key !
this is my Form:
<?php
// filename : module/Users/src/Users/Form/addForm.php
namespace Vehicules\Form;
use Zend\Form\Form;
use DoctrineModule\Persistence\ObjectManagerAwareInterface;
use Doctrine\Common\Persistence\ObjectManager;
class VehiculeForm extends form implements ObjectManagerAwareInterface
{
protected $objectManager;
public function setObjectManager(ObjectManager $objectManager)
{
$this->objectManager = $objectManager;
}
public function getObjectManager()
{
return $this->objectManager;
}
//public function init()
public function __construct(ObjectManager $objectManager)
{
parent::__construct('add');
$this->objectManager = $objectManager;
$this->init();
}
public function init(){
$this->setAttribute('method', 'post');
$this->setAttribute('enctype','multipart/formdata');
$this->add(array(
'name' => 'matricule',
'attributes' => array(
'type' => 'text',
'required' => true
),
'options' => array(
'label' => 'Matricule',
),
));
$this->add(array(
'type' => 'Zend\Form\Element\Select',
'name' => 'carburant',
'options' => array(
'label' => 'Carburant',
'value_options' => array(
'0' => 'Essence',
'1' => 'Gasoil',
'2' => 'Hybride',
),
)
));
$this->add(array(
'type' => 'DoctrineModule\Form\Element\ObjectMultiCheckbox',
'name' => 'option',
'options' => array(
'label' => 'Options Véhicule',
'object_manager' => $this->getObjectManager(),
'target_class' => 'Vehicules\Entity\optionsvehicule',
'property' => 'libellee',
)));
$this->add(array(
'type' => 'DoctrineModule\Form\Element\ObjectSelect',
'name' => 'categorie',
'options' => array(
'label' => 'categorie',
'object_manager' => $this->getObjectManager(),
'target_class' => 'Vehicules\Entity\categorie',
'property' => 'idcat',
)
));
$this->add(array(
'type' => 'DoctrineModule\Form\Element\ObjectSelect',
'name' => 'modele',
'options' => array(
'label' => 'Modèle',
'object_manager' => $this->getObjectManager(),
'target_class' => 'Vehicules\Entity\modele',
'property' => 'nom',
)
));
/*$this->add(array(
'type' => 'DoctrineModule\Form\Element\ObjectSelect',
'name' => 'modele',
'options' => array(
'label' => 'Modèle',
'object_manager' => $this->getObjectManager(),
'target_class' => 'Vehicules\Entity\modele',
'property' => 'nom',
'is_method' => true,
'find_method' => array(
'name' => 'findBy',
'params' => array(
'criteria' => array('active' => 1),
// Use key 'orderBy' if using ORM
'orderBy' => array('lastname' => 'ASC'),
// Use key 'sort' if using ODM
'sort' => array('lastname' => 'ASC')
),
),
),
));*/
$this->add(array(
'type' => 'DoctrineModule\Form\Element\ObjectSelect',
'name' => 'marque',
'options' => array(
'label' => 'Marque',
'object_manager' => $this->getObjectManager(),
'target_class' => 'Vehicules\Entity\marque',
'property' => 'nom',
)
));
$this->add(array(
'name' => 'dateMiseCirculation',
'attributes' => array(
'type' => 'Zend\Form\Element\Date',
),
'options' => array(
'label' => 'Date de Mise en Circulation',
),
));
$this->add(array(
'name' => 'numChasis',
'attributes' => array(
'type' => 'text',
),
'options' => array(
'label' => 'Numero de Chasis',
),
));
$this->add(array(
'name' => "Prix d'achat",
'attributes' => array(
'type' => 'int',
),
'options' => array(
'label' => "Prix d'achat",
),
));
$this->add(array(
'name' => 'concessionnaire',
'attributes' => array(
'type' => 'text',
),
'options' => array(
'label' => 'concessionnaire',
),
));
$this->add(array(
'name' => 'souslocation',
'attributes' => array(
'type' => 'string',
),
'options' => array(
'label' => 'Sous-location',
),
));
$this->add(array(
'name' => 'remarque',
'attributes' => array(
'type' => 'text',
),
'options' => array(
'label' => 'remarque',
),
));
$this->add(array(
'name' => 'puisfiscal',
'attributes' => array(
'type' => 'int',
),
'options' => array(
'label' => "puissance fiscale",
),
));
$this->add(array(
'type' => 'Zend\Form\Element\Select',
'name' => 'nbreport',
'options' => array(
'label' => 'Nombre de portes',
'value_options' => array(
'0' => '4',
'1' => '2',
'2' => '5',
'3' => '6',
'4' => '7',
'5' => '7',
),
)
));
$this->add(array(
'name' => 'dernierKm',
'attributes' => array(
'type' => 'text',
),
'options' => array(
'label' => 'Dernier kilométrage',
),
));
$this->add(array(
'name' => 'submit',
'attributes' => array(
'type' => 'submit',
'value' => 'Valider'
),
));
}}
and this is my Entity Vehicule:
<?php
namespace Vehicules\Entity;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterInterface;
use Zend\InputFilter\Factory as InputFactory;
use Doctrine\ORM\Mapping as ORM;
/**
* Vehicule
*
* #ORM\Table(name="vehicule", uniqueConstraints={#ORM\UniqueConstraint(name="VEHICULE_PK", columns={"idVeh"})}, indexes={#ORM\Index(name="ASSOCIATION11_FK", columns={"idCat"}), #ORM\Index(name="ASSOCIATION13_FK", columns={"idMod"})})
* #ORM\Entity
*/
class Vehicule
{ protected $inputFilter;
/**
* #var integer
*
* #ORM\Column(name="idVeh", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $idveh;
/**
* #var string
*
* #ORM\Column(name="matricule", type="string", length=254, nullable=false)
*/
private $matricule;
/**
* #var string
*
* #ORM\Column(name="dateMiseCirculation", type="string", length=254, nullable=true)
*/
private $datemisecirculation;
/**
* #var string
*
* #ORM\Column(name="numChasis", type="string", length=254, nullable=false)
*/
private $numchasis;
/**
* #var string
*
* #ORM\Column(name="carburant", type="string", length=254, nullable=true)
*/
private $carburant;
/**
* #var string
*
* #ORM\Column(name="dernierKm", type="decimal", precision=10, scale=0, nullable=false)
*/
private $dernierkm;
/**
* #var integer
*
* #ORM\Column(name="prixachat", type="integer", precision=10, scale=0, nullable=false)
*/
private $prixachat;
/**
* #var string
*
* #ORM\Column(name="concessionnaire", type="string", length=254, nullable=true)
*/
private $concessionnaire;
/**
* #var integer
*
* #ORM\Column(name="sousLocation", type="smallint", nullable=true)
*/
private $souslocation;
/**
* #var string
*
* #ORM\Column(name="remarque", type="string", length=254, nullable=true)
*/
private $remarque;
/**
* #var integer
*
* #ORM\Column(name="puisFiscal", type="integer", nullable=true)
*/
private $puisfiscal;
/**
* #var integer
*
* #ORM\Column(name="nbrePort", type="integer", nullable=true)
*/
private $nbreport;
/**
* #var \Vehicules\Entity\Categorie
*
* #ORM\ManyToOne(targetEntity="Vehicules\Entity\Categorie")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="idCat", referencedColumnName="idCat")
* })
*/
private $idcat;
/**
* #var \Vehicules\Entity\Modele
*
* #ORM\ManyToOne(targetEntity="Vehicules\Entity\Modele")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="idMod", referencedColumnName="idMod")
* })
*/
private $idmod;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="Vehicules\Entity\Optionsvehicule", inversedBy="idveh")
* #ORM\JoinTable(name="veh_option",
* joinColumns={
* #ORM\JoinColumn(name="idVeh", referencedColumnName="idVeh")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="idOptVeh", referencedColumnName="idOptVeh")
* }
* )
*/
private $idoptveh;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="Vehicules\Entity\Vehiculestatut", inversedBy="idveh")
* #ORM\JoinTable(name="veh_status",
* joinColumns={
* #ORM\JoinColumn(name="idVeh", referencedColumnName="idVeh")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="idStatut", referencedColumnName="idStatut")
* }
* )
*/
private $idstatut;
/**
* Constructor
*/
public function __construct()
{
$this->idoptveh = new \Doctrine\Common\Collections\ArrayCollection();
$this->idstatut = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get idveh
*
* #return integer
*/
public function getIdveh()
{
return $this->idveh;
}
/**
* Set matricule
*
* #param string $matricule
* #return Vehicule
*/
public function setMatricule($matricule)
{
$this->matricule = $matricule;
return $this;
}
/**
* Get matricule
*
* #return string
*/
public function getMatricule()
{
return $this->matricule;
}
/**
* Set datemisecirculation
*
* #param string $datemisecirculation
* #return Vehicule
*/
public function setDatemisecirculation($datemisecirculation)
{
$this->datemisecirculation = $datemisecirculation;
return $this;
}
/**
* Get datemisecirculation
*
* #return string
*/
public function getDatemisecirculation()
{
return $this->datemisecirculation;
}
/**
* Set numchasis
*
* #param string $numchasis
* #return Vehicule
*/
public function setNumchasis($numchasis)
{
$this->numchasis = $numchasis;
return $this;
}
/**
* Get numchasis
*
* #return string
*/
public function getNumchasis()
{
return $this->numchasis;
}
/**
* Set carburant
*
* #param string $carburant
* #return Vehicule
*/
public function setCarburant($carburant)
{
$this->carburant = $carburant;
return $this;
}
/**
* Get carburant
*
* #return string
*/
public function getCarburant()
{
return $this->carburant;
}
/**
* Set dernierkm
*
* #param string $dernierkm
* #return Vehicule
*/
public function setDernierkm($dernierkm)
{
$this->dernierkm = $dernierkm;
return $this;
}
/**
* Get dernierkm
*
* #return string
*/
public function getDernierkm()
{
return $this->dernierkm;
}
/**
* Set prixachat
*
* #param integer $prixachat
* #return Vehicule
*/
public function setPrixachat($prixachat)
{
$this->prixachat = $prixachat;
return $this;
}
/**
* Get prixachat
*
* #return integer
*/
public function getPrixachat()
{
return $this->prixachat;
}
/**
* Set concessionnaire
*
* #param string $concessionnaire
* #return Vehicule
*/
public function setConcessionnaire($concessionnaire)
{
$this->concessionnaire = $concessionnaire;
return $this;
}
/**
* Get concessionnaire
*
* #return string
*/
public function getConcessionnaire()
{
return $this->concessionnaire;
}
/**
* Set souslocation
*
* #param integer $souslocation
* #return Vehicule
*/
public function setSouslocation($souslocation)
{
$this->souslocation = $souslocation;
return $this;
}
/**
* Get souslocation
*
* #return integer
*/
public function getSouslocation()
{
return $this->souslocation;
}
/**
* Set remarque
*
* #param string $remarque
* #return Vehicule
*/
public function setRemarque($remarque)
{
$this->remarque = $remarque;
return $this;
}
/**
* Get remarque
*
* #return string
*/
public function getRemarque()
{
return $this->remarque;
}
/**
* Set puisfiscal
*
* #param integer $puisfiscal
* #return Vehicule
*/
public function setPuisfiscal($puisfiscal)
{
$this->puisfiscal = $puisfiscal;
return $this;
}
/**
* Get puisfiscal
*
* #return integer
*/
public function getPuisfiscal()
{
return $this->puisfiscal;
}
/**
* Set nbreport
*
* #param integer $nbreport
* #return Vehicule
*/
public function setNbreport($nbreport)
{
$this->nbreport = $nbreport;
return $this;
}
/**
* Get nbreport
*
* #return integer
*/
public function getNbreport()
{
return $this->nbreport;
}
/**
* Set idcat
*
* #param \Vehicules\Entity\Categorie $idcat
* #return Vehicule
*/
public function setIdcat(\Vehicules\Entity\Categorie $idcat = null)
{
$this->idcat = $idcat;
return $this;
}
/**
* Get idcat
*
* #return \Vehicules\Entity\Categorie
*/
public function getIdcat()
{
return $this->idcat;
}
/**
* Set idmod
*
* #param \Vehicules\Entity\Modele $idmod
* #return Vehicule
*/
public function setIdmod(\Vehicules\Entity\Modele $idmod = null)
{
$this->idmod = $idmod;
return $this;
}
/**
* Get idmod
*
* #return \Vehicules\Entity\Modele
*/
public function getIdmod()
{
return $this->idmod;
}
/**
* Add idoptveh
*
* #param \Vehicules\Entity\Optionsvehicule $idoptveh
* #return Vehicule
*/
public function addIdoptveh(\Vehicules\Entity\Optionsvehicule $idoptveh)
{
$this->idoptveh[] = $idoptveh;
return $this;
}
/**
* Remove idoptveh
*
* #param \Vehicules\Entity\Optionsvehicule $idoptveh
*/
public function removeIdoptveh(\Vehicules\Entity\Optionsvehicule $idoptveh)
{
$this->idoptveh->removeElement($idoptveh);
}
/**
* Get idoptveh
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getIdoptveh()
{
return $this->idoptveh;
}
/**
* Add idstatut
*
* #param \Vehicules\Entity\Vehiculestatut $idstatut
* #return Vehicule
*/
public function addIdstatut(\Vehicules\Entity\Vehiculestatut $idstatut)
{
$this->idstatut[] = $idstatut;
return $this;
}
/**
* Remove idstatut
*
* #param \Vehicules\Entity\Vehiculestatut $idstatut
*/
public function removeIdstatut(\Vehicules\Entity\Vehiculestatut $idstatut)
{
$this->idstatut->removeElement($idstatut);
}
/**
* Get idstatut
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getIdstatut()
{
return $this->idstatut;
}
public function populate($data) {
$this->setMatricule($data['matricule']) ;
$this->setDatemisecirculation($data['dateMiseCirculation']) ;
$this->setNumchasis($data['numChasis']) ;
$this->setCarburant($data['carburant']) ;
$this->setDernierkm($data['dernierKm']) ;
$this->setPrixachat($data["Prix d'achat"]) ;
$this->setConcessionnaire($data['concessionnaire']) ;
$this->setSouslocation($data['souslocation']) ;
$this->setRemarque($data['remarque']) ;
$this->setPuisfiscal($data['puisfiscal']) ;
$this->setNbreport($data['nbreport']) ;
//$this->addIdoptveh($data['option']) ; /* select................*/
//$this->setIdmod() ; /* select................*/
//$this->addIdstatut() ; /*ghanakhd l option dyal libre */
}
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' => 'matricule',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 4,
'max' => 14,
),
),
),
)));
$inputFilter->add($factory->createInput(array(
'name' => 'option',
'required' => false,
)));
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
public function getArrayCopy()
{
return get_object_vars($this);
}
}
this is my controller VehiculeController:
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* #link http://github.com/zendframework/Vehicules for the canonical source repository
* #copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* #license http://framework.zend.com/license/new-bsd New BSD License
*
*/
namespace Vehicules\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Vehicules\Form\VehiculeForm;
use Vehicules\Entity\Vehicule;
class VehiculesController extends AbstractActionController
{
/**
* #var Doctrine\ORM\EntityManager
*/
protected $_objectManager;
protected function getObjectManager()
{
if (!$this->_objectManager) {
$this->_objectManager = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
}
return $this->_objectManager;
}
public function indexAction()
{
$vehicules = $this->getObjectManager()->getRepository('Vehicules\Entity\Vehicule')->findAll();
return new ViewModel(array('vehicules' => $vehicules));
}
public function addAction()
{ $_objectManager=$this->getObjectManager();
$form = new VehiculeForm($_objectManager);
$request = $this->getRequest();
$post = $this->request->getPost();
if ($this->request->isPost()) {
$Vehicule= new Vehicule();
$form->setData($post);
$form->setInputFilter($Vehicule->getInputFilter());
if ($form->isValid()) {
$f=$form->getData();
$Vehicule->populate($f);
$cat = $this->getObjectManager()->getRepository('Vehicules\Entity\categorie')->findAll();
foreach ($cat as $c){
if($c->getIdcat()==$f['categorie'] ){
$Vehicule->setIdcat($c) ;
exit;
}
}
$mod = $this->getObjectManager()->getRepository('Vehicules\Entity\modele')->findAll();
foreach ($mod as $m){
if($m->getNom()==$f['modele'] ){
$Vehicule->setIdmod($m->getIdmod()) ;
exit;
}
}
$objectManager = $this->getObjectManager();
$objectManager->persist($Vehicule);
$objectManager->flush();
$id=$Vehicule->getIdveh();
var_dump($id);
$viewModel = new ViewModel(array('form' =>$form,'donne'=>$id));
return $viewModel;
}
}
$viewModel = new ViewModel(array('form' =>$form));
return $viewModel;
}
public function editAction()
{
$id = (int) $this->getEvent()->getRouteMatch()->getParam('id');
if (!$id) {
return $this->redirect()->toRoute('vehicules/default', array('controller'=>'vehicules','action'=>'add'));
}
$vehicule = $this->getObjectManager()->find('Vehicules\Entity\vehicule', $id);
$objectManager= $this->getObjectManager();
$form = new VehiculeForm($objectManager);
$form->setBindOnValidate(false);
$form->bind($vehicule);
$request = $this->getRequest();
if ($request->isPost()) {
$form->setData($request->post());
if ($form->isValid()) {
$form->bindValues();
$this->getEntityManager()->flush();
// Redirect to list of vehicules
return $this->redirect()->toRoute('vehicules/default', array('controller'=>'vehicules','action'=>'index'));
}
}
return array(
'id' => $id,
'form' => $form,
);
}
public function deleteAction()
{
$id = (int)$this->getEvent()->getRouteMatch()->getParam('idVeh');
if (!$id) {
return $this->redirect()->toRoute('vehicules');
}
$request = $this->getRequest();
if ($request->isPost()) {
$del = $request->post()->get('del', 'No');
if ($del == 'Yes') {
$id = (int)$request->post()->get('id');
$vehicule = $this->getEntityManager()->find('Vehicules\Entity\vehicule', $id);
if ($vehicule) {
$this->getEntityManager()->remove($vehicule);
$this->getEntityManager()->flush();
}
}
// Redirect to list of albums
return $this->redirect()->toRoute('default', array(
'controller' => 'vehicules',
'action' => 'index',
));
}
return array(
'id' => $id,
'vehicule' => $this->getEntityManager()->find('Vehicules\Entity\vehicule', $id)->getArrayCopy()
);
}
}
to populate forgnein key idMod and idCat i tried with this:
$mod = $this->getObjectManager()->getRepository('Vehicules\Entity\modele')->findAll();
foreach ($mod as $m){
if($m->getNom()==$f['modele'] ){
$Vehicule->setIdmod($m->getIdmod()) ;
exit;
}
}
but id doesn't work :/
Your issue is the form/entity hydration. You don't need to reinvent the wheel here as Zend\Form already takes care of getting the data in and out of a form.
Currently your form uses the default ArraySerializable hydrator, so when the form is validated and you fetch the data (using $form->getData()) you are given an array. What you want is a already populated Vehicule entity.
The DoctrineModule\Stdlib\Hydrator\DoctrineObject is a hydrator specifically for Doctrine. If you attach it as the hydrator to your form it will return hydrated entity.
To solve this you need to STOP creating the form using new
$form = new VehiculeForm($_objectManager);
Instead create it via the ServiceManager
$form = $this->getServiceLocator()->get('MyModule\Form\VehiculeForm');
Now create the form from a service factory; allowing the injection of the form dependencies, including the hydrator.
MyModule/Factory/Form/VehiculeFormFactory.php
namespace MyModule\Factory\Form;
use MyModule\Entity;
use MyModule\Form;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\ServiceManager\FactoryInterface;
use DoctrineModule\Stdlib\Hydrator;
class VehiculeFormFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $sl)
{
$objectManager = $sl->get('Doctrine\ORM\EntityManager');
$form = new Form\VehiculeForm($objectManager);
$vehicule = new Entity\Vehicule();
// create the hydrator; this could also be done via the
// hydrator manager but create here for the example
$hydrator = new DoctrineObject($objectManager);
$form->setHydrator($hydrator);
$form->setObject($vehicule);
// We can also take care of the input filter here too!
// meaning less code in the controller and only
// one place to modify should it change
$form->setInputFilter($Vehicule->getInputFilter());
return $form;
}
}
Module.php
public function getFormElementConfig()
{
return array(
'factories' => array(
'MyModule\Form\VehiculeForm' => 'MyModule\Factory\Form\VehiculeForm' // path to our new factory
),
);
}
You can now get rid of your populate() method and allot of the controller code.
FooController.php
//...
protected function getVehiculeForm()
{
return $this->getServiceLocator()->get('MyModule\Form\VehiculeForm');
}
public function addAction()
{
$request = $this->getRequest();
$form = $this->getVehiculeForm();
if ($request->isPost()) {
$form->setData($request->getPost());
if ($form->isValid()) {
$vehicule = $form->getData(); // returns the entity!
if ($vehicule instanceof Vehicule) {
/// Fully hydrated entity!
var_dump($vehicule);
}
}
}
//...
}
//...
So what i want is to validate my Checkbox in my form and check if it's checked so i should save it as 1 in my database else as 0, like this :
$this->add(array(
'name' => 'publication',
'type' => 'Zend\Form\Element\Checkbox',
'options' => array(
'checked_value' => 1,
'unchecked_value' => 0,
),
));
But when i tried i got Null in my database !!, for more details i will write some of my codes,
This is my view :
<label>Publication:</label>
<?php
echo $this->formInput($form->get('publication'));
?>
And this is my Entity :
/**
* #ORM\Column(name="publication", type="boolean")
*/
protected $publication;
/**
* Set publication
*
* #param boolean $publication
* #return Article
*/
public function setPublication($publication)
{
$this->publication = $publication;
return $this;
}
/**
* Get publication
*
* #return boolean
*/
public function getPublication()
{
return $this->publication;
}
public function exchangeArray($data)
{
$this->publication = (isset($data['publication'])) ? $data['publication'] : null;
}
public function getInputFilter()
{
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
$inputFilter->add(array(
'name' => 'publication',
'required' => false,
));
So please if someone has any solution i will be so appreciative :)
When a checkbox is not ticked, it is not included in the post. In your exchangeArray, you are setting it null in this case.
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.