Magento 2:以编程方式创建客户

本文说明如何在Magento 2.x中以编程方式(通过代码)创建客户。

在此示例代码中,我将展示如何使用常规信息(例如名字,姓氏和电子邮件)保存客户。我还将展示如何保存客户地址(帐单地址和收货地址)。

我将展示Magento 2中的两种编程方式,即

–通过依赖注入
–通过对象管理器

使用依赖注入创建客户

请注意,在此示例中,我的自定义模块“ HelloWorld ”路径为:app / code / Chapagain / HelloWorld /

我有一个Add控制器文件,可以按以下方式浏览:
http://127.0.0.1/magento2/helloworld/customer/add

浏览此路径将显示一个表单,并且其作用是对Addpost控制器的。

Addpost此示例的控制器文件是:

app / code / Chapagain / HelloWorld / Customer / Addpost.php


2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
<?php
namespace Chapagain\HelloWorld\Controller\Customer;
 
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Customer\Model\CustomerFactory;
use Magento\Customer\Model\AddressFactory;
use Magento\Framework\Message\ManagerInterface;
use Magento\Framework\Escaper;
use Magento\Framework\UrlFactory;
use Magento\Customer\Model\Session;
use Magento\Customer\Model\Registration;
use Magento\Framework\Data\Form\FormKey\Validator;
use Magento\Framework\App\ObjectManager;
 
class Addpost extends \Magento\Framework\App\Action\Action
{
    /**
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    protected $storeManager;
 
    /**
     * @var \Magento\Customer\Model\CustomerFactory
     */
    protected $customerFactory;
 
    /**
     * @var \Magento\Customer\Model\AddressFactory
     */
    protected $addressFactory;
 
    /**
     * @var \Magento\Framework\Message\ManagerInterface
     */
    protected $messageManager;
 
    /**
     * @var \Magento\Framework\Escaper
     */
    protected $escaper;
 
    /**
     * @var \Magento\Framework\UrlFactory
     */
    protected $urlFactory;
 
    /**
     * @var \Magento\Customer\Model\Session
     */
    protected $session;
 
    /**
     * @var Magento\Framework\Data\Form\FormKey\Validator
     */
    private $formKeyValidator;
 
    /**
     * @param Context $context
     * @param StoreManagerInterface $storeManager
     * @param CustomerFactory $customerFactory
     * @param AddressFactory $addressFactory
     * @param ManagerInterface $messageManager
     * @param Escaper $escaper
     * @param UrlFactory $urlFactory
     * @param Session $session
     * @param Validator $formKeyValidator
     */
    public function __construct(
        Context $context,
        StoreManagerInterface $storeManager,
        CustomerFactory $customerFactory,
        AddressFactory $addressFactory,
        ManagerInterface $messageManager,
        Escaper $escaper,
        UrlFactory $urlFactory,
        Session $session,
        Validator $formKeyValidator = null
    )
    {
        $this->storeManager     = $storeManager;
        $this->customerFactory  = $customerFactory;
        $this->addressFactory   = $addressFactory;
        $this->messageManager   = $messageManager;
        $this->escaper          = $escaper;
        $this->urlModel         = $urlFactory->create();
        $this->session          = $session;
        $this->formKeyValidator = $formKeyValidator ?: ObjectManager::getInstance()->get(Validator::class);
        
        // messageManager can also be set via $context
        // $this->messageManager   = $context->getMessageManager();
 
        parent::__construct($context);
    }
 
    /**
     * Default customer account page
     *
     * @return void
     */
    public function execute()
    {
        /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
        $resultRedirect = $this->resultRedirectFactory->create();
        // if ($this->session->isLoggedIn() || !$this->registration->isAllowed()) {
        //     $resultRedirect->setPath('*/*/');
        //     return $resultRedirect;
        // }
        
        // check if the form is actually posted and has the proper form key
        if (!$this->getRequest()->isPost() || !$this->formKeyValidator->validate($this->getRequest())) {
            $url = $this->urlModel->getUrl('*/*/add', ['_secure' => true]);
            $resultRedirect->setUrl($this->_redirect->error($url));
            return $resultRedirect;
        }
 
        $websiteId  = $this->storeManager->getWebsite()->getWebsiteId();
 
        $firstName = 'John';
        $lastName = 'Doe';
        $email = 'johndoe4@example.com';
        $password = 'Test1234';
 
        // instantiate customer object
        $customer = $this->customerFactory->create();
        $customer->setWebsiteId($websiteId);
        
        // check if customer is already present
        // if customer is already present, then show error message
        // else create new customer
        if ($customer->loadByEmail($email)->getId()) {
            //echo 'Customer with the email ' . $email . ' is already registered.';
            $message = __(
                'There is already an account with this email address "%1".',
                $email
            );
            // @codingStandardsIgnoreEnd
            $this->messageManager->addError($message);
        } else {
            try {
                // prepare customer data
                $customer->setEmail($email); 
                $customer->setFirstname($firstName);
                $customer->setLastname($lastName);
 
                // set null to auto-generate password
                $customer->setPassword($password); 
 
                // set the customer as confirmed
                // this is optional
                // comment out this line if you want to send confirmation email
                // to customer before finalizing his/her account creation
                $customer->setForceConfirmed(true);
                
                // save data
                $customer->save();
                
                // save customer address
                // this is optional
                // you can skip saving customer address while creating the customer
                $customerAddress = $this->addressFactory->create();                
                $customerAddress->setCustomerId($customer->getId())
                                ->setFirstname($firstName)
                                ->setLastname($lastName)
                                ->setCountryId('US')
                                ->setRegionId('12') // optional, depends upon Country, e.g. USA
                                ->setRegion('California') // optional, depends upon Country, e.g. USA
                                ->setPostcode('90232')
                                ->setCity('Culver City')
                                ->setTelephone('888-888-8888')
                                ->setFax('999')
                                ->setCompany('XYZ')
                                ->setStreet(array(
                                    '0' => 'Your Customer Address 1', // compulsory
                                    '1' => 'Your Customer Address 2' // optional
                                )) 
                                ->setIsDefaultBilling('1')
                                ->setIsDefaultShipping('1')
                                ->setSaveInAddressBook('1');
                
                try {
                    // save customer address
                    $customerAddress->save();
                } catch (Exception $e) {
                    $this->messageManager->addException($e, __('We can\'t save the customer address.'));
                }                
 
                // send welcome email to the customer
                $customer->sendNewAccountEmail();
 
                //echo 'Customer with the email ' . $email . ' is successfully created.';
 
                $this->messageManager->addSuccess(
                    __(
                        'Customer account with email %1 created successfully.',
                        $email
                    )
                );
                
                $url = $this->urlModel->getUrl('*/*/add', ['_secure' => true]);
                $resultRedirect->setUrl($this->_redirect->success($url));
                
                //$resultRedirect->setPath('*/*/');
                return $resultRedirect;
            } catch (StateException $e) {
                $url = $this->urlModel->getUrl('customer/account/forgotpassword');
                // @codingStandardsIgnoreStart
                $message = __(
                    'There is already an account with this email address. If you are sure that it is your email address, <a href="%1">click here</a> to get your password and access your account.',
                    $url
                );
                // @codingStandardsIgnoreEnd
                $this->messageManager->addError($message);
            } catch (InputException $e) {
                $this->messageManager->addError($this->escaper->escapeHtml($e->getMessage()));
                foreach ($e->getErrors() as $error) {
                    $this->messageManager->addError($this->escaper->escapeHtml($error->getMessage()));
                }
            } catch (LocalizedException $e) {
                $this->messageManager->addError($this->escaper->escapeHtml($e->getMessage()));
            } catch (\Exception $e) {
                $this->messageManager->addException($e, __('We can\'t save the customer.'));
            }
        }
 
        $this->session->setCustomerFormData($this->getRequest()->getPostValue());
        $defaultUrl = $this->urlModel->getUrl('*/*/add', ['_secure' => true]);
        $resultRedirect->setUrl($this->_redirect->error($defaultUrl));
        return $resultRedirect;
    }
}
?>

使用对象管理器创建客户

使用对象管理器的代码可以写在任何文件中,例如控制器文件,块文件,甚至模板(.phtml)文件中。但是,不建议使用对象管理器。建议使用上面显示的依赖项注入进行编码。

$objectManager =  \Magento\Framework\App\ObjectManager::getInstance();        
$appState = $objectManager->get('\Magento\Framework\App\State');
//$appState->setAreaCode('frontend'); // not needed if Area code is already set
 
$storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
$websiteId = $storeManager->getStore()->getWebsiteId();
 
$firstName = 'John';
$lastName = 'Doe';
$email = 'johndoe10@example.com';
$password = 'Test1234';
 
// instantiate customer object
$customer = $objectManager->get('\Magento\Customer\Model\CustomerFactory')->create();
$customer->setWebsiteId($websiteId);
 
// if customer is already created, show message
// else create customer
if ($customer->loadByEmail($email)->getId()) {
    echo 'Customer with email '.$email.' is already registered.';  
} else {
    try {        
        // prepare customer data
        $customer->setEmail($email); 
        $customer->setFirstname($firstName);
        $customer->setLastname($lastName);
 
        // set null to auto-generate password
        $customer->setPassword($password); 
 
        // set the customer as confirmed
        // this is optional
        // comment out this line if you want to send confirmation email
        // to customer before finalizing his/her account creation
        $customer->setForceConfirmed(true);
        
        // save data
        $customer->save();
        
        // save customer address
        // this is optional
        // you can skip saving customer address while creating the customer
        $customerAddress = $objectManager->get('\Magento\Customer\Model\AddressFactory')->create();
        $customerAddress->setCustomerId($customer->getId())
                        ->setFirstname($firstName)
                        ->setLastname($lastName)
                        ->setCountryId('US')
                        ->setRegionId('12') // optional, depends upon Country, e.g. USA
                        ->setRegion('California') // optional, depends upon Country, e.g. USA
                        ->setPostcode('90232')
                        ->setCity('Culver City')
                        ->setTelephone('888-888-8888')
                        ->setFax('999')
                        ->setCompany('XYZ')
                        ->setStreet(array(
                            '0' => 'Your Customer Address 1', // compulsory
                            '1' => 'Your Customer Address 2' // optional
                        )) 
                        ->setIsDefaultBilling('1')
                        ->setIsDefaultShipping('1')
                        ->setSaveInAddressBook('1');
        
        try {
            // save customer address
            $customerAddress->save();
        } catch (Exception $e) {
            echo 'Cannot save customer address.';
        }                
 
        // send welcome email to the customer
        $customer->sendNewAccountEmail();
 
        echo 'Customer with the email ' . $email . ' is successfully created.';
 
    } catch (Exception $e) {
        echo $e->getMessage();
    }
}

希望这可以帮助。谢谢。

赞(0)
微信
支付宝
微信二维码图片

微信扫描二维码打赏

支付宝二维码图片

支付宝扫描二维码打赏

相关文章

0 0 投票数
文章评分
订阅评论
提醒
0 评论
内联反馈
查看所有评论