Change attribute data for a store - Magento 2 - magento

I have created a custom attribute for customer using InstallData in magento 2.
However I wanted to change the is_required option of the attribute store wise.
updateAttribute can do the same however I don't know how to use it store wise.
$customerSetup->updateAttribute('customer', 'tax_exempted', 'is_required', true);
Code Snippet to create attribute.
namespace xyz\abc\Setup;
use Magento\Customer\Model\Customer;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
/**
* Install attributes
*/
class InstallData implements \Magento\Framework\Setup\InstallDataInterface
{
/**
* #var \Magento\Customer\Setup\CustomerSetupFactory
*/
protected $customerSetupFactory;
/**
* #var \Magento\Eav\Api\AttributeRepositoryInterface
*/
protected $attributeRepository;
/**
* Init
*
* #param \Magento\Customer\Setup\CustomerSetupFactory $customerSetupFactory
* #param \Magento\Eav\Api\AttributeRepositoryInterface $attributeRepository
*/
public function __construct(
\Magento\Customer\Setup\CustomerSetupFactory $customerSetupFactory,
\Magento\Eav\Api\AttributeRepositoryInterface $attributeRepository
) {
$this->customerSetupFactory = $customerSetupFactory;
$this->attributeRepository = $attributeRepository;
}
/**
* DB setup code
*
* #param \Magento\Framework\Setup\SchemaSetupInterface $setup
* #param \Magento\Framework\Setup\ModuleContextInterface $context
* #return void
*/
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context) {
/** #var \Magento\Customer\Setup\CustomerSetup $customerSetup */
$customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);
$setup->startSetup();
if ($customerSetup->getAttributeId('customer', 'tax_exempted') === false) {
$custAttr = $customerSetup->addAttribute(
Customer::ENTITY,
'tax_exempted',
[
'label' => 'Is Tax Exempted',
'type' => 'int',
'input' => 'boolean',
'default' => '0',
'position' => 71,
'visible' => true,
'required' => false,
'system' => false,
'user_defined' => true,
'visible_on_front' => false,
]
);
$taxExemptedAttr = $customerSetup->getEavConfig()->getAttribute(
Customer::ENTITY,
'tax_exempted'
);
$this->attributeRepository->save($taxExemptedAttr);
}
$setup->endSetup();
}
}

I found a solution to this, sharing the same below.
//Fetch all websites
$websites = $this->_storeManager->getWebsites();
foreach ($websites as $website) {
//fetch the attribute
$customAttribute = $this->_customerSetup->getEavConfig()
->getAttribute(
\Magento\Customer\Model\Customer::ENTITY,
'tax_exempted'
);
$customAttribute->setWebsite($website->getId());
$customAttribute->load($customAttribute->getId());
//for options that are website specific, scope_ is prefixed while changing
$customAttribute->setData('scope_is_required', 0);
$customAttribute->setData('scope_is_visible', 0);
/** For xyzwebsite, show the attribute */
if ($website->getCode() == 'xyz') {
$customAttribute->setData('scope_is_required', 1);
$customAttribute->setData('scope_is_visible', 1);
}
$customAttribute->save();
}

Related

Codeigniter method of class - undefiend function

ive try to do my first steps with codeignitter, so i have write a new methode(function) in a existing class.
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class App
{
/**
* Options autoload=1
* #var array
*/
private $options = [];
/**
* Quick actions create aside
* #var array
*/
private $quick_actions = [];
/**
* CI Instance
* #deprecated 1.9.8 Use $this->ci instead
* #var object
*/
private $_instance;
/**
* CI Instance
* #var object
*/
private $ci;
/**
* Show or hide setup menu
* #var boolean
*/
private $show_setup_menu = true;
/**
* Available reminders
* #var array
*/
private $available_reminders = ['customer', 'lead', 'estimate', 'invoice', 'proposal', 'expense', 'credit_note'];
/**
* Tables where currency id is used
* #var array
*/
private $tables_with_currency = [];
/**
* Media folder
* #var string
*/
private $media_folder;
/**
* Available languages
* #var array
*/
private $available_languages = [];
public function __construct()
{
$this->ci = & get_instance();
// #deprecated
$this->_instance = $this->ci;
$this->init();
do_action('app_base_after_construct_action');
}
/**
* Check if database upgrade is required
* #param string $v
* #return boolean
*/
public function is_db_upgrade_required($v = '')
{
if (!is_numeric($v)) {
$v = $this->get_current_db_version();
}
$this->ci->load->config('migration');
if ((int) $this->ci->config->item('migration_version') !== (int) $v) {
return true;
}
return false;
}
/**
* Return current database version
* #return string
*/
public function get_current_db_version()
{
$this->ci->db->limit(1);
return $this->ci->db->get('tblmigrations')->row()->version;
}
/**
* Upgrade database
* #return mixed
*/
public function upgrade_database()
{
if (!is_really_writable(APPPATH . 'config/config.php')) {
show_error('/config/config.php file is not writable. You need to change the permissions to 755. This error occurs while trying to update database to latest version.');
die;
}
$update = $this->upgrade_database_silent();
if ($update['success'] == false) {
show_error($update['message']);
} else {
set_alert('success', 'Your database is up to date');
if (is_staff_logged_in()) {
redirect(admin_url(), 'refresh');
} else {
redirect(site_url('authentication/admin'));
}
}
}
/**
* Make request to server to get latest version info
* #return mixed
*/
public function get_update_info()
{
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_USERAGENT => $this->ci->agent->agent_string(),
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_TIMEOUT => 30,
CURLOPT_URL => UPDATE_INFO_URL,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => [
'update_info' => 'true',
'current_version' => $this->get_current_db_version(),
],
]);
$result = curl_exec($curl);
$error = '';
if (!$curl || !$result) {
$error = 'Curl Error - Contact your hosting provider with the following error as reference: Error: "' . curl_error($curl) . '" - Code: ' . curl_errno($curl);
}
curl_close($curl);
if ($error != '') {
return $error;
}
return $result;
}
/**
* Return all available languages in the application/language folder
* #return array
*/
public function get_available_languages()
{
$languages = $this->available_languages;
return do_action('before_get_languages', $languages);
}
/**
* Function that will parse table data from the tables folder for amin area
* #param string $table table filename
* #param array $params additional params
* #return void
*/
public function get_table_data($table, $params = [])
{
$hook_data = do_action('before_render_table_data', [
'table' => $table,
'params' => $params,
]);
foreach ($hook_data['params'] as $key => $val) {
$$key = $val;
}
$table = $hook_data['table'];
$customFieldsColumns = [];
$path = VIEWPATH . 'admin/tables/' . $table . '.php';
if (file_exists(VIEWPATH . 'admin/tables/my_' . $table . '.php')) {
$path = VIEWPATH . 'admin/tables/my_' . $table . '.php';
}
include_once($path);
echo json_encode($output);
die;
}
/**
* Check if a option value is preset or individual
* #param string $name, string $value
* #return true/false
*/
public function option_is_preset($name,$value)
{
$str="`name`='".$name."' and value='".$value."' ";
$this->ci->db->select('id, name, value');
$this->ci->db->where($str);
$row = $this->ci->db->get('4U_tbloptions_preset')->row_array();
if ($row['id']>0) {
return true;
}
return false;
}
/**
* All available reminders keys for the features
* #return array
*/
public function get_available_reminders_keys()
{
return $this->available_reminders;
}
/**
* Get all db options
* #return array
*/
public function get_options()
{
return $this->options;
}
/**
* Function that gets option based on passed name
* #param string $name
* #return string
*/
public function get_option($name)
{
if ($name == 'number_padding_invoice_and_estimate') {
$name = 'number_padding_prefixes';
}
$val = '';
$name = trim($name);
if (!isset($this->options[$name])) {
// is not auto loaded
$this->ci->db->select('value');
$str="`name`='".$name."' and `maccid`='".$this->ci->session->userdata('macc_id')."'";
$this->ci->db->where($str);
$row = $this->ci->db->get('4U_accounts_tbloptions')->row();
if ($row) {
#echo"Wert aus account_tbloptions";
$val = $row->value;
}
} else {
#echo $name.'->'.$val.' Autoload - nicht aus DB!<br>';
$val = $this->options[$name];
}
$hook_data = do_action('get_option', ['name' => $name, 'value' => $val]);
//Fallback auf Standardwert
if ($hook_data['value']=='')
{
$this->ci->db->select('value');
$this->ci->db->where('name', $name);
$row = $this->ci->db->get('4U_tbloptions_preset')->row();
if ($row) {
#echo"Wert aus preset";
$val = $row->value;
}
$hook_data = do_action('get_option', ['name' => $name, 'value' => $val]);
}
return $hook_data['value'];
}
/**
* Add new quick action data
* #param array $item
*/
public function add_quick_actions_link($item = [])
{
$this->quick_actions[] = $item;
}
/**
* Quick actions data set from admin_controller.php
* #return array
*/
public function get_quick_actions_links()
{
$this->quick_actions = do_action('before_build_quick_actions_links', $this->quick_actions);
return $this->quick_actions;
}
/**
* Aside.php will set the menu visibility here based on few conditions
* #param int $total_setup_menu_items total setup menu items shown to the user
*/
public function set_setup_menu_visibility($total_setup_menu_items)
{
$this->show_setup_menu = $total_setup_menu_items == 0 ? false : true;
}
/**
* Check if should the script show the setup menu or not
* #return boolean
*/
public function show_setup_menu()
{
return do_action('show_setup_menu', $this->show_setup_menu);
}
/**
* Return tables that currency id is used
* #return array
*/
public function get_tables_with_currency()
{
return do_action('tables_with_currency', $this->tables_with_currency);
}
/**
* Return the media folder name
* #return string
*/
public function get_media_folder()
{
return do_action('get_media_folder', $this->media_folder);
}
/**
* Upgrade database without throwing any errors
* #return mixed
*/
private function upgrade_database_silent()
{
$this->ci->load->config('migration');
$beforeUpdateVersion = $this->get_current_db_version();
$this->ci->load->library('migration', [
'migration_enabled' => true,
'migration_type' => $this->ci->config->item('migration_type'),
'migration_table' => $this->ci->config->item('migration_table'),
'migration_auto_latest' => $this->ci->config->item('migration_auto_latest'),
'migration_version' => $this->ci->config->item('migration_version'),
'migration_path' => $this->ci->config->item('migration_path'),
]);
if ($this->ci->migration->current() === false) {
return [
'success' => false,
'message' => $this->ci->migration->error_string(),
];
}
update_option('upgraded_from_version', $beforeUpdateVersion);
return [
'success' => true,
];
}
/**
* Init necessary data
*/
protected function init()
{
//Autoloadfelder zuerst alle Presetfelder, die dann mit den Individualfeldern ueberschrieben werden
$optionsA = $this->ci->db->select('name, value')
->where('autoload', 1)
->get('4U_tbloptions_preset')->result_array();
$str=" 'maccid'='".$this->ci->session->userdata('macc_id')."' AND 'autoload'='1' ";
$optionsB = $this->ci->db->select('name, value')
->where($str)
->get('4U_accounts_tbloptions')->result_array();
$options=array_merge($optionsA, $optionsB);
// Loop the options and store them in a array to prevent fetching again and again from database
foreach ($options as $option) {
$this->options[$option['name']] = $option['value'];
}
/**
* Available languages
*/
foreach (list_folders(APPPATH . 'language') as $language) {
if (is_dir(APPPATH . 'language/' . $language)) {
array_push($this->available_languages, $language);
}
}
/**
* Media folder
* #var string
*/
$this->media_folder = do_action('before_set_media_folder', 'media');
/**
* Tables with currency
* #var array
*/
$this->tables_with_currency = [
[
'table' => 'tblinvoices',
'field' => 'currency',
],
[
'table' => 'tblexpenses',
'field' => 'currency',
],
[
'table' => 'tblproposals',
'field' => 'currency',
],
[
'table' => 'tblestimates',
'field' => 'currency',
],
[
'table' => 'tblclients',
'field' => 'default_currency',
],
[
'table' => 'tblcreditnotes',
'field' => 'currency',
],
[
'table' => 'tblsubscriptions',
'field' => 'currency',
],
];
}
/**
* Predefined contact permission
* #deprecated 1.9.8 use get_contact_permissions() instead
* #return array
*/
public function get_contact_permissions()
{
return get_contact_permissions();
}
}
Now i want to use this methode for example like this
echo"Test1: ".get_option('company_logo_dark');
echo"Test2: ".option_is_preset('company_logo_dark');
The methode "get_option" is one of the existing methode in the class.
This (get_option) work, but option_is_present produce a error " Call to undefined function option_is_preset() "
If i try
echo "Test3: ".$this->app->option_is_preset('company_logo',$company_logo);
it will work.
Why the first methode "get_option" i can use in this way ( echo "Test: ".get_option(string); " and why i can't do the same way for the other methode?
Thanks a lot for support me :-)
Inside class, you need to use the pseudo-variable $this
echo"Test1: ". $this->get_option('company_logo_dark');
echo"Test2: ". $this->option_is_preset('company_logo_dark', 'some_value');
Unsing a instance of a class:
$instance = new App();
echo"Test1: ". $instance ->get_option('company_logo_dark');
echo"Test2: ". $instance ->option_is_preset('company_logo_dark', 'some_value');
If the class App is placed in the library directory, you can use the Codeigniter Loader Class
$this->load->library('app');
echo"Test1: ". $this->app->get_option('company_logo_dark');
echo"Test2: ". $this->app->option_is_preset('company_logo_dark', 'some_value');
EDIT 1
get_option method can be called directly only if this is declared outside class. Please see the next example
function method_a($var) {
echo __METHOD__ . ' : ' . $var .'<br />';
}
class MyClass {
public function method_a($var) {
echo __METHOD__ . ' : ' . $var .'<br />';
$this->method_b($var);
}
public function method_b($var) {
echo __METHOD__ . ' : ' . $var .'<br />';
}
}
$instance = new MyClass();
$instance->method_a("Test");
method_a("Test");
this will return:
MyClass::method_a : Test
MyClass::method_b : Test
method_a : Test
EDIT 2
According to the updated class, method option_is_preset takes two arguments, $name and $value and you are trying to call only with one argument
echo"Test2: ".option_is_preset('company_logo_dark'); // wrong
echo"Test2: ".option_is_preset('company_logo_dark', 'some_value'); // correct
In another file i've found that
function get_option($name)
{
$CI = & get_instance();
if (!class_exists('app')) {
$CI->load->library('app');
}
return $CI->app->get_option($name);
}
This explains, why it is possible to call the "get_option" in a normal way of a function.
So i've add
function option_is_preset($name, $value)
{
$CI = & get_instance();
if (!class_exists('app')) {
$CI->load->library('app');
}
return $CI->app->option_is_preset($name, $value);
}
and now i can call the new methode like a function :-))

Laravel Datatable only searchs ID

I generated my Laravel CRUD views with InfyOm, which uses Datatables to present it. It comes with a search field by default, but when I try to search it only searches by ID. I can't find how I can set to search in the other fields too. I can't find any documentation about how to implement this. It seems that it has something to do with this, but I didn't get it. How can I make this?
Here is my Datatable class:
<?php
namespace App\DataTables;
use App\Models\SubscriptionStatus;
use Yajra\DataTables\Services\DataTable;
use Yajra\DataTables\EloquentDataTable;
class SubscriptionStatusDataTable extends DataTable
{
/**
* Build DataTable class.
*
* #param mixed $query Results from query() method.
* #return \Yajra\DataTables\DataTableAbstract
*/
public function dataTable($query)
{
$dataTable = new EloquentDataTable($query);
return $dataTable->addColumn('action', 'subscription_statuses.datatables_actions');
}
/**
* Get query source of dataTable.
*
* #param \App\Models\Post $model
* #return \Illuminate\Database\Eloquent\Builder
*/
public function query(SubscriptionStatus $model)
{
return $model->newQuery();
}
/**
* Optional method if you want to use html builder.
*
* #return \Yajra\DataTables\Html\Builder
*/
public function html()
{
return $this->builder()
->columns($this->getColumns())
->minifiedAjax()
->addAction(['width' => '80px', "title" => "Ações"])
->parameters([
'dom' => 'Bfrtip',
'order' => [[0, 'desc']],
'buttons' => [
'export',
'print',
'reset',
'reload',
],
]);
}
/**
* Get columns.
*
* #return array
*/
protected function getColumns()
{
return [
['data' => 'name', 'title' => 'Nome'],
['data' => 'description', 'title' => 'Descrição'],
['data' => 'expire_days', 'title' => 'Tempo para Expirar'],
];
}
/**
* Get filename for export.
*
* #return string
*/
protected function filename()
{
return 'subscription_statusesdatatable_' . time();
}
}

nullable not being read in Doctrine

I have a Zend Expressive project from Skeleton app. Also, the database NOT NULL is set for each of the fields that I have set nullable on. I think it might have something to do with it not reading the annotations. I had issues getting the annotations working in the first place, especially for the cli-config.php
Here's the DoctrineFactory I created loosely based on one I found as an example. I changed the way it creates the entityManager to more closely represent the Doctrine docs config example.
public function __invoke(ContainerInterface $container)
{
$config = $container->has('config') ? $container->get('config') : [];
$proxyDir = (isset($config['doctrine']['orm']['proxy_dir'])) ?
$config['doctrine']['orm']['proxy_dir'] : 'data/cache/EntityProxy';
$proxyNamespace = (isset($config['doctrine']['orm']['proxy_namespace'])) ?
$config['doctrine']['orm']['proxy_namespace'] : 'EntityProxy';
$autoGenerateProxyClasses = (isset($config['doctrine']['orm']['auto_generate_proxy_classes'])) ?
$config['doctrine']['orm']['auto_generate_proxy_classes'] : false;
$underscoreNamingStrategy = (isset($config['doctrine']['orm']['underscore_naming_strategy'])) ?
$config['doctrine']['orm']['underscore_naming_strategy'] : false;
$paths = (isset($config['doctrine']['paths'])) ? $config['doctrine']['paths'] : [];
$isDevMode = (isset($config['doctrine']['isDevMode'])) ? $config['doctrine']['isDevMode'] : false;
$doctrine = Setup::createAnnotationMetadataConfiguration($paths, $isDevMode);
// Doctrine ORM
$doctrine->setProxyDir($proxyDir);
$doctrine->setProxyNamespace($proxyNamespace);
$doctrine->setAutoGenerateProxyClasses($autoGenerateProxyClasses);
if ($underscoreNamingStrategy) {
$doctrine->setNamingStrategy(new UnderscoreNamingStrategy());
}
// Cache
$cache = $container->get(Cache::class);
$doctrine->setQueryCacheImpl($cache);
$doctrine->setResultCacheImpl($cache);
$doctrine->setMetadataCacheImpl($cache);
// EntityManager
return EntityManager::create($config['doctrine']['connection']['orm_default'], $doctrine);
}
Config like so:
'doctrine' => [
'orm' => [
'auto_generate_proxy_classes' => false,
'proxy_dir' => 'data/cache/EntityProxy',
'proxy_namespace' => 'EntityProxy',
'underscore_naming_strategy' => true,
],
'connection' => [
// default connection
'orm_default' => [
'driver' => 'pdo_mysql',
'host' => '127.0.0.1',
'port' => '3306',
'dbname' => 'users',
'user' => 'root',
'password' => 'password',
'charset' => 'UTF8',
],
],
'paths' => [
__DIR__.'/../../vendor/plexus/user-lib/src/Entity'
],
'isDevMode' => false,
'cache' => [
'redis' => [
'host' => '127.0.0.1',
'port' => '6379',
],
],
],
Entity:
namespace Plexus\User\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
*/
class User
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(name="id", type="int")
* #var int
*/
protected $id;
/**
* #ORM\Column(name="email", type="string", length=255)
* #var string
*/
protected $email;
/**
* #ORM\Column(name="unverifiedEmail", type="string", length=255, nullable=true)
* #var string
*/
protected $unverifiedEmail;
/**
* #ORM\Column(name="unverifiedEmailHash", type="string", length=255, nullable=true)
* #var string
*/
protected $verifyEmailHash;
/**
* #var string
* At this time, http://php.net/manual/en/function.password-hash.php recommends using 255 length for hashes
* #ORM\Column(name="passwordHash", type="string", length=255)
*/
protected $passwordHash;
/**
* #var string
* #ORM\Column(name="passwordResetHash", type="string", length=255, nullable=true)
*/
protected $passwordResetHash;
/**
* #return mixed
*/
public function getUnverifiedEmail()
{
return $this->unverifiedEmail;
}
/**
* #param mixed $unverifiedEmail
*/
public function setUnverifiedEmail($unverifiedEmail)
{
$this->unverifiedEmail = $unverifiedEmail;
}
/**
* #return mixed
*/
public function getVerifyEmailHash()
{
return $this->verifyEmailHash;
}
/**
* #param mixed $verifyEmailHash
*/
public function setVerifyEmailHash($verifyEmailHash)
{
$this->verifyEmailHash = $verifyEmailHash;
}
/**
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* #param string $email
*/
public function setEmail($email)
{
$this->email = $email;
}
/**
* #return string
*/
public function getPasswordHash()
{
return $this->passwordHash;
}
/**
* #param string $passwordHash
*/
public function setPasswordHash($passwordHash)
{
$this->passwordHash = $passwordHash;
}
/**
* #return string
*/
public function getPasswordResetHash(): string
{
return $this->passwordResetHash;
}
/**
* #param string $passwordResetHash
*/
public function setPasswordResetHash(string $passwordResetHash)
{
$this->passwordResetHash = $passwordResetHash;
}
/**
* #return mixed
*/
public function getId()
{
return $this->id;
}
/**
* #param mixed $id
*/
public function setId($id)
{
$this->id = $id;
}
public function toArray()
{
return [
'email' => $this->getEmail(),
];
}
}
Error:
Doctrine\DBAL\Exception\NotNullConstraintViolationException: An exception occurred while executing 'INSERT INTO user (unverifiedEmail, unverifiedEmailHash, passwordHash, passwordResetHash) VALUES (?, ?, ?, ?)' with params [null, null, "$2y$10$pRDv8NFXaCxF7\/ZUzL.ZuulsFqdwTs9IOycWTHYA.1Q0qpFu5uGXe", null]:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'unverifiedEmail' cannot be null in file /var/www/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/AbstractMySQLDriver.php on line 118
Stack trace:
1. Doctrine\DBAL\Exception\NotNullConstraintViolationException->() /var/www/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/AbstractMySQLDriver.php:118
2. Doctrine\DBAL\Driver\AbstractMySQLDriver->convertException() /var/www/vendor/doctrine/dbal/lib/Doctrine/DBAL/DBALException.php:176
3. Doctrine\DBAL\DBALException->wrapException() /var/www/vendor/doctrine/dbal/lib/Doctrine/DBAL/DBALException.php:150
4. Doctrine\DBAL\DBALException->driverExceptionDuringQuery() /var/www/vendor/doctrine/dbal/lib/Doctrine/DBAL/Statement.php:177
5. Doctrine\DBAL\Driver\PDOException->() /var/www/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOStatement.php:107
6. PDOException->() /var/www/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOStatement.php:105
7. PDOStatement->execute() /var/www/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOStatement.php:105
8. Doctrine\DBAL\Driver\PDOStatement->execute() /var/www/vendor/doctrine/dbal/lib/Doctrine/DBAL/Statement.php:168
9. Doctrine\DBAL\Statement->execute() /var/www/vendor/doctrine/orm/lib/Doctrine/ORM/Persisters/Entity/BasicEntityPersister.php:283
10. Doctrine\ORM\Persisters\Entity\BasicEntityPersister->executeInserts() /var/www/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php:1051
11. Doctrine\ORM\UnitOfWork->executeInserts() /var/www/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php:386
12. Doctrine\ORM\UnitOfWork->commit() /var/www/vendor/doctrine/orm/lib/Doctrine/ORM/EntityManager.php:358
13. Doctrine\ORM\EntityManager->flush() /var/www/vendor/plexus/user-lib/src/Service/UserServiceDoctrine.php:53
14. Plexus\User\Service\UserServiceDoctrine->saveUser() /var/www/vendor/plexus/user-lib/src/Service/UserService.php:27
15. Plexus\User\Service\UserService->setPassword() /var/www/vendor/plexus/user-lib/src/Service/UserServiceDoctrine.php:43
16. Plexus\User\Service\UserServiceDoctrine->createUser() /var/www/src/App/src/Action/CreateUserAction.php:39
17. App\Action\CreateUserAction->process() /var/www/vendor/zendframework/zend-expressive/src/Middleware/LazyLoadingMiddleware.php:62
...
Any help would be greatly appreciated. I can't think of what would cause this.
So the issue, it turns out, is that Doctrine was caching my entities and probably had a hold of a stale entity. I figured this out because I added the id field but it wasn't showing up at all. I destroyed and recreated my Vagrant box, and it worked.
So I added this if statement around the cache adapter:
if (!$isDevMode) {
// Cache
$cache = $container->get(Cache::class);
$doctrine->setQueryCacheImpl($cache);
$doctrine->setResultCacheImpl($cache);
$doctrine->setMetadataCacheImpl($cache);
}
and I set $isDevMode to true.

Magento 2 Custom Customer Attribute not Displaying

I have been attempting to create a custom customer attribute that would allow the customer to save an attribute to their profile. When I update my Magento site with the code, I see no front end change nor do I see any update in my Database. What am I doing incorrectly that is causing both of these issues? Do I need to add some .phtml change?
InstallData.php
<?php
namespace SR\DeliveryDate\Setup;
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;
/**
* #codeCoverageIgnore
*/
class InstallData implements InstallDataInterface
{
/**
* #var CustomerSetupFactory
*/
protected $customerSetupFactory;
/**
* #var AttributeSetFactory
*/
private $attributeSetFactory;
/**
* #param CustomerSetupFactory $customerSetupFactory
* #param AttributeSetFactory $attributeSetFactory
*/
public function __construct(
CustomerSetupFactory $customerSetupFactory,
AttributeSetFactory $attributeSetFactory
) {
$this->customerSetupFactory = $customerSetupFactory;
$this->attributeSetFactory = $attributeSetFactory;
}
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
/** #var CustomerSetup $customerSetup */
$customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);
$customerEntity = $customerSetup->getEavConfig()->getEntityType('customer');
$attributeSetId = $customerEntity->getDefaultAttributeSetId();
/** #var $attributeSet AttributeSet */
$attributeSet = $this->attributeSetFactory->create();
$attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);
$customerSetup->addAttribute(Customer::ENTITY, 'custom_attribute', [
'type' => 'varchar',
'label' => 'Custom Attributeeee',
'input' => 'text',
'required' => false,
'visible' => true,
'user_defined' => true,
'position' =>999,
'system' => 0,
]);
$attribute = $customerSetup->getEavConfig()->getAttribute(Customer::ENTITY, 'custom_attribute')
->addData([
'attribute_set_id' => $attributeSetId,
'attribute_group_id' => $attributeGroupId,
'used_in_forms' => ['adminhtml_customer', 'customer_address_edit'],//you can use other forms also ['adminhtml_customer_address', 'customer_address_edit', 'customer_register_address']
]);
$attribute->save();
}
}
Please try this:
\magento2\app\code\Custom\CustomerAttribute\Block\Widget\Passport.php
/**
* #return bool
*/
public function isEnabled() {
$attributeMetadata = $this->_getAttribute('passport');
return $attributeMetadata ? (bool) $attributeMetadata->isVisible() : false;
}
Try to run the following commands after you make any major changes to your code. For example, if you create an extension, you might run the upgrade command.
php bin/magento setup:upgrade
php bin/magento setup:static-content:deploy
php bin/magento cache:clean or php bin/magento cache:flush
The above commands should be run in the console.

Laravel : Overwrite Socialite Provider to add new fields

I want to extend/overwrite my LinkedInProvider.php (in vendor\laravel\socialite\src\Two) to add new fields in the Linkedin Request.
I've create a new LinkedInProvider.php (in app\Providers) with the following code :
namespace App\Providers;
use Illuminate\Support\Arr;
use Illuminate\Http\Request;
use Laravel\Socialite\Two\AbstractProvider;
use Laravel\Socialite\Two\ProviderInterface;
use Laravel\Socialite\Two\User;
class LinkedInProvider extends AbstractProvider implements ProviderInterface
{
/**
* The scopes being requested.
*
* #var array
*/
protected $scopes = ['r_basicprofile', 'r_emailaddress'];
/**
* The separating character for the requested scopes.
*
* #var string
*/
protected $scopeSeparator = ' ';
/**
* The fields that are included in the profile.
*
* #var array
*/
protected $fields = [
'id', 'first-name', 'last-name', 'formatted-name',
'email-address', 'headline', 'location', 'industry', 'positions',
'public-profile-url', 'picture-url', 'picture-urls::(original)',
];
/**
* {#inheritdoc}
*/
protected function getAuthUrl($state)
{
return $this->buildAuthUrlFromBase('https://www.linkedin.com/oauth/v2/authorization', $state);
}
/**
* {#inheritdoc}
*/
protected function getTokenUrl()
{
return 'https://www.linkedin.com/oauth/v2/accessToken';
}
/**
* Get the POST fields for the token request.
*
* #param string $code
* #return array
*/
protected function getTokenFields($code)
{
return parent::getTokenFields($code) + ['grant_type' => 'authorization_code'];
}
/**
* {#inheritdoc}
*/
protected function getUserByToken($token)
{
$fields = implode(',', $this->fields);
$url = 'https://api.linkedin.com/v1/people/~:('.$fields.')';
$response = $this->getHttpClient()->get($url, [
'headers' => [
'x-li-format' => 'json',
'Authorization' => 'Bearer '.$token,
],
]);
return json_decode($response->getBody(), true);
}
/**
* {#inheritdoc}
*/
protected function mapUserToObject(array $user)
{
return (new User)->setRaw($user)->map([
'id' => $user['id'], 'nickname' => null, 'name' => Arr::get($user, 'formattedName'),
'email' => Arr::get($user, 'emailAddress'), 'avatar' => Arr::get($user, 'pictureUrl'),
'avatar_original' => Arr::get($user, 'pictureUrls.values.0'),
]);
}
/**
* Set the user fields to request from LinkedIn.
*
* #param array $fields
* #return $this
*/
public function fields(array $fields)
{
$this->fields = $fields;
return $this;
}
}
But now, I've got this error :
Type error: Argument 1 passed to Laravel\Socialite\Two\AbstractProvider::__construct() must be an instance of Illuminate\Http\Request, instance of Illuminate\Foundation\Application given, called in G:\laragon\www\localhost\vendor\laravel\framework\src\Illuminate\Foundation\ProviderRepository.php on line 201
I know I can install Socialite Manager, but I just want to overwrite the fields list to add new field (like position and industry)
You shouldn't have to overwrite/extend the whole class. In the Laravel\Socialite\Two\User object that is being created, there is a $user property, which contains the raw information the provider sent back.
When making the request, you can set the fields you want LinkedIn to return in your controller method:
public function redirectToProvider()
{
$fields = [
'id', 'first-name', 'last-name', 'formatted-name',
'email-address', 'headline', 'location', 'industry',
'public-profile-url', 'picture-url', 'picture-urls:(original)',
'positions', 'summary' // <-- additional fields here
];
return Socialite::driver('linkedin')->fields($fields)->redirect();
}
You can see two additional fields being requested, positions and summary, which aren't included by default.
Happy hacking!

Resources