Invalid Value provided for RegionId field in Magento 2 - php

I am getting this error while the controller run -'Invalid value of "491" provided for the regionId field.'. I want to transfer the telephone number from the billing address to the customer mobile number field and for that I have built this controller
My controller code is :
<?php
namespace [Vendor]\[Extension]\Controller\Adminhtml\Index;
use [Vendor]\[Extension]\Helper\Data;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Controller\Result\JsonFactory;
class Update extends Action
{
protected $_customerRepoInterface;
protected $_customerFactory;
public function __construct(
Context $context,
Data $helper,
JsonFactory $resultJsonFactory,
\Magento\Customer\Api\CustomerRepositoryInterface $customerRepoInterface,
\Magento\Customer\Model\CustomerFactory $customerFactory
)
{
$this->resultJsonFactory = $resultJsonFactory;
$this->helper = $helper;
$this->_customerRepoInterface = $customerRepoInterface;
$this->_customerFactory = $customerFactory;
parent::__construct($context);
}
public function execute()
{
$result = $this->resultJsonFactory->create();
$customerCollectoin = $this->_customerFactory->create()->getCollection()
->addAttributeToSelect("*")
->load();
foreach ($customerCollectoin as $customer){
if($customer->getPrimaryBillingAddress()) {
if ($customer->getPrimaryBillingAddress()->getTelephone()) {
$telephone = $customer->getPrimaryBillingAddress()->getTelephone();
$customerObj = $this->_customerRepoInterface->getById($customer->getId());
$customerObj->setCustomAttribute('mobilenumber', $telephone);
$this->_customerRepoInterface->save($customerObj);
}
}
}
return $result->setData( count($customerCollectoin));
}
protected function _isAllowed()
{
return true;
}
}
~~Thank you in advance!
enter code here

Related

Laravel send mail on each Orderplaced

I have below Order Controller and have created Mailable as well. I am stuck at point what argument should be passed so I can pass data on shipped.blade file. I have gone through few examples but couldn't get it working.
Also, where should I use foreach function to attach all items for which order is placed.
class Order extends Controller
{
public function addOrder(Request $req)
{
// User detail
$results = DB::table('users')->get()->where('id' , $req->input('user_id'));
foreach($results as $userrow) {
$address_id = $userrow->address;
}
// Address
$address_query = DB::table('shippings')->get()->where('id' , $address_id);
foreach($address_query as $ad_row) {
$address = $ad_row->address;
$name = $ad_row->name;
}
// Generate Orderid
$order_id = mt_rand();
// Bag total
$amount = DB::table('bag')->where('user_id' , $req->input('user_id'))->where('order_id', 0)->sum('bag.sale_price');
// add order
// get user email
$emailId = DB::table('users')->where('id' , $req->input('user_id'))->value('email');
$addAddress = DB::table('orders')->insert([
'email' => $emailId,
'user_id' => $req->input('user_id'),
'name' => $req->input('name'),
'order_id' => $order_id,
'payment_method'=> $req->input('payment_method'),
'mobile_number'=> $req->input('mobile_number'),
'pincode'=> $req->input('pincode'),
'city'=> $req->input('city'),
'state'=> $req->input('state'),
'house_number'=> $req->input('house_number'),
'address_area'=> $req->input('address_area'),
'landmark'=> $req->input('landmark'),
'amount'=> $amount
]);
if ($addAddress ==1) {
$response = array('message'=>"Order Added" , 'result'=>1);
//update bag items
$affected = DB::table('bag')->where('user_id', $req->input('user_id'))->where('order_id', 0)->update(['order_id' => $order_id]);
Mail::to($emailId)->send(new OrderShipped());
} else {
$response = array('message'=>"Problem in adding order" , 'result'=>0);
}
return $response;
}
}
OrderShipped Mailable
public function __construct()
{
//
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->from('orders#factory2homes.com', 'Factory2Homes')
->subject('New Order Received')
->bcc('mail#androidapp.factory2homes.com')
->markdown('emails.orders.shipped');
}
You create public properties on your mailable and then inject them via the constructor
public $prop1;
public $prop2;
...
public function __construct($arg1, $arg2, ...)
{
$this->prop1 = $arg1;
$this->prop2 = $arg2;
...
}
public function build()
{
return $this->from('orders#factory2homes.com', 'Factory2Homes')
->subject('New Order Received')
->bcc('mail#androidapp.factory2homes.com')
->markdown('emails.orders.shipped', ['arg1' => $this->prop1, 'arg2' => $this->prop2, ...]);
}
Mail::to($emailId)->send(new OrderShipped($arg1, $arg2, ...));

how can i get auth user or any session in the my custom class and provider?

i have to get the company which user chooses but i can't get user data in my class and provider boot function .
user can have more than one company so user have to choose a company for some operations. But as i said , i can't get the company which user chooses.
Like this :
public function boot()
{
$user = Auth::user();
dd( $user ); // return null;
$bid = new Bid();
$show = $bid->check();
Blade::directive('bid',function() use($show){
return "<?php if( $show ) { ?>";
});
Blade::directive('endbid',function(){
return '<?php } ?>';
});
}
My other class :
<?php
namespace App\Services\Buying\Package;
use App\Services\Buying\Package\PackageInterface;
use App\Models\Company\Company;
use Illuminate\Support\Facades\Session;
use Illuminate\Http\Request;
use App\User;
class PackageBuying extends PackageQuery implements PackageInterface
{
private $company_id;
public function __construct()
{
$user = Auth::user();
dd( $user ); // return null
$this->setCompanyId($this->company_id);
}
public function setSession( Request $request )
{
$request->session()->get('selected-company');
}
public function company()
{
return $this->company_id;
}
public function package()
{
if ( $this->check() ) {
return $this->getPackage($this->company())->first();
}
return [];
}
public function features()
{
return (object)json_decode( $this->package()->features );
}
public function importantFeatures()
{
return (object)json_decode( $this->package()->important_features );
}
public function active()
{
return (bool) $this->getPackage()->firstOrFail()->active;
}
}
Actually if i got user data in the provider boot function , i could send data to my class .
May you please help me ?
Thanks in advance.
Put the code inside your construct function to calMethod function like this
public function callAction( $method, $parameters ) {
$user = Auth::user();
dd( $user ); // return null
$this->setCompanyId($this->company_id);
return parent::callAction( $method, $parameters );
}

Problem when trying to validate email that already exists in database

I am building custom mvc framework in php in order to learn and when I am trying to submit my form with an mail that already exists in the database, my validation should prevent me to do so, instead I get this error:
Fatal error: Uncaught Error: Call to a member function findUserByEmail() on null in C:\xampp\htdocs\gacho\App\Controllers\UsersController.php:
UsersController.php
<?php
namespace App\Controllers;
use App\Models\User;
use Core\Controller;
class UsersController extends Controller
{
public function __construct($controller, $action)
{
parent::__construct($controller, $action);
$this->userModel = $this->load_model('User');
}
public function registerAction()
{
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$data = [
'email' => trim($_POST['email']),
];
}
if (empty($data['email'])) {
$data['email_err'] = "Please enter your email!!!";
} else {
if ($this->userModel->findUserByEmail($data['email'])) {
$data['email_err'] = "Email is already taken!";
}
}
}
User.php
<?php
namespace App\Models;
use Core\Database;
class User
{
private $db;
public function __construct()
{
$this->db = new Database();
}
public function findUserByEmail($email)
{
$this->db->query('SELECT * FROM users WHERE email = :email');
$this->db->bind(':email', $email);
$row = $this->db->single();
if ($this->db->rowCount() > 0) {
return true;
} else {
return false;
}
}
}
Controller.php:
<?php
namespace Core;
class Controller
{
protected $_controller;
protected $_action;
public $view;
public function __construct($controller, $action)
{
$this->_controller = $controller;
$this->_action = $action;
$this->view = new View();
}
protected function load_model($model)
{
$modelPath = 'App\Models\\' . $model;
if (class_exists($modelPath)) {
$this->{$model.'Model'} = new $modelPath();
}
}
}
I think the mistake is about $this->userModel , but I'm stuck and any help is appreciated.
The problem is that in __construct of UsersController you have:
$this->userModel = $this->load_model('User');
So you assign to userModel property the return value of load_model method.
load_model method doesn't return anything so $this->userModel is always set to NULL, doesn't matter if load_model succeeded or not.
You should just return new $modelPath(); in load_model if you want to assign it to a property by return value.
Also add throw new Exception($modelPath. 'not found'); at the end of load_model method to be sure it did load the model, and not just failed silently to find it.
Note that $this->userModel is not the same as $this->UserModel (case sensitive) and $modelPath = 'App\Models\\' . $model; - why \ after App, and two \ after Models?
I think you need to access your model in $this->UserModel, since User was passed into the load_model method.

Yii2 save() creating DB row with default values

I am trying to implement a login method using OpenID, and the $_SESSION var's are posting correctly - and through those I am simply trying to register users in MySQL. For some reason, when passing through the 'login' action in my controller ::
public function actionLogin()
{
if (!Yii::$app->user->isGuest) {
return $this->goHome();
}
include ('../views/user-record/steamauth/userInfo.php');
$steamid = $_SESSION['steam_steamid'];
$username = $_SESSION['steam_personaname'];
$profileurl = $_SESSION['steam_profileurl'];
$avatar = $_SESSION['steam_avatar'];
$avatarmedium = $_SESSION['steam_avatarmedium'];
$avatarfull = $_SESSION['steam_avatarfull'];
$user = UserRecord::findBySteamId($steamid);
if ($user === null)
{
$user = new UserRecord();
$user->steamid = $steamid;
$user->username = $username;
$user->profileurl = $profileurl;
$user->avatar = $avatar;
$user->avatarmedium = $avatarmedium;
$user->avatarfull = $avatarfull;
$user->verified = 0;
$user->banned = 0;
$user->save();
}
Yii::$app->user->login($user, 604800);
return $this->redirect(Yii::$app->user->returnUrl);
}
EDIT: Here is the UserRecord class, forgot to add it in.
<?php
namespace app\models;
class UserRecord extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface
{
public $id;
public $steamid;
public $username;
public $profileurl;
public $avatar;
public $avatarmedium;
public $avatarfull;
public $verified;
public $banned;
public $rank;
public $authKey;
// public $password;
// public $accessToken;
public static function tableName()
{
return 'users';
}
public function getAuthKey()
{
return $this->authKey;
}
public function getId()
{
return $this->id;
}
public function validateAuthKey($authKey)
{
return $this->authKey === $authKey;
}
public static function findIdentity($id)
{
return self::findOne($id);
}
public function validateSteamID($steamid)
{
return $this->steamid === $steamid;
}
public static function findIdentityByAccessToken($token, $type = null)
{
throw new \yii\base\NotSupportedException;
}
public static function findBySteamId($steamid)
{
return self::findOne(['steamid' => $steamid]);
}
}
The result is simply a posted row, with none of the data entered.
Any help would be greatly appreciated, thank you.
If you have redefine the same columns name using public vars these override the vars for activeRecord and then are saved only empty value ..
if this you must remove the (redifined) public vars in your model
otherwise if you have no rules then
Try adding safe at the attribute in you model rules
public function rules()
{
return [
[['steamid', 'username', 'profileurl', 'avatar', 'avatarmedium',
'avatarfull', 'verified', 'banned', 'rank', 'authKey',], 'safe'],
];
}
Declaring 'public' variables made the save() ignore the data being posted. Thanks.

Get distinct attribute from database in Laravel

I have two tables, one called "products" and another "product_brands".
A product has one brand, and a brand can belong to many products.
I have:
class Product extends Eloquent {
protected $table = 'products';
public function type() {
return $this->hasOne('ProductTypes');
}
public function brand()
{
return $this->hasOne('ProductBrands', 'id', 'brand_id');
}
public function image() {
return $this->hasMany('ProductImages');
}
public function toArray() {
$ar = $this->attributes;
$ar['type'] = $this->type;
$ar['brand'] = $this->brand;
return $ar;
}
public function getBrandAttribute() {
$brand = $this->brand()->first();
return (isset($brand->brand) ? $brand->brand : '');
}
}
And my controller:
class ProductsController extends BaseController {
public function index($type_id) {
$Product = new Product;
$products = $Product->where('type_id', $type_id)->get();
return View::make('products.products', array('products' => $products));
}
}
Ideally I would like the column from "product_brands" to be in the same array as the columns from "products", hence why I am trying that stuff with toArray() and getBrandAttribute() but it isn't working.
How can I do this?
I'm sure the getBrandAttribute accessor collides with the brand relationship. Try this instead:
class Product extends Eloquent {
protected $table = 'products';
public function type() {
return $this->hasOne('ProductTypes');
}
public function productBrand() {
return $this->hasOne('ProductBrands', 'id', 'brand_id');
}
public function image() {
return $this->hasMany('ProductImages');
}
public function getBrandAttribute() {
$brand = $this->productBrand()->first();
return (isset($brand->brand) ? $brand->brand : '');
}
protected $appends = array('brand'); // this makes Laravel include the property in toArray
}
You should change your accessor to other name:
public function getSpecBrandAttribute() {
$brand = $this->brand()->first();
return (isset($brand->brand) ? $brand->brand : '');
}
and in toArray you should then use:
public function toArray() {
$ar = $this->attributes;
$ar['type'] = $this->type;
$ar['brand'] = $this->spec_brand;
return $ar;
}
That's because you shouldn't create fields with the same name as relationship name.
In addition as it's one to many relationship, probably for brand() you should use belongsTo and not hasOne

Categories