I have a xe:jsonRpcService that I'd like to pass to a csjs class. How is this possible?
The service:
<xe:jsonRpcService id="jsonRpcService1" serviceName="rpcServices">
<xe:this.methods>
<xe:remoteMethod name="loadEntity"
script="PersonBean.loadEntity(id);">
<xe:this.arguments>
<xe:remoteMethodArg name="id" type="string"></xe:remoteMethodArg>
</xe:this.arguments>
</xe:remoteMethod>
</xe:this.methods>
</xe:jsonRpcService>
Call to my class in a output script:
formHelper = new FormHeler( rpcServices ) ;
The csjs class:
function Formhelper( service ) {
//...
this.loadEntity = function( id ) {
//...
resultObj = service.loadEntity( id ) ;
//...
}
}
Using rpcServices.loadEntity in the class works. But I'd like to pass it as parameter, so I can use the class with different services.
rpcServices as parameter for the class constructor doesn't work. Is there another way to pass a reference to a service and make it available in the class?
rpcServices is a server-side collection of REST service endpoints (the this.methods). You can't pass that collection to CSJS, you can only pass the result of one of the endpoints.
Think of it as being like trying to pass a SSJS Script Library into a CSJS function.
Thank's Paul. Got it to work by passing the service name to the class. Then I use eval to call the rpc method:
var serviceName = "rpcServices" ;
formHelper = new FormHelper( serviceName ) ;
function FormHelper( serviceName ) {
this.serviceName = serviceName ;
//...
this.loadEntity = function( id ) {
var rpcResultObj = eval( this.serviceName + ".loadEntity( \"" + id + "\" )" ) ;
}
//...
}
Now I can use my FormHelper methods with different services.
Related
I'm making an export data to excel based on employee_id filter, month and year of absence:
.
when the filter is submitted the data appears in the table below:
I have managed to get the data, but when the Download Excel button is clicked, the contents are just empty Excel, like this:
the data does not enter the excel.
My Controller:
public function rekapabsensiExcel(Request $request)
{
$idkaryawan = $request->id_karyawan;
$bulan = $request->query('bulan',Carbon::now()->format('m'));
$tahun = $request->query('tahun',Carbon::now()->format('Y'));
// simpan session
$idkaryawan = $request->session()->get('idkaryawan');
$bulan = $request->session()->get('bulan');
$tahun = $request->session()->get('tahun',);
// dd($idkaryawan,$bulan,$tahun );
if(isset($idkaryawan) && isset($bulan) && isset($tahun))
{
$data = Absensi::where('id_karyawan', $idkaryawan)
->whereMonth('tanggal', $bulan)
->whereYear('tanggal',$tahun)
->get();
// dd($data);
}else{
$data = Absensi::all();
}
return Excel::download(new RekapabsensiExport(['data'=>$data, 'idkaryawan'=>$idkaryawan]),'rekap_absensi_bulanan.xlsx');
}
My RekapAbsensiExport.php:
<?php
namespace App\Exports;
use App\Models\Absensi;
use Maatwebsite\Excel\Concerns\FromCollection;
class RekapabsensiExport implements FromCollection
{
protected $id_karyawan;
// function __construct($id_karyawan) {
// $this->id_karyawan = $id_karyawan;
// }
public function headings(): array {
return [
"No. ID","ID Karyawan","NIK","Tanggal","Jam Kerja","Jam Masuk","Jam Pulang",
"Scan Masuk","Scan Pulang","Normal","Riil","Terlambat","Plg Cepat","Absent",
"Lembur","Jml Jam Kerja","pengecualian","Harus C/I","Harus C/O","Departemen",
"Hari Normal","Akhir Pekan","Hari Libur","Jml Kehadiran","Lembur Hari Normal",
"Lembur Akhir Pekan","Lembur Hari Libur"
];
}
/**
* #return \Illuminate\Support\Collection
*/
public function collection()
{
return Absensi::where('id_karyawan',$this->id_karyawan)->get();
}
}
What part did I go wrong? Please help
Currently, you get no response to this statement because $this->id_karyawan is null as you have not properly passed the value through.
return Absensi::where('id_karyawan', $this->id_karyawan)->get();
Above, you are passing an array of values to the Export class. But your commented-out constructor function is only configured to accept a single parameter. If we stick to single parameters, you could do something like this.
return Excel::download(new RekapabsensiExport($data, $idkaryawan),'rekap_absensi_bulanan.xlsx');
Then your export constructor would look like this.
protected $data;
protected $id_karyawan;
function __construct($data, $id_karyawan) {
$this->data = $data;
$this->id_karyawan = $id_karyawan;
}
I'm trying to load custom attribute value in my controller but it always returns null. Here is my code:
public function execute()
{
$product_id = $this->getRequest()->getParam('id');
if(isset($product_id)){
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$_product = $objectManager->get('Magento\Catalog\Model\Product')->load($product_id);
$colorGriding = $_product->getCustomAttribute('color_griding'); // returns null
echo json_encode(array('message'=>'found', 'colors' => $colorGriding->getValue()));
}
else
echo json_encode(array('message'=>'empty'));
What is wrong here?
Can someone help me to get userID in event listener from event.controller?
# EventListener
kernel.listener.corporation.manage:
class: Site\CorporationBundle\Event\SiteCorporationManageListener
arguments: ["#doctrine.orm.entity_manager", "#user.own.item", "#security.context"]
tags:
- { name: kernel.event_listener, event: kernel.controller, method: onKernelRequest }
And listener class
use Doctrine\ORM\EntityManager;
use Site\MainBundle\Service\UserOwnItem;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\Security\Core\SecurityContext;
class SiteCorporationManageListener
{
private $oEntityManager = null;
private $oUserOwnItem = null;
private $oSecurityContext = null;
public function __construct(EntityManager $oEntityManager, UserOwnItem $oUserOwnItem, SecurityContext $oSecurityContext)
{
$this->oEntityManager = $oEntityManager;
$this->oUserOwnItem = $oUserOwnItem;
$this->oSecurityContext = $oSecurityContext;
}
public function onKernelRequest(FilterControllerEvent $event)
{
if (HttpKernelInterface::MASTER_REQUEST === $event->getRequestType()) {
$route = $event->getRequest()->get('_route');
$corporationID = $event->getRequest()->get('corporationID', null);
$userID = $this->oSecurityContext->getToken()->getUser()->getID();
//$userID = 3;
//var_dump($userID);
if (strstr($route, 'corporation')) {
if (!strstr($route, 'corporation_index')) {
$bUserOwn = $this->oUserOwnItem->setUserID($userID)->setItemType('corporation')->setItemID($corporationID)->userOwn();
//var_dump($bUserOwn);
}
}
}
}
}
I'll clean it later, i try different ways to do it, but even through container and security_context i cannot get userID. It brokes after getToken() method =.
At this example $userID is null... Even after getToken()->getUser() give me null...
FatalErrorException: Error: Call to a member function getUser() on a non-object in /home/dev/public_html/git.eve-ceo/src/Site/CorporationBundle/Event/SiteCorporationManageListener.php line 32
Help please.
Can get user id with this.
Include this.
use FOS\UserBundle\Model\UserInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
Here you get userId
$user = $this->oSecurityContext->getToken()->getUser();
if (!is_object($user) || !$user instanceof UserInterface) {
throw new AccessDeniedException('You are not authorize to access this location.');
}
else{
$userID = $user->getId();
}
you must use checking of token like this:
if ($context->getToken() && $context->getToken()->getUser() !== 'anon.')
$user = $context->getToken()->getUser();
Basically you are not authenticated user.
I think the same, but in symfony if you put "var_dump($user)" before you are logged in, the result is: string 'anon.' (length=5).
Maybe you can use "is_object($user) (for me is better option)
like:
if ($securityContext->getToken() && is_object($securityContext->getToken()->getUser())){
For an update, service security.context is deprecated since Symfony 2.6.
So your new service declaration should looks like
# EventListener
kernel.listener.corporation.manage:
class: Site\CorporationBundle\Event\SiteCorporationManageListener
arguments: ["#doctrine.orm.entity_manager", "#user.own.item", "#security.token_storage"]
tags:
- { name: kernel.event_listener, event: kernel.controller, method: onKernelRequest }
Construct would be like
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
...
public function __construct(EntityManager $oEntityManager, UserOwnItem $oUserOwnItem, TokenStorage $tokenStorage)
{
$this->oEntityManager = $oEntityManager;
$this->oUserOwnItem = $oUserOwnItem;
$this->tokenStorage = $tokenStorage;
}
Then getting the user would become
$user = $this->tokenStorage->getToken()->getUser();
source : http://symfony.com/blog/new-in-symfony-2-6-security-component-improvements
There is a similar issue, where I posted an answer solving it:
https://stackoverflow.com/a/49794146/2564552
In short: Your Listener on kernel.controller is called before the Token is initialized, so you have to play with priorities or (in newer Symfony versions) just use the (not yet documented) kernel.controller_arguments event.
In my scenario I want to mock 1 of the service framework method which takes object parameter and reset it with strongly typed class object.
public void Updatedata(object pvm)
{
var vm = new datamodel()
{
name = "test",
age = 100
};
pvm = vm;
}
It gives compilation error "Invalid callback. Setup on method with parameters (Object) cannot invoke callback with parameters (datamodel)." with below code for mocking.
mockderived.Setup(p => p.Updatedata(It.IsAny<datamodel>()))
.Callback<datamodel>(p =>
{
p.name ="My name is test";
});
The mock works fine if I change my updatedata method to accepts datamodel as parameter instead of object type. To avoid compilation errors I changed code by passing object as parameter:
mockderived.Setup(p => p.Updatedata(It.IsAny<object>()))
.Callback<object>(p =>
{
p = new datamodel() {name = "My name is test"};
});
Code get executed by it did not reulted in change of values of datamodel as expected.
After using reflection to set properties of the object parameter in the callback method, I am able to mock method proerly.
mockderived.Setup(p => p.Updatedata(It.IsAny<object>()))
.Callback<object>(p =>
{
var temp = new datamodel();
var t = temp.GetType();
var nameprop = "no name";
var prop = t.GetProperties();
prop[0].SetValue(p, nameprop, null);
});
Heres some example code. I successfully figured out how to compile this. I grabbed the location and was able to use visual studios object browser to look through the DLL. I cant figure out how to get a class instance and call a function.
public static void test()
{
JScriptCodeProvider js = new JScriptCodeProvider();
System.CodeDom.Compiler.CompilerParameters param = new System.CodeDom.Compiler.CompilerParameters();
var cr = js.CompileAssemblyFromSource(param, new string[] { "package pkg { class b { public function increment(x) { return x+1; } } }" });
foreach (var e in cr.Errors) {
var s = e.ToString();
}
var asm = cr.CompiledAssembly;
var module = cr.CompiledAssembly.GetModules();
//or var module = cr.CompiledAssembly.GetModule("JScript Module");
//...
}
Hmmm realy late on the answer but this is how you would invoke a method from a CodeDom compiled class
You have to use reflection to create an assembly from your compiler results...(your var cr)
Assembly assembly = cr.CompiledAssembly;
Then you have to create an instance of the class you want
object sourceClass = assembly.CreateInstance("YourNamespace.YourClass");
Then you invoke any method inside the class
var result = sourceClass.GetType().InvokeMember("YourMethod", BindingFlags.InvokeMethod, null, sourceClass, new object[] { *Parameters go here* });
And with that what ever the method you invoked had to returned would now be the value of the "result" var....pretty easy.