How to override ImageFactory in Magento 2.3.3 - module

i have my module which is overriding product in images in product list page (it is loading product images from custom attribute).
In Magento 2.2.x there was file vendor/magento/module-catalog/Block/Product/ImageBuilder.php which you can override and then use your own product image, in my case loaded from custom attribute.
class ImageBuilder extends \Magento\Catalog\Block\Product\ImageBuilder
{
public function create()
{
/** #var \Magento\Catalog\Helper\Image $helper */
$helper = $this->helperFactory->create()
->init($this->product, $this->imageId);
$template = $helper->getFrame()
? 'Magento_Catalog::product/image.phtml'
: 'Magento_Catalog::product/image_with_borders.phtml';
$imagesize = $helper->getResizedImageInfo();
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->create('Magento\Catalog\Model\Product')->load($this->product->getId());
$url = $product->getData('MY_OWN_ATTRIBUTE');
if (trim($url) == '')
{
$url = $helper->getUrl();
}
$data = [
'data' => [
'template' => $template,
'image_url' => $url,
'width' => $helper->getWidth(),
'height' => $helper->getHeight(),
'label' => $helper->getLabel(),
'ratio' => $this->getRatio($helper),
'custom_attributes' => $this->getCustomAttributes(),
'resized_image_width' => !empty($imagesize[0]) ? $imagesize[0] : $helper->getWidth(),
'resized_image_height' => !empty($imagesize[1]) ? $imagesize[1] : $helper->getHeight()
],
];
return $this->imageFactory->create($data);
}
}
In Magento 2.3.3 this code was moved into vendor/magento/module-catalog/Block/Product/ImageFactory.php
Even if i copy whole file and overrride it under my module (without any changes), product list page wont load and i dont see any errors. It just look like this:
This is how look ImageFactory.php under my module:
<?php
namespace MY_COMPANY\MY_MODULE\Block\Product;
use Magento\Catalog\Block\Product\Image as ImageBlock;
use Magento\Catalog\Model\View\Asset\ImageFactory as AssetImageFactory;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\Product\Image\ParamsBuilder;
use Magento\Catalog\Model\View\Asset\PlaceholderFactory;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\View\ConfigInterface;
use Magento\Catalog\Helper\Image as ImageHelper;
class ImageFactory extends \Magento\Catalog\Block\Product\ImageFactory
{
/**
* #var ConfigInterface
*/
private $presentationConfig;
/**
* #var AssetImageFactory
*/
private $viewAssetImageFactory;
/**
* #var ParamsBuilder
*/
private $imageParamsBuilder;
/**
* #var ObjectManagerInterface
*/
private $objectManager;
/**
* #var PlaceholderFactory
*/
private $viewAssetPlaceholderFactory;
/**
* #param ObjectManagerInterface $objectManager
* #param ConfigInterface $presentationConfig
* #param AssetImageFactory $viewAssetImageFactory
* #param PlaceholderFactory $viewAssetPlaceholderFactory
* #param ParamsBuilder $imageParamsBuilder
*/
public function __construct(
ObjectManagerInterface $objectManager,
ConfigInterface $presentationConfig,
AssetImageFactory $viewAssetImageFactory,
PlaceholderFactory $viewAssetPlaceholderFactory,
ParamsBuilder $imageParamsBuilder
) {
$this->objectManager = $objectManager;
$this->presentationConfig = $presentationConfig;
$this->viewAssetPlaceholderFactory = $viewAssetPlaceholderFactory;
$this->viewAssetImageFactory = $viewAssetImageFactory;
$this->imageParamsBuilder = $imageParamsBuilder;
}
public function create(Product $product, string $imageId, array $attributes = null): ImageBlock
{
$viewImageConfig = $this->presentationConfig->getViewConfig()->getMediaAttributes(
'Magento_Catalog',
ImageHelper::MEDIA_TYPE_CONFIG_NODE,
$imageId
);
$imageMiscParams = $this->imageParamsBuilder->build($viewImageConfig);
$originalFilePath = $product->getData($imageMiscParams['image_type']);
if ($originalFilePath === null || $originalFilePath === 'no_selection') {
$imageAsset = $this->viewAssetPlaceholderFactory->create(
[
'type' => $imageMiscParams['image_type']
]
);
} else {
$imageAsset = $this->viewAssetImageFactory->create(
[
'miscParams' => $imageMiscParams,
'filePath' => $originalFilePath,
]
);
}
$data = [
'data' => [
'template' => 'Magento_Catalog::product/image_with_borders.phtml',
'image_url' => $imageAsset->getUrl(),
'width' => $imageMiscParams['image_width'],
'height' => $imageMiscParams['image_height'],
'label' => $this->getLabel($product, $imageMiscParams['image_type']),
'ratio' => $this->getRatio($imageMiscParams['image_width'], $imageMiscParams['image_height']),
'custom_attributes' => $this->getStringCustomAttributes($attributes),
'class' => $this->getClass($attributes),
'product_id' => $product->getId()
],
];
return $this->objectManager->create(ImageBlock::class, $data);
}
}
Of course i have defined override in di.xml.
Question is: how can i override ImageFactory.php in my module ?
thanks

just asking: have You deleted content of generated?
like rm -rf ./generated/*
and cleared cache (especially config)
like:
bin/magento c:c
https://devdocs.magento.com/guides/v2.3/howdoi/php/php_clear-dirs.html

Related

Call id from product table in projects table as forignId name product_id in laravel-8

I have three tables named users, products and projects.
products and projects have one too many relationships
products have id this id belongs to many projects
This is my products.php table
Schema::create('products', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->text('detail');
$table->string('color');
$table->string('image');
$table->string('logo');
$table->unsignedBigInteger('user_id');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
This is projects.php thable
Schema::create('projects', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('chapter_name', 255)->nullable();
$table->string('sub_section_name', 500)->nullable();
$table->string('title_1', 255)->nullable();
$table->string('description_1', 5000)->nullable();
$table->string('image_1', 255)->nullable();
$table->string('image_2', 255)->nullable();
$table->string('image_3', 255)->nullable();
$table->string('title_2', 255)->nullable();
$table->string('description_2', 5000)->nullable();
$table->string('title_3', 255)->nullable();
$table->string('description_3', 255)->nullable();
$table->string('video_1', 255)->nullable();
$table->string('video_2', 255)->nullable();
$table->string('video_3', 255)->nullable();
$table->unsignedBigInteger ('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
// $table->foreignId('product_id')->nullable();
$table->unsignedBigInteger('product_id')->references('id')->on('products')->onDelete('cascade');
$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->nullable();
});
Here in my ProjectImport.php I want call product_id = id of products table
This is my ProjectImport.php
public function model(array $row)
{
return new Project([
'chapter_name' => $row['chapter_name'],
'sub_section_name' => $row['sub_section_name'],
'title_1' => $row['title_1'],
'description_1' => $row['description_1'],
'image_1' => $row['image_1'],
'image_2' => $row['image_2'],
'image_3' => $row['image_3'],
'title_2' => $row['title_2'],
'description_2' => $row['description_2'],
'title_3' => $row['title_3'],
'description_3' => $row['description_3'],
'video_1' => $row['video_1'],
'video_2' => $row['video_2'],
'video_3' => $row['video_3'],
'user_id' => auth()->user()->id,
'product_id' => Product::where('user_id',Auth::id())->pluck('id') // Here i want product_id = product table id
// 'product_id' => id()->id
]);
}
The relationship is one to many and one to many. Here user have many products with id and every products can have many projects.
This is ProductController.php
<?php
namespace App\Http\Controllers;
use App\Models\Product;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
class ProductController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
// public function indexGetProducts(){
// return User::find(auth()->user()->id)->getProducts;
// }
public function index()
{
// $products = Product::latest()->paginate(20);
$products = Product::where('user_id',auth()->user()->id)->latest()->paginate(20);
return view('products.index',compact('products'))
->with('i', (request()->input('page', 1) - 1) * 5);
// $products= Product::where('user_id',auth()->user()->id)->orderby('created_at','desc')->get();
// return view('products.index',compact('products'))->with('i', (request()->input('page', 5) - 1) * 5);
}
function authapi(Request $request)
{
$user = User:: where('email', $request->email)->first();
if(!$user || !Hash::check($request->password, $user->password)){
return response([
'message' => ['These credentials do not match our records.']
],404);
}
$token = $user -> createToken('my-app-token')->plainTextToken;
$response = [
'user' => $user,
'token' => $token
];
return response($response,201);
}
function all_app_jsons(){
// return Product::all();
return User::find(auth()->user()->id)->getProducts;
}
function search_by_name($name){
return Product::where('name','like','%'.$name.'%')->get();
}
function search_by_id($id){
return Product::where('id',$id)->
where('user_id',auth()->user()->id)->get();
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('products.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//$tag = Product::create($request->all());
//return redirect()->route('admin.tags.index');
$request->validate([
'name' => 'required',
'detail' => 'required',
'color' => 'required',
'image' => 'required|image|mimes:png,jpg,jpeg|dimensions:width=1080,height=1920|max:2048',
'logo' => 'required|image|mimes:png,jpg,jpeg|dimensions:width=512,height=512|max:1024',
]);
$input = $request->all();
// $request->validated();
$input['user_id'] = auth()->user()->id;
if ($image = $request->file('image')) {
$destinationPath = 'image/';
$profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
$image->move($destinationPath, $profileImage);
$input['image'] = "$profileImage";
}
if ($logo = $request->file('logo')) {
$destinationPath = 'logo/';
$profileLogo = date('YmdHis') . "." . $logo->getClientOriginalExtension();
$logo->move($destinationPath, $profileLogo);
$input['logo'] = "$profileLogo";
}
Product::create($input);
return redirect()->route('projects.index')
->with('success','Product created successfully.');
}
/**
* Display the specified resource.
*
* #param \App\Product $product
* #return \Illuminate\Http\Response
*/
public function show(Product $product)
{
return view('products.show',compact('product'));
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Product $product
* #return \Illuminate\Http\Response
*/
public function edit(Product $product)
{
return view('products.edit',compact('product'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Product $product
* #return \Illuminate\Http\Response
*/
// public function update(Request $request, Product $product)
public function update(Request $request, $product_id)
{
$user_id = Auth::user()->id ;
$request->validate([
'name' => 'required',
'detail' => 'required',
'color' => 'required',
]);
$input = $request->all();
if ($image = $request->file('image')) {
$destinationPath = 'image/';
$profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
$image->move($destinationPath, $profileImage);
$input['image'] = "$profileImage";
}else{
unset($input['image']);
}
if ($logo = $request->file('logo')) {
$destinationPath = 'logo/';
$profileLogo = date('YmdHis') . "." . $logo->getClientOriginalExtension();
$logo->move($destinationPath, $profileLogo);
$input['logo'] = "$profileLogo";
}else{
unset($input['logo']);
}
$product_id->update($input);
return redirect()->route('products.index')
->with('success','Product updated successfully');
}
/**
* Remove the specified resource from storage.
*
* #param \App\Product $product
* #return \Illuminate\Http\Response
*/
public function destroy(Product $product)
{
$product->delete();
return redirect()->route('products.index')
->with('success','Product deleted successfully');
}
// function indextwo(){
// //return DB::select("select * from products");
// //DB::table('products')->orderBy('id','desc')->first();
// return Product::orderBy('id', 'DESC')->first();
// }
}
This is ProjectController.php
<?php
namespace App\Http\Controllers;
use App\Exports\UsersExport;
use App\Models\Project;
use App\Imports\ProjectsImport;
use App\Models\Product;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class ProjectController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
// $projects = Project::where('user_id',auth()->user()->id)->latest()->paginate(20);
// $projects = Project::where('user_id',auth()->user()->id)->where('product_id')->latest()->paginate(20);
// $projects = Project::where('user_id',auth()->user()->id)->latest('product_id',8) ->paginate(20);
// $projects = Project::whereIn('product_id',Product::where('user_id',Auth::id())->pluck('id')->toArray())->latest();
// $projects = Project::whereIn('product_id',Product::where('user_id',Auth::id())->pluck('id')->toArray())->latest()->paginate(20);
$projects = Project::whereIn('product_id',Product::where('user_id',Auth::id())->pluck('id')->toArray())->latest()->paginate(20);
return view('projects.index', compact('projects'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('projects.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'chapter_name' => 'required',
'sub_section_name' => 'required',
'title_1' => 'required',
'description_1' => 'required',
'image_1' => 'required',
'image_2' => 'required',
'image_3' => 'required',
'title_2' => 'required',
'description_2' => 'required',
'title_3' => 'required',
'description_3' => 'required',
'video_1' => 'required',
'video_2' => 'required',
'video_3' => 'required',
]);
// $input = $request->all();
// $input['user_id'] = auth()->user()->id;
// $input['product_id'] = $id;
$input = Project::whereIn('product_id',Product::where('user_id',Auth::id())->pluck('id'));
Project::create($input);
return redirect()->route('project.index')
->with('success','Product created successfully.');
}
/**
* Display the specified resource.
*
* #param \App\Models\Project $project
* #return \Illuminate\Http\Response
*/
public function show(Project $project)
{
// $category = $project->category;
return view('projects.show', compact('project'));
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Models\Project $project
* #return \Illuminate\Http\Response
*/
public function edit(Project $project)
{
return view('projects.edit', compact('project'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Models\Project $project
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Project $project)
{
// $user_id = Auth::user()->id ;
$request->validate([
'chapter_name' => 'required',
'sub_section_name' => 'required',
'title_1' => 'required',
'description_1' => 'required',
'image_1' => 'required',
'image_2' => 'required',
'image_3' => 'required',
'title_2' => 'required',
'description_2' => 'required',
'title_3' => 'required',
'description_3' => 'required',
'video_1' => 'required',
'video_2' => 'required',
'video_3' => 'required',
]);
$input = $request->all();
$project->update($input);
return redirect()->route('project.index')
->with('success','Product updated successfully');
}
/**
* Remove the specified resource from storage.
*
* #param \App\Models\Project $project
* #return \Illuminate\Http\Response
*/
public function destroy(Project $project)
{
$project->delete();
return redirect()->route('projects.index')
->with('success', 'Project deleted successfully');
}
public function importProject()
{
Excel::import(new ProjectsImport, request()->file('file'));
return back()->with('success','Project created successfully.');
}
public function export()
{
return Excel::download(new UsersExport, 'projects.xlsx');
}
}
This is user Model user.php
class User extends Authenticatable
{
use HasApiTokens;
use HasFactory;
use HasProfilePhoto;
use Notifiable;
use TwoFactorAuthenticatable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
public function Products(){
return $this->hasMany('App\Models\Product');
}
public function Project(){
return $this->hasMany('App\Models\Project');
}
// public function products(){
// return $this->hasMany(Product::class);
// }
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
'two_factor_recovery_codes',
'two_factor_secret',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* The accessors to append to the model's array form.
*
* #var array
*/
protected $appends = [
'profile_photo_url',
];
}
This is product model product.php
class Product extends Model
{
use HasFactory;
protected $fillable = [
'name', 'detail', 'image','color','logo','user_id'
];
public function User(){
return $this->belongsTo(User::class);
}
public function Project(){
return $this->hasMany('App\Models\Project');
}
}
This is project model project.php
class Project extends Model
{
use HasFactory;
protected $fillable = [
'chapter_name',
'sub_section_name',
'title_1',
'description_1',
'image_1',
'image_2',
'image_3',
'title_2',
'description_2',
'title_3',
'description_3',
'video_1',
'video_2',
'video_3',
'user_id',
'product_id'
];
public function User(){
return $this->belongsTo(User::class);
}
public function Product(){
return $this->belongsTo(Product::class);
}
}
Solved by Project::where('product_id',Product::where('user_id',Auth::id())->pluck('id')->last())->delete();
In ProjectImport

Prestashop : Can't make my module work : Get order details when order status is changed to “shipped”

I am developing a module, it gets order details when order status is changed to "shipped" by admin, to post them to a third-party application with API.
I am using Prestashop V 1.7.7.0.
The hook i'm using is hookActionOrderStatusPostUpdate
The module is installed successfully in the Backoffice and there's no syntax errors, But it doesn't do anything.
Can't figure out what's wrong in my code.
Need help please. Thanks
<?php
/**
* 2007-2021 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license#prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* #author PrestaShop SA <contact#prestashop.com>
* #copyright 2007-2021 PrestaShop SA
* #license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
if (!defined('_PS_VERSION_')) {
exit;
}
class Cargo extends Module
{
protected $config_form = false;
public function __construct()
{
$this->name = 'cargo';
$this->tab = 'administration';
$this->version = '1.0.0';
$this->author = 'tekwave';
$this->need_instance = 1;
/**
* Set $this->bootstrap to true if your module is compliant with bootstrap (PrestaShop 1.6)
*/
$this->bootstrap = true;
parent::__construct();
$this->displayName = $this->l('cargo');
$this->description = $this->l('Ce module permet la synchronisation entre Prestashop et Cargo');
$this->confirmUninstall = $this->l('');
$this->ps_versions_compliancy = array('min' => '1.6', 'max' => _PS_VERSION_);
}
/**
* Don't forget to create update methods if needed:
* http://doc.prestashop.com/display/PS16/Enabling+the+Auto-Update
*/
public function install()
{
Configuration::updateValue('CARGO_LIVE_MODE', false);
return parent::install() &&
$this->registerHook('header') &&
$this->registerHook('backOfficeHeader') &&
$this->registerHook('actionOrderStatusPostUpdate');
}
public function uninstall()
{
Configuration::deleteByName('CARGO_LIVE_MODE');
return parent::uninstall();
}
/**
* Load the configuration form
*/
public function getContent()
{
/**
* If values have been submitted in the form, process.
*/
if (((bool)Tools::isSubmit('submitCargoModule')) == true) {
$this->postProcess();
}
$this->context->smarty->assign('module_dir', $this->_path);
$output = $this->context->smarty->fetch($this->local_path.'views/templates/admin/configure.tpl');
return $output.$this->renderForm();
}
/**
* Create the form that will be displayed in the configuration of your module.
*/
protected function renderForm()
{
$helper = new HelperForm();
$helper->show_toolbar = false;
$helper->table = $this->table;
$helper->module = $this;
$helper->default_form_language = $this->context->language->id;
$helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG', 0);
$helper->identifier = $this->identifier;
$helper->submit_action = 'submitCargoModule';
$helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false)
.'&configure='.$this->name.'&tab_module='.$this->tab.'&module_name='.$this->name;
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->tpl_vars = array(
'fields_value' => $this->getConfigFormValues(), /* Add values for your inputs */
'languages' => $this->context->controller->getLanguages(),
'id_language' => $this->context->language->id,
);
return $helper->generateForm(array($this->getConfigForm()));
}
/**
* Create the structure of your form.
*/
protected function getConfigForm()
{
return array(
'form' => array(
'legend' => array(
'title' => $this->l('Settings'),
'icon' => 'icon-cogs',
),
'input' => array(
array(
'type' => 'switch',
'label' => $this->l('Live mode'),
'name' => 'CARGO_LIVE_MODE',
'is_bool' => true,
'desc' => $this->l('Use this module in live mode'),
'values' => array(
array(
'id' => 'active_on',
'value' => true,
'label' => $this->l('Enabled')
),
array(
'id' => 'active_off',
'value' => false,
'label' => $this->l('Disabled')
)
),
),
array(
'col' => 3,
'type' => 'text',
'prefix' => '<i class="icon icon-envelope"></i>',
'desc' => $this->l('Enter a valid email address'),
'name' => 'CARGO_ACCOUNT_EMAIL',
'label' => $this->l('Email'),
),
array(
'type' => 'password',
'name' => 'CARGO_ACCOUNT_PASSWORD',
'label' => $this->l('Password'),
),
),
'submit' => array(
'title' => $this->l('Save'),
),
),
);
}
/**
* Set values for the inputs.
*/
protected function getConfigFormValues()
{
return array(
'CARGO_LIVE_MODE' => Configuration::get('CARGO_LIVE_MODE', true),
'CARGO_ACCOUNT_EMAIL' => Configuration::get('CARGO_ACCOUNT_EMAIL', 'contact#prestashop.com'),
'CARGO_ACCOUNT_PASSWORD' => Configuration::get('CARGO_ACCOUNT_PASSWORD', null),
);
}
/**
* Save form data.
*/
protected function postProcess()
{
$form_values = $this->getConfigFormValues();
foreach (array_keys($form_values) as $key) {
Configuration::updateValue($key, Tools::getValue($key));
}
}
/**
* Add the CSS & JavaScript files you want to be loaded in the BO.
*/
public function hookBackOfficeHeader()
{
if (Tools::getValue('module_name') == $this->name) {
$this->context->controller->addJS($this->_path.'views/js/back.js');
$this->context->controller->addCSS($this->_path.'views/css/back.css');
}
}
/**
* Add the CSS & JavaScript files you want to be added on the FO.
*/
public function hookHeader()
{
$this->context->controller->addJS($this->_path.'/views/js/front.js');
$this->context->controller->addCSS($this->_path.'/views/css/front.css');
}
This is my code under hookActionOrderStatusPostUpdate function :
public function hookActionOrderStatusPostUpdate($params)
{
if ($params['newOrderStatus']->id == 6) {
$order = new Order((int)$params['id_order']);
$address = new Address((int)$order->id_address_delivery);
$country = new Country((int)($address->id_country));
$state = new State((int)($address->id_state));
$message = new Message((int)($order->id_message));
$Products = $order->getProducts();
$tel_cl = $address->phone;
$nom_prenom_cl = $address->lastname . ' ' . $address->firstname;
$ville_cl = $country->name;
$delegation_cl = $state->name;
$adresse_cl = $address->address1 . ' ' . $address->address2;
$tel_2_cl = $address->phone_mobile;
$libelle = '';
$nb_piece = 0;
foreach ($Products as $product) {
$libelle .= $product['product_name'] . '<br/>';
$nb_piece += $product['product_quantity'];
}
$cod = $order->total_paid;
$remarque = $message->message;
$Url_str = 'http://admin.cargotunisie.com/cargo_api/set_colis_cargo_get.php?id=1&tel_cl='.$tel_cl.'&nom_prenom_cl='.$nom_prenom_cl.'&ville_cl='.$ville_cl.'&delegation_cl='.$delegation_cl.'&adresse_cl='.$adresse_cl.'&tel_2_cl='.$tel_2_cl.'&libelle='.$libelle.'&cod='.$cod.'&nb_piece='.$nb_piece.'&remarque='.$remarque;
$json = Tools::file_get_contents($Url_str);
$result = json_decode($json);
}
}
}
It could be due to several things.
First: make sure the hook is hooked.
Go to Design > Positions > Then add new hook
Choose your module's name and check if you can select the hook actionOrderStatusPostUpdate. If you can, then it means it was unhooked.
This happens more than we would like, and sometimes you can get crazy until you found it
If that doesn't work you can try this (only if is not on a production site). If it is, just wrap it by using an if that checks if it's from your IP.
Add Tools::dieObject($params); at the beginning of the function.
Then change the an order and check the results. You should see a user friendly list of the values stored in $params.
Make it sure the $params['newOrderStatus'] exists and $params['newOrderStatus']->id is an object.
Also, it should be pretty obvious, but make sure the order ID which are you doing the tests is 6.
With that you should be able to have a general clue of what may be happening.

Authentication using username instead of email laravel 5.2

Below is my code for AuthController
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
//use App\Http\Requests\Request;
use Request;
use View;
use Hash;
use DB;
use Auth;
class AuthController extends Controller
{
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
/**
* Where to redirect users after login / registration.
*
* #var string
*/
protected $redirectTo = '/home';
protected $redirectAfterLogout = '/login';
protected $username = 'user_name';
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
public function showLogin()
{
if (Auth::check())
{
return redirect('/home');
}
else
{
return View::make('index');
}
}
public function doLogin()
{
//echo 'test';
$input = Request::all();
$pass = Hash::make($input['password']);
//print_r($input);exit;
//echo $input['username'];exit;
/*DB::table('admin_user')->insert(
['user_name' => $input['username'], 'password' => $pass]
);*/
if (Auth::attempt(['user_name' => $input['username'], 'password' => $input['password']])) {
return redirect('/home');
//return View::make('home');
}
else
{
return redirect('/');
}
}
public function doLogout()
{
Auth::logout();
return redirect('/');
}
}
Below is my Route Code
Route::get('/',array('uses'=>'Auth\AuthController#showLogin') );
Route::post('/login',array('uses'=>'Auth\AuthController#doLogin'));
//Route::get('/login',array('uses'=>'Login#showLogin') );
Route::group(['middleware' => ['web', 'auth.basic']], function(){
Route::get('/home',['uses'=>'Home#getHome']);
Route::get('/logout',array('uses'=>'Auth\AuthController#doLogout') );
});
i am using user name instead of email id for Auth but below error is shown
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'email' in
'where clause' (SQL: select * from admin_user where email = admin
limit 1)
below is my kernal.php code
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* #var array
*/
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
];
/**
* The application's route middleware groups.
*
* #var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
],
'api' => [
'throttle:60,1',
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* #var array
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];
}
please help me how can i do login with username .
Thanks in advance.
Update:
Add the auth middleware to specific route
Route::group(['middleware' => ['web']], function(){
Route::get('/',array('uses'=>'Auth\AuthController#showLogin') );
Route::post('/login',array('uses'=>'Auth\AuthController#doLogin'));
Route::get('/home',['uses'=>'Home#getHome'])->middleware('auth');//update
Route::get('/logout',array('uses'=>'Auth\AuthController#doLogout') );
});
To redirect to intended page after login replace your doLogin() function with following:
public function doLogin()
{
$input = Request::all();
$pass = Hash::make($input['password']);
if (Auth::attempt(['user_name' => $input['username'], 'password' => $input['password']])) {
return redirect()->intended('/home');//This line is changed
}
else
{
return redirect('/');
}
}
Explaination:
intended() method redirects the user to the previous page, from where the user is redirected to login page. It expects a default route as a parameter, where user will be sent if he has came here directly.
Update 2:
add doLogout in your AuthController's constructor:
public function __construct()
{
$this->middleware($this->guestMiddleware(), ['except' => 'doLogout']);
}
You can simply override $username in AuthController by writing protected $username = 'username'.

Creating an issue in JIRA using REST API - PHP YII2

I'm trying to create an issue in JIRA from my PHP YII2 framework.
What I'm trying to do is - Whenever I create a new version in my system I want that an issue JIRA will be created automatically for this version.
I've found examples in CURL but so far it's not working.
I don't even get any error message. It creates a new version in my system, but nothing happens in JIRA, looks like it's not even trying to connect to JIRA.
This is my VersionController.php -
<?php
namespace app\controllers;
require_once("Curl.php");
use Yii;
use app\models\Version;
use app\models\VersionSearch;
use app\models\Binfile;
use app\models\VersionStatus;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\swiftmailer\Mailer;
use yii\web\UnauthorizedHttpException;
use linslin\yii2\curl;
use understeam\yii2\httpclient;
use understeam\yii2\jira;
/**
* VersionController implements the CRUD actions for Version model.
*/
class VersionController extends Controller
{
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
'access' => [
'class' => \yii\filters\AccessControl::className(),
'only' => ['index','create','update','view'],
'rules' => [
// allow authenticated users
[
'allow' => true,
'roles' => ['#'],
],
// everything else is denied
],
],
];
}
/**
* Lists all Version models.
* #return mixed
*/
public function actionIndex()
{
if (\Yii::$app->user->can('deleteVersion')) {
$template = '{view} {update} {delete} ';
}
else if((\Yii::$app->user->can('changeStatus')) || (\Yii::$app->user->can('uploadVersion'))){
$template = '{view} {update}';
}
else{$template = '{view}';
}
$searchModel = new VersionSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'template' => $template,
]);
}
/**
* Displays a single Version model.
* #param integer $id
* #return mixed
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new Version model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate()
{
if(!\Yii::$app->user->can('createVersion')){
throw new UnauthorizedHttpException("Access denied: You don't have permission to create a version");
}else{
$model = new Version();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
//$this->actionSend();
$this->actionPostExample();
// $this->actionGetExample();
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
}
/**
* Updates an existing Version model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id
* #return mixed
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
/**
* Deletes an existing Version model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* #param integer $id
* #return mixed
*/
public function actionDelete($id)
{
if(!\Yii::$app->user->can('isAdmin')){
throw new UnauthorizedHttpException("Access denied: Only Admin can perform this action!!!");
}else{
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
}
/**
* Finds the Version model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return Version the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Version::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
public function actionSend()
{
Yii::$app->mailer->compose()
->setFrom('jenya#ttttt.com')
->setTo('jenya#tttt.com')
->setSubject('Message test')
->setTextBody('Plain text content')
->setHtmlBody('<b>test</b>')
->send();
}
public function actionPostExample()
{
define('JIRA_URL', 'http://jiratest.../');
define('USERNAME', 'jenya');
define('PASSWORD', 'password');
function post_to($resource, $data)
{
$jdata = json_encode($data);
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_POST => 1,
CURLOPT_URL => JIRA_URL . '/rest/api/latest/' . $resource,
CURLOPT_USERPWD => USERNAME . ':' . PASSWORD,
CURLOPT_POSTFIELDS => $jdata,
CURLOPT_HTTPHEADER => array('Content-type: application/json'),
CURLOPT_RETURNTRANSFER => true
));
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result);
}
$new_issue = array(
'fields' => array(
'project' => array('key' => 'key'),
'issuetype' => array('name' => 'Version Integration Task'),
'summary' => 'Test via REST',
'components' => 'General',
'customfield_10110' => 'name of value',
'fixVersions' => 'name of version',
'Description' => 'Description of issue goes here.',
//'labels' => array('a','b')
)
);
function create_issue($issue)
{
return post_to('issue', $issue);
}
$result = create_issue($new_issue);
if (property_exists($this, 'errors'))
{
echo "Error(s) creating issue:\n";
var_dump($result);
}
else
{
echo "New issue created at " . JIRA_URL ."/browse/{$result}\n";
}
}
}
Curl.php-
<?php
/**
* Yii2 cURL wrapper
* With RESTful support.
*
* #category Web-yii2
* #package yii2-curl
* #author Nils Gajsek <info#linslin.org>
* #copyright 2013-2015 Nils Gajsek<info#linslin.org>
* #license http://opensource.org/licenses/MIT MIT Public
* #version 1.0.7
* #link http://www.linslin.org
*
*/
namespace linslin\yii2\curl;
use Yii;
use yii\base\Exception;
use yii\helpers\Json;
use yii\web\HttpException;
/**
* cURL class
*/
class Curl
{
// ################################################ class vars // ################################################
/**
* #var string
* Holds response data right after sending a request.
*/
public $response = null;
/**
* #var integer HTTP-Status Code
* This value will hold HTTP-Status Code. False if request was not successful.
*/
public $responseCode = null;
/**
* #var array HTTP-Status Code
* Custom options holder
*/
private $_options = array();
/**
* #var object
* Holds cURL-Handler
*/
private $_curl = null;
/**
* #var array default curl options
* Default curl options
*/
private $_defaultOptions = array(
CURLOPT_USERAGENT => 'Yii2-Curl-Agent',
CURLOPT_TIMEOUT => 30,
CURLOPT_CONNECTTIMEOUT => 30,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => false,
);
// ############################################### class methods // ##############################################
/**
* Start performing GET-HTTP-Request
*
* #param string $url
* #param boolean $raw if response body contains JSON and should be decoded
*
* #return mixed response
*/
public function get($url, $raw = true)
{
return $this->_httpRequest('GET', $url, $raw);
}
/**
* Start performing HEAD-HTTP-Request
*
* #param string $url
*
* #return mixed response
*/
public function head($url)
{
return $this->_httpRequest('HEAD', $url);
}
/**
* Start performing POST-HTTP-Request
*
* #param string $url
* #param boolean $raw if response body contains JSON and should be decoded
*
* #return mixed response
*/
public function post($url, $raw = true)
{
return $this->_httpRequest('POST', $url, $raw);
}
/**
* Start performing PUT-HTTP-Request
*
* #param string $url
* #param boolean $raw if response body contains JSON and should be decoded
*
* #return mixed response
*/
public function put($url, $raw = true)
{
return $this->_httpRequest('PUT', $url, $raw);
}
/**
* Start performing DELETE-HTTP-Request
*
* #param string $url
* #param boolean $raw if response body contains JSON and should be decoded
*
* #return mixed response
*/
public function delete($url, $raw = true)
{
return $this->_httpRequest('DELETE', $url, $raw);
}
/**
* Set curl option
*
* #param string $key
* #param mixed $value
*
* #return $this
*/
public function setOption($key, $value)
{
//set value
if (in_array($key, $this->_defaultOptions) && $key !== CURLOPT_WRITEFUNCTION) {
$this->_defaultOptions[$key] = $value;
} else {
$this->_options[$key] = $value;
}
//return self
return $this;
}
/**
* Unset a single curl option
*
* #param string $key
*
* #return $this
*/
public function unsetOption($key)
{
//reset a single option if its set already
if (isset($this->_options[$key])) {
unset($this->_options[$key]);
}
return $this;
}
/**
* Unset all curl option, excluding default options.
*
* #return $this
*/
public function unsetOptions()
{
//reset all options
if (isset($this->_options)) {
$this->_options = array();
}
return $this;
}
/**
* Total reset of options, responses, etc.
*
* #return $this
*/
public function reset()
{
if ($this->_curl !== null) {
curl_close($this->_curl); //stop curl
}
//reset all options
if (isset($this->_options)) {
$this->_options = array();
}
//reset response & status code
$this->_curl = null;
$this->response = null;
$this->responseCode = null;
return $this;
}
/**
* Return a single option
*
* #param string|integer $key
* #return mixed|boolean
*/
public function getOption($key)
{
//get merged options depends on default and user options
$mergesOptions = $this->getOptions();
//return value or false if key is not set.
return isset($mergesOptions[$key]) ? $mergesOptions[$key] : false;
}
/**
* Return merged curl options and keep keys!
*
* #return array
*/
public function getOptions()
{
return $this->_options + $this->_defaultOptions;
}
/**
* Get curl info according to http://php.net/manual/de/function.curl-getinfo.php
*
* #return mixed
*/
public function getInfo($opt = null)
{
if ($this->_curl !== null && $opt === null) {
return curl_getinfo($this->_curl);
} elseif ($this->_curl !== null && $opt !== null) {
return curl_getinfo($this->_curl, $opt);
} else {
return [];
}
}
/**
* Performs HTTP request
*
* #param string $method
* #param string $url
* #param boolean $raw if response body contains JSON and should be decoded -> helper.
*
* #throws Exception if request failed
*
* #return mixed
*/
private function _httpRequest($method, $url, $raw = false)
{
//set request type and writer function
$this->setOption(CURLOPT_CUSTOMREQUEST, strtoupper($method));
//check if method is head and set no body
if ($method === 'HEAD') {
$this->setOption(CURLOPT_NOBODY, true);
$this->unsetOption(CURLOPT_WRITEFUNCTION);
}
//setup error reporting and profiling
Yii::trace('Start sending cURL-Request: '.$url.'\n', __METHOD__);
Yii::beginProfile($method.' '.$url.'#'.md5(serialize($this->getOption(CURLOPT_POSTFIELDS))), __METHOD__);
/**
* proceed curl
*/
$this->_curl = curl_init($url);
curl_setopt_array($this->_curl, $this->getOptions());
$body = curl_exec($this->_curl);
//check if curl was successful
if ($body === false) {
switch (curl_errno($this->_curl)) {
case 7:
$this->responseCode = 'timeout';
return false;
break;
default:
throw new Exception('curl request failed: ' . curl_error($this->_curl) , curl_errno($this->_curl));
break;
}
}
//retrieve response code
$this->responseCode = curl_getinfo($this->_curl, CURLINFO_HTTP_CODE);
$this->response = $body;
//end yii debug profile
Yii::endProfile($method.' '.$url .'#'.md5(serialize($this->getOption(CURLOPT_POSTFIELDS))), __METHOD__);
//check responseCode and return data/status
if ($this->getOption(CURLOPT_CUSTOMREQUEST) === 'HEAD') {
return true;
} else {
$this->response = $raw ? $this->response : Json::decode($this->response);
return $this->response;
}
}
}
I would really appreciate your help, I don't know what else to try.
Thanks in advance.
There is a bug in VersionController.php / actionPostExample() / post_to. As written I would expect the HTTP post to JIRA to result in an HTTP 404 response.
This line:
CURLOPT_URL => JIRA_URL . '/rest/api/latest/' . $resource,
Should be:
CURLOPT_URL => JIRA_URL . '/rest/api/2/' . $resource,
../latest/... is used in the JIRA api docs pages but it is not part of the rest API. .../rest/api/2/... is compatible with JIRA 6 and 7.
I did it.
This is the function that works for me:
function post_to($resource, $data)
{
$jdata = json_encode($data);
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_POST => true,
CURLOPT_URL => JIRA_URL . '/rest/api/latest/' . $resource,
CURLOPT_USERPWD => USERNAME . ':' . PASSWORD,
CURLOPT_POSTFIELDS => $jdata,
CURLOPT_HTTPHEADER => array('Content-type: application/json'),
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
//CURLOPT_RETURNTRANSFER => true
));
After that I had to fix several things in JSON which are specific for my project.
For easier debugging you can add this:
error_reporting(E_ALL);
ini_set('display_errors', 1);
To get clear errors.

Can't authenticate with different table

I've changed the auth.php file in order to authenticate my users according to authors table. But I keep getting No account for you when I'm running test route.
auth.php
<?php
return array(
'driver' => 'eloquent',
'model' => 'Author',
'table' => 'authors',
'reminder' => array(
'email' => 'emails.auth.reminder', 'table' => 'password_reminders',
),
);
routes.php
Route::get('test', function() {
$credentials = array('username' => 'giannis',
'password' => Hash::make('giannis'));
if (Auth::attempt($credentials)) {
return "You are a user.";
}
return "No account for you";
});
AuthorsTableSeeder.php
<?php
class AuthorsTableSeeder extends Seeder {
public function run()
{
// Uncomment the below to wipe the table clean before populating
DB::table('authors')->delete();
$authors = array(
[
'username' => 'giannis',
'password' => Hash::make('giannis'),
'name' => 'giannis',
'lastname' => 'christofakis'],
[
'username' => 'antonis',
'password' => Hash::make('antonis'),
'name' => 'antonis',
'lastname' => 'antonopoulos']
);
// Uncomment the below to run the seeder
DB::table('authors')->insert($authors);
}
}
Addendum
I saw in another post that you have to implement the UserInterface RemindableInterface interfaces. But the result was the same.
Author.php
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class Author extends Eloquent implements UserInterface, RemindableInterface {
protected $guarded = array();
public static $rules = array();
public function posts() {
return $this->hasMany('Post');
}
/**
* Get the unique identifier for the user.
*
* #return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* #return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the e-mail address where password reminders are sent.
*
* #return string
*/
public function getReminderEmail()
{
return "giannis#hotmail.com";
}
}
You don't need to Hash your password when you are using Auth::attempt(); so remove Hash::make from routes
Route::get('test', function() {
$credentials = array('username' => 'giannis',
'password' => 'giannis');
if (Auth::attempt($credentials)) {
return "You are a user.";
}
return "No account for you";
});
and it will work like a charm!