How to add custom field in Customer Registration on Magento 2.2? - php

I want to add Custom field in Customer Registration on Magento 2.2
I 've tried following code but it's not working.
I tried InstallData.php
use Magento\Customer\Setup\CustomerSetupFactory;
use Magento\Customer\Model\Customer;
use Magento\Eav\Model\Entity\Attribute\Set as AttributeSet;
use Magento\Eav\Model\Entity\Attribute\SetFactory as AttributeSetFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
class InstallData implements InstallDataInterface
{
protected $customerSetupFactory;
private $attributeSetFactory;
public function __construct(CustomerSetupFactory $customerSetupFactory, AttributeSetFactory $attributeSetFactory)
{
$this->customerSetupFactory = $customerSetupFactory;
$this->attributeSetFactory = $attributeSetFactory;
}
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
$customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);
$customerEntity = $customerSetup->getEavConfig()->getEntityType('customer');
$attributeSetId = $customerEntity->getDefaultAttributeSetId();
$attributeSet = $this->attributeSetFactory->create();
$attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);
$customerSetup->addAttribute(Customer::ENTITY, 'intrestedin', [
'type' => 'varchar',
'label' => 'Custom Field',
'input' => 'text',
'required' => true,
'visible' => true,
'user_defined' => true,
'sort_order' => 1000,
'position' => 1000,
'system' => 0,
]);
$attribute = $customerSetup->getEavConfig()->getAttribute(Customer::ENTITY, 'mobile_number')
->addData([
'attribute_set_id' => $attributeSetId,
'attribute_group_id' => $attributeGroupId,
'used_in_forms' => ['adminhtml_customer', 'customer_account_create'],
]);
$attribute->save();
}
}

Please try to create a module and add customer attribute. you can create module from here- https://mage2gen.com/
After installing the module , you can run setup upgrade and deploy command.

Related

How to add multiple attributes in InstallData Magento 2

Please specify how to add multiple attributes in single InstallData script
Magento 2 uses Data scripts to add attributes.
In folder Vendor/Module/Setup/Patch/Data add a .php file (eg: AddCustomerAttributes)
The following will add a few customer attributes.
After adding this bin/magento setup:upgrade command is required.
There will be an entry added to patch_list datatable, if the script file was executed correctly and also the attributes in the eav attribute table of course.
<?php
namespace Vendor\Module\Setup\Patch\Data;
use Magento\Customer\Model\Customer;
use Magento\Customer\Setup\CustomerSetupFactory;
use Magento\Eav\Model\Entity\Attribute\SetFactory as AttributeSetFactory;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\Patch\DataPatchInterface;
class AddCustomerAttributes implements DataPatchInterface
{
/**
* #var ModuleDataSetupInterface
*/
protected $moduleDataSetup;
/**
* #var CustomerSetupFactory
*/
protected $customerSetupFactory;
/**
* #var AttributeSetFactory
*/
protected $attributeSetFactory;
/**
* AddCustomerPhoneNumberAttribute constructor.
* #param ModuleDataSetupInterface $moduleDataSetup
* #param CustomerSetupFactory $customerSetupFactory
* #param AttributeSetFactory $attributeSetFactory
*/
public function __construct(
ModuleDataSetupInterface $moduleDataSetup,
CustomerSetupFactory $customerSetupFactory,
AttributeSetFactory $attributeSetFactory
) {
$this->moduleDataSetup = $moduleDataSetup;
$this->customerSetupFactory = $customerSetupFactory;
$this->attributeSetFactory = $attributeSetFactory;
}
/**
* {#inheritdoc}
*/
public function apply()
{
$customerSetup = $this->customerSetupFactory->create(['setup' => $this->moduleDataSetup]);
$customerEntity = $customerSetup->getEavConfig()->getEntityType(Customer::ENTITY);
$attributeSetId = $customerEntity->getDefaultAttributeSetId();
$attributeSet = $this->attributeSetFactory->create();
$attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);
/** attribute_1 */
$customerSetup->addAttribute(
Customer::ENTITY,
'attribute_1',
[
'type' => 'text',
'label' => 'Attribute One',
'input' => 'text',
'required' => false,
'user_defined' => true,
'sort_order' => 1000,
'position' => 1000,
'default' => 0,
'system' => 0
]
);
$attribute = $customerSetup->getEavConfig()->getAttribute(
Customer::ENTITY,
'attribute_1'
);
$attribute->addData(
[
'attribute_set_id' => $attributeSetId,
'attribute_group_id' => $attributeGroupId,
'used_in_forms' => ['adminhtml_customer']
]
);
$attribute->save();
/** attribute_2 */
$customerSetup->addAttribute(
Customer::ENTITY,
'attribute_2',
[
'type' => 'int',
'label' => 'Attribute Two',
'input' => 'select',
'source' => 'Vendor\Module\Model\Options',
'required' => false,
'user_defined' => true,
'sort_order' => 1000,
'position' => 1000,
'default' => 0,
'system' => 0
]
);
$attribute = $customerSetup->getEavConfig()->getAttribute(
Customer::ENTITY,
'attribute_2'
);
$attribute->addData(
[
'attribute_set_id' => $attributeSetId,
'attribute_group_id' => $attributeGroupId,
'used_in_forms' => ['adminhtml_customer']
]
);
$attribute->save();
}
/**
* {#inheritdoc}
*/
public static function getDependencies()
{
return [];
}
/**
* {#inheritdoc}
*/
public function getAliases()
{
return [];
}
}
Please let me know if you need help with anything on this.
thanks for the above solution using patches. It's working and I used the same methodology using InstallData/UpgradeData.php according to my requirement.
Please check my answer
This will save the data in the database in table customer_entity_varchar and attributes in eav_attribute.
Check the code:
<?php
namespace CustomB2BRFQ\Module\Setup;
use Magento\Customer\Model\Customer;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\UpgradeDataInterface;
use Magento\Customer\Setup\CustomerSetupFactory;
use Magento\Eav\Model\Entity\Attribute\SetFactory as AttributeSetFactory;
class UpgradeData implements \Magento\Framework\Setup\UpgradeDataInterface
{
private $eavSetupFactory;
private $eavConfig;
private $attributeResource;
private $customerSetupFactory;
/**
* #var AttributeSetFactory
*/
protected $attributeSetFactory;
protected $moduleDataSetup;
public function __construct(
\Magento\Eav\Setup\EavSetupFactory $eavSetupFactory,
\Magento\Eav\Model\Config $eavConfig,
\Magento\Customer\Model\ResourceModel\Attribute $attributeResource,
CustomerSetupFactory $customerSetupFactory,
AttributeSetFactory $attributeSetFactory,
ModuleDataSetupInterface $moduleDataSetup
) {
$this->eavSetupFactory = $eavSetupFactory;
$this->eavConfig = $eavConfig;
$this->attributeResource = $attributeResource;
$this->customerSetupFactory = $customerSetupFactory;
$this->attributeSetFactory = $attributeSetFactory;
$this->moduleDataSetup = $moduleDataSetup;
}
public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
$customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);
//$customerSetup->removeAttribute(Customer::ENTITY, "phonenumber");
$customerEntity = $customerSetup->getEavConfig()->getEntityType(Customer::ENTITY);
$attributeSetId = $customerEntity->getDefaultAttributeSetId();
$attributeSet = $this->attributeSetFactory->create();
$attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);
/** attribute_1 */
$customerSetup->addAttribute(
Customer::ENTITY,
'phonenumber',
[
'type' => 'varchar',
'label' => 'Phone Number',
'input' => 'text',
'required' => true,
'visible' => true,
'user_defined' => true,
'sort_order' => 991,
'position' => 991,
'system' => 0,
]
);
$attribute = $customerSetup->getEavConfig()->getAttribute(
Customer::ENTITY,
'phonenumber'
);
$attribute->addData(
[
'attribute_set_id' => $attributeSetId,
'attribute_group_id' => $attributeGroupId,
'used_in_forms' => ['adminhtml_customer',
'customer_account_create',
'customer_account_edit']
]
);
$attribute->save();
/** attribute_2 */
$customerSetup->addAttribute(
Customer::ENTITY,
'gstnumber',
[
'type' => 'varchar',
'label' => 'GST Number',
'input' => 'text',
'required' => true,
'visible' => true,
'user_defined' => true,
'sort_order' => 992,
'position' => 992,
'system' => 0,
]
);
$attribute = $customerSetup->getEavConfig()->getAttribute(
Customer::ENTITY,
'gstnumber'
);
$attribute->addData(
[
'attribute_set_id' => $attributeSetId,
'attribute_group_id' => $attributeGroupId,
'used_in_forms' => ['adminhtml_customer',
'customer_account_create',
'customer_account_edit']
]
);
$attribute->save();
}
}
?>

Creating a custom Customer attribute through module upgrade (UpgradeData.php)

As title says, i'm having troubles at creating new customers attribute when upgrading one of my modules.
I've created the UpgradeData.php file under /app/code/vendor/modulename/Setup/UpgradeData.php with the current code:
namespace Ucs\CustomerAttribute\Setup;
use Magento\Customer\Model\Customer;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\UpgradeDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Customer\Setup\CustomerSetupFactory;
class UpgradeData implements UpgradeDataInterface{
private $customerSetupFactory;
public function __construct(
CustomerSetupFactory $customerSetupFactory
) {
$this->customerSetupFactory = $customerSetupFactory;
}
/**
* {#inheritdoc}
*/
public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context){
$setup->startSetup();
$customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);
if (version_compare($context->getVersion(), '1.0.6') < 0) {
$customerSetup->addAttribute(\Magento\Customer\Model\Customer::ENTITY, 'nome_azienda', [
'type' => 'varchar',
'label' => 'Nome azienda',
'input' => 'text',
'source' => '',
'required' => false,
'visible' => true,
'position' => 333,
'system' => false,
'backend' => ''
]);
$attribute = $customerSetup->getEavConfig()->getAttribute(\Magento\Customer\Model\Customer::ENTITY, 'nome_azienda')
->addData(['used_in_forms' => [
'adminhtml_customer',
'adminhtml_checkout',
'customer_account_create',
'customer_account_edit'
]]);
$attribute->save();
$customerSetup->addAttribute(\Magento\Customer\Model\Customer::ENTITY, 'codice_univoco', [
'type' => 'varchar',
'label' => 'Codice Univoco',
'input' => 'text',
'source' => '',
'required' => false,
'visible' => true,
'position' => 333,
'system' => false,
'backend' => ''
]);
$attribute = $customerSetup->getEavConfig()->getAttribute(\Magento\Customer\Model\Customer::ENTITY, 'codice_univoco')
->addData(['used_in_forms' => [
'adminhtml_customer',
'adminhtml_checkout',
'customer_account_create',
'customer_account_edit'
]]);
$attribute->save();
}
}
}
in short, it needs to create 2 new text (varchar) attributes. My module.xml has
setup_version="1.0.5" schema_version="1.0.5" so it should enter the version_compare condition and create the attribute, but, after running php bin/magento setup:upgrade it doesn't work. Even by removing that "if" condition no attributes are created. If i check in the setup_module table, the setup_version and schema_version change correctly with the version in the module.xml. It looks like for some reason the UpgradeData.php does not get executed at all (even trying to log a string into a log file doesn't write anything). Other log files under ..../var/log/ show no errors or warnings. With this module i have already created OTHER custom Customer attributes with the installData.php file with no issues at all.
I have no idea what to do, can't really understand what i'm doing wrong
You can check it the below links:
https://magento.stackexchange.com/questions/254790/upgradedata-to-add-a-custom-customer-attribute-is-not-working-in-magento2
https://github.com/mundipagg/magento2/blob/master/Setup/UpgradeData.php

Magento 2 Overriding a custom module

So in summary I'm trying to override a third party module to include an extra dropdown menu on the admin Ui
Heres the third party file at
Prince/Productattach/Block/Adminhtml/Productattach/Edit/Tab/Main.php
namespace Prince\Productattach\Block\Adminhtml\Productattach\Edit\Tab;
/**
*Class Main
*#package Prince\Productattach\Block\Adminhtml\Productattach\Edit\Tab
*/
class Main extends \Magento\Backend\Block\Widget\Form\Generic implements
\Magento\Backend\Block\Widget\Tab\TabInterface
{
/**
* #var \Magento\Store\Model\System\Store
*/
private $systemStore;
/**
* #var \Magento\Customer\Model\ResourceModel\Group\Collection
*/
private $customerCollection;
/**
* Main constructor.
* #param \Magento\Backend\Block\Template\Context $context
* #param \Magento\Framework\Registry $registry
* #param \Magento\Framework\Data\FormFactory $formFactory
* #param \Magento\Store\Model\System\Store $systemStore
* #param \Magento\Customer\Model\ResourceModel\Group\Collection $customerCollection
* #param array $data
*/
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Framework\Registry $registry,
\Magento\Framework\Data\FormFactory $formFactory,
\Magento\Store\Model\System\Store $systemStore,
\Magento\Customer\Model\ResourceModel\Group\Collection $customerCollection,
array $data = []
) {
$this->_systemStore = $systemStore;
$this->_customerCollection = $customerCollection;
parent::__construct($context, $registry, $formFactory, $data);
}
/**
* Prepare form
*
* #return $this
*/
public function _prepareForm()
{
$model = $this->_coreRegistry->registry('productattach');
/*
* Checking if user have permissions to save information
*/
if ($this->_isAllowedAction('Prince_Productattach::save')) {
$isElementDisabled = false;
} else {
$isElementDisabled = true;
}
/** #var \Magento\Framework\Data\Form $form */
$form = $this->_formFactory->create();
$form->setHtmlIdPrefix('productattach_main_');
$fieldset = $form->addFieldset(
'base_fieldset',
['legend' => __('Attachment Information')]
);
$customerGroup = $this->customerCollection->toOptionArray();
if ($model->getId()) {
$fieldset->addField('productattach_id', 'hidden', ['name' => 'productattach_id']);
}
$fieldset->addField(
'name',
'text',
[
'name' => 'name',
'label' => __('Attachment Name'),
'title' => __('Attachment Name'),
'required' => true,
'disabled' => $isElementDisabled
]
);
$fieldset->addField(
'description',
'textarea',
[
'name' => 'description',
'label' => __('Description'),
'title' => __('Description'),
'disabled' => $isElementDisabled
]
);
$fieldset->addField(
'files',
'file',
[
'name' => 'file',
'label' => __('File'),
'title' => __('File'),
'required' => false,
'note' => 'File size must be less than 2 Mb.', // TODO: show ACCTUAL file-size
'disabled' => $isElementDisabled
]
);
$fieldset->addType(
'uploadedfile',
\Prince\Productattach\Block\Adminhtml\Productattach\Renderer\FileIconAdmin::class
);
$fieldset->addField(
'file',
'uploadedfile',
[
'name' => 'uploadedfile',
'label' => __('Uploaded File'),
'title' => __('Uploaded File'),
]
);
$fieldset->addField(
'url',
'text',
[
'name' => 'url',
'label' => __('URL'),
'title' => __('URL'),
'required' => false,
'disabled' => $isElementDisabled,
'note' => 'Upload file or Enter url'
]
);
$fieldset->addField(
'customer_group',
'multiselect',
[
'name' => 'customer_group[]',
'label' => __('Customer Group'),
'title' => __('Customer Group'),
'required' => true,
'value' => [0,1,2,3], // todo: preselect ALL customer groups, not just 0-3
'values' => $customerGroup,
'disabled' => $isElementDisabled
]
);
$fieldset->addField(
'store',
'multiselect',
[
'name' => 'store[]',
'label' => __('Store'),
'title' => __('Store'),
'required' => true,
'value' => [0],
'values' => $this->systemStore->getStoreValuesForForm(false, true),
'disabled' => $isElementDisabled
]
);
$fieldset->addField(
'active',
'select',
[
'name' => 'active',
'label' => __('Active'),
'title' => __('Active'),
'value' => 1,
'options' => ['1' => __('Yes'), '0' => __('No')],
'disabled' => $isElementDisabled
]
);
$this->_eventManager->dispatch('adminhtml_productattach_edit_tab_main_prepare_form', ['form' => $form]);
if ($model->getId()) {
$form->setValues($model->getData());
}
$this->setForm($form);
return parent::_prepareForm();
}
/**
* Prepare label for tab
*
* #return string
*/
public function getTabLabel()
{
return __('Attachment Information');
}
/**
* Prepare title for tab
*
* #return string
*/
public function getTabTitle()
{
return __('Attachment Information');
}
/**
* {#inheritdoc}
*/
public function canShowTab()
{
return true;
}
/**
* {#inheritdoc}
*/
public function isHidden()
{
return false;
}
/**
* Check permission for passed action
*
* #param string $resourceId
* #return bool
*/
public function _isAllowedAction($resourceId)
{
return $this->_authorization->isAllowed($resourceId);
}
}
I have my module setup and my di.xml configured with the usual plus below to override the class.
<preference for="Prince\Productattach\Block\Adminhtml\Productattach\Edit\Tab" type="Vendor\Filecategory\Block\Adminhtml\Productattach\Edit\Tab"/>
then and exact replica of the class with namespace and my extra field added at
Vendor/Filecategory/Block/Adminhtml/Productattach/Edit/Tab/Main.php
namespace Vendor\Filecategory\Block\Adminhtml\Productattach\Edit\Tab;
use \Prince\Productattach\Block\Adminhtml\Productattach\Edit\Tab\Main as Main;
class MainExt extends Main
{
/**
* #var \Magento\Store\Model\System\Store
*/
private $systemStore;
/**
* #var \Magento\Customer\Model\ResourceModel\Group\Collection
*/
private $customerCollection;
/**
* Main constructor.
* #param \Magento\Backend\Block\Template\Context $context
* #param \Magento\Framework\Registry $registry
* #param \Magento\Framework\Data\FormFactory $formFactory
* #param \Magento\Store\Model\System\Store $systemStore
* #param \Magento\Customer\Model\ResourceModel\Group\Collection $customerCollection
* #param array $data
*/
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Framework\Registry $registry,
\Magento\Framework\Data\FormFactory $formFactory,
\Magento\Store\Model\System\Store $systemStore,
\Magento\Customer\Model\ResourceModel\Group\Collection $customerCollection,
array $data = []
) {
$this->systemStore = $systemStore;
$this->customerCollection = $customerCollection;
parent::__construct($context, $registry, $formFactory, $data, $systemStore);
}
/**
* Prepare form
*
* #return $this
*/
public function _prepareForm()
{
$model = $this->_coreRegistry->registry('productattach');
/*
* Checking if user have permissions to save information
*/
if ($this->_isAllowedAction('Prince_Productattach::save')) {
$isElementDisabled = false;
} else {
$isElementDisabled = true;
}
/** #var \Magento\Framework\Data\Form $form */
$form = $this->_formFactory->create();
$form->setHtmlIdPrefix('productattach_main_');
$fieldset = $form->addFieldset(
'base_fieldset',
['legend' => __('Attachment Information')]
);
$customerGroup = $this->customerCollection->toOptionArray();
if ($model->getId()) {
$fieldset->addField('productattach_id', 'hidden', ['name' => 'productattach_id']);
}
$fieldset->addField(
'name',
'text',
[
'name' => 'name',
'label' => __('Attachment Name'),
'title' => __('Attachment Name'),
'required' => true,
'disabled' => $isElementDisabled
]
);
$fieldset->addField(
'Category',
'select',
[
'name' => 'Category',
'label' => __('Category'),
'title' => __('Category'),
'value' => 0,
'options' => ['0' => __('Technical Specification'), '1' => __('Installation Instructions')],
]
);
$fieldset->addField(
'description',
'textarea',
[
'name' => 'description',
'label' => __('Description'),
'title' => __('Description'),
'disabled' => $isElementDisabled
]
);
$fieldset->addField(
'files',
'file',
[
'name' => 'file',
'label' => __('File'),
'title' => __('File'),
'required' => false,
'note' => 'File size must be less than 2 Mb.', // TODO: show ACCTUAL file-size
'disabled' => $isElementDisabled
]
);
$fieldset->addType(
'uploadedfile',
\Prince\Productattach\Block\Adminhtml\Productattach\Renderer\FileIconAdmin::class
);
$fieldset->addField(
'file',
'uploadedfile',
[
'name' => 'uploadedfile',
'label' => __('Uploaded File'),
'title' => __('Uploaded File'),
]
);
$fieldset->addField(
'url',
'text',
[
'name' => 'url',
'label' => __('URL'),
'title' => __('URL'),
'required' => false,
'disabled' => $isElementDisabled,
'note' => 'Upload file or Enter url'
]
);
$fieldset->addField(
'customer_group',
'multiselect',
[
'name' => 'customer_group[]',
'label' => __('Customer Group'),
'title' => __('Customer Group'),
'required' => true,
'value' => [0,1,2,3], // todo: preselect ALL customer groups, not just 0-3
'values' => $customerGroup,
'disabled' => $isElementDisabled
]
);
$fieldset->addField(
'store',
'multiselect',
[
'name' => 'store[]',
'label' => __('Store'),
'title' => __('Store'),
'required' => true,
'value' => [0],
'values' => $this->systemStore->getStoreValuesForForm(false, true),
'disabled' => $isElementDisabled
]
);
$fieldset->addField(
'active',
'select',
[
'name' => 'active',
'label' => __('Active'),
'title' => __('Active'),
'value' => 1,
'options' => ['1' => __('Yes'), '0' => __('No')],
'disabled' => $isElementDisabled
]
);
$this->_eventManager->dispatch('adminhtml_productattach_edit_tab_main_prepare_form', ['form' => $form]);
if ($model->getId()) {
$form->setValues($model->getData());
}
$this->setForm($form);
return parent::_prepareForm();
}
/**
* Prepare label for tab
*
* #return string
*/
public function getTabLabel()
{
return __('Attachment Information');
}
/**
* Prepare title for tab
*
* #return string
*/
public function getTabTitle()
{
return __('Attachment Information');
}
/**
* {#inheritdoc}
*/
public function canShowTab()
{
return true;
}
/**
* {#inheritdoc}
*/
public function isHidden()
{
return false;
}
/**
* Check permission for passed action
*
* #param string $resourceId
* #return bool
*/
public function _isAllowedAction($resourceId)
{
return $this->_authorization->isAllowed($resourceId);
}
}
However I keep getting Error
Incompatible argument type: Required type: \Magento\Store\Model\System\Store. Actual type: array;
I have tried flush cache and reindex but no luck. Please can someone tell me what im doing wrong here? Also happy to listen to any alternative ways of completing the same thing.
Thanks in advance.
I have managed to complete this by creating a plugin class instead of overriding the whole class. I have attached the post I followed for any one interested in adding a form field to n existing form attached to a third part module.
https://magento.stackexchange.com/questions/174209/magento-2-add-new-field-to-magento-user-admin-form

Symfony2 Data Transformer receives null

My data transformer receives null values in all cases but those with 'multiple'=>true.
For now I'm just trying to var_dump the values.
This is my form:
$entitiesClasses = array(
'AppBundle\Entity\Category' => array( 'label' => 'entity.vehicle.category' ),
'AppBundle\Entity\Specific\ExteriorColor' => array( 'label' => 'entity.specific.exteriorColor' ),
'AppBundle\Entity\Specific\DoorCount' => array( 'label' => 'entity.specific.doorCount' ),
'AppBundle\Entity\Specific\Fuel' => array( 'label' => 'entity.specific.fuel' ),
'AppBundle\Entity\Specific\Gearbox' => array( 'label' => 'entity.specific.gearbox' ),
'AppBundle\Entity\Specific\Climatisation' => array( 'label' => 'entity.specific.climatisation' ),
'AppBundle\Entity\Specific\WheelFormula' => array( 'label' => 'entity.specific.wheelFormula' ),
'AppBundle\Entity\Specific\InteriorColor' => array( 'label' => 'entity.specific.interiorColor' ),
'AppBundle\Entity\Specific\InteriorType' => array( 'label' => 'entity.specific.interiorType' ),
'AppBundle\Entity\Specific\ParkingAssistant' => array( 'label' => 'entity.specific.parkingAssistant', 'multiple' => true ),
'AppBundle\Entity\Feature' => array( 'label' => 'entity.vehicle.features', 'multiple' => true ),
);
$getEntityInputName = function($className) {
$test = preg_split('/\\\/', $className);
return lcfirst(end($test));
};
foreach($entitiesClasses as $className => $options) {
$inputName = $getEntityInputName($className);
isset($options['multiple']) && $options['multiple'] == true? $inputName .= 's' : null;
$formMapper->add(
$formMapper->getFormBuilder()->create($inputName, 'entity',
array_merge(
$options,
array(
'required' => false,
'class' => $className,
'query_builder' => $query_builder,
))
)->addModelTransformer(new EntityTranslationTransformer($this->em))
This is my transformer:
namespace AppBundle\Form\DataTransformer;
use Doctrine\ORM\EntityManager;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;
class EntityTranslationTransformer implements DataTransformerInterface
{
/**
* #var EntityManager
*/
private $em;
/**
* #var mixed $entity
*/
private $entity;
/**
* #param EntityManager $em
* #param string $entity
*/
public function __construct(EntityManager $em)
{
$this->em = $em;
}
public function transform($value)
{
if ($value === null) {
return null;
}
return $value;
}
Any idea why this is happening and how to fix it?
if you read here
http://symfony.com/doc/current/cookbook/form/data_transformers.html#creating-the-transformer
transform should change an object into string(an entity to its id), try it as it is in the docs
public function transform($value)
{
if (null === $value) {
return "";
}
return $value->getId();
}
In addition, why do you need a transformer for an entity type field?

Fatal error: Class 'Application\forms\ArticleForm' not found in my Controller

So I've a problem that made me crazy :(, I create a form and when I use the class form in my controller I got this error:
Fatal error: Class 'Application\forms\ArticleForm' not found in C:\wamp2\www\test\module\Application\src\Application\Controller\BlogController.php
and even when I try to use Application\forms\ArticleForm this path doesn't found, this is a part of my action : Update the code :
public function addAction()
{
$form = new ArticleForm();// here the class doesn't found !!
//var_dump($form);die;
$form->initForm();
$request = $this->getRequest();
$form->setData($request->getPost());
And this is my ArticleForm :
class ArticleForm extends Form {
public function __construct()
{
parent::__construct('UserEntry');
$this->setAttribute('method', 'post');
$this->setAttribute('enctype', 'multipart/form-data');
$this->setAttribute('class', 'contact_form');
}
public function initForm()
{
$this->addFormFields(); //function where we added all fields
$articleInputFilter = new ArticleInputFilter();
$this->setInputFilter($articleInputFilter->getInputFilter()); //Asign input Filter to form
}
protected function addFormFields()
{
$this->addSubmit();
$this->addTitle();
$this->addContent();
$this->addDate();
$this->addPublication();
$this->addImage();
}
/**
*
*/
protected function addTitle()
{
$this->add(array(
'name' => 'title',
'attributes' => array(
'type' => 'text',
),
'options' => array(
'label' => _('Title')
),
));
}
/**
*
*/
protected function addContent()
{
$this->add(array(
'name' => 'content',
'attributes' => array(
'type' => 'text',
),
'options' => array(
'label' => _('Content')
),
));
}
/**
*
*/
protected function addDate()
{
$this->add(array(
'name' => 'date',
'attributes' => array(
'type' => 'date',
),
'options' => array(
'label' => _('Date'),
'id' => 'datepicker',
),
));
}
/**
*
*/
protected function addPublication()
{
$this->add(array(
'name' => 'publication',
'attributes' => array(
'type' => 'checkbox',
),
'options' => array(
'label' => _('Publication'),
'use_hidden_element' => true,
'checked_value' => 1,
'unchecked_value' => 'no',
),
));
}
/**
*
*/
protected function addImage()
{
$this->add(array(
'name' => 'Image',
'attributes' => array(
'type' => new ImageForm(),
),
'options' => array(
'label' => _('Image')
),
));
}
/**
*
*/
protected function addSubmit()
{
$this->add(array(
'name' => 'submit',
'attributes' => array(
'type' => 'submit',
'value' => _('Add'),
'class' => 'submit',
),
));
}
}
Finally this is my ArticleInputFilter :
class ArticleInputFilter extends InputFilter implements InputFilterAwareInterface
{
/**
* #var string
*/
public $title;
/**
* #var int
*/
public $image;
/**
* #var string
*/
public $content;
/**
* #var Date
*/
public $date;
/**
* #var Boolean
*/
public $publication;
/**
* #param $data
*/
public function exchangeArray($data)
{
$this->title = (isset($data['title'])) ? $data['title'] : $this->title;
$this->image = (isset($data['image'])) ? $data['image'] : $this->image;
$this->content = (isset($data['content'])) ? $data['content'] : $this->content;
$this->publication = (isset($data['publication'])) ? $data['publication'] : $this->publication;
$this->date = (isset($data['date'])) ? $data['date'] : $this->date;
}
/**
* #param InputFilterInterface $inputFilter
* #return void|InputFilterAwareInterface
* #throws \Exception
*/
public function setInputFilter(InputFilterInterface $inputFilter)
{
throw new \Exception("Not used");
}
/**
* #return InputFilter|InputFilterInterface
*/
public function getInputFilter()
{
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
$factory = new InputFactory();
$inputFilter->add($factory->createInput(array(
'name' => 'title',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 6,
'max' => 100,
),
),
),
)));
$inputFilter->add($factory->createInput(array(
'name' => 'content',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 10,
),
),
),
)));
$inputFilter->add($factory->createInput(array(
'name' => 'publication',
'required' => false,
)));
$inputFilter->add($factory->createInput(array(
'name' => 'date',
'required' => true,
)));
$inputFilter->add($factory->createInput(array(
'name' => 'image',
'required' => true,
)));
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
}
So please if someone has any idea or solution to my problem I will be very appreciative.
Probably an autoloading problem.
Where is defined your ArticleForm ?
Note : you'd better use the form element manager to get form instance. You can read more on this subject here
I had the same problem. The answer is pretty simple. The problem is in the autoloader so you need to "refresh" or "sincronyze everything" before you get started. So at the top of the function addAction() or the file just require the autoload.php file that is inside of the vendor folder to "update" your project. Something like this:
require 'vendor/autoload.php';
Obviously, you need to write your own path.
I hope that would help.

Categories