I want to render a YooKassa widget in flutter app, so I've written this code to implement it
https://yookassa.ru/checkout-widget/v1/checkout-widget.js
#JS()
library checkout-widget.js;
import 'package:js/js.dart';
#JS('YooMoneyCheckoutWidget')
class YooMoneyCheckoutWidget {
external YooMoneyCheckoutWidget(YooMoneyCheckoutWidgetParams params);
external render(String viewID);
}
#JS()
#anonymous
class YooMoneyCheckoutWidgetParams {
external factory YooMoneyCheckoutWidgetParams({
String confirmation_token,
String return_url,
Map<String, dynamic> customization,
Function error_callback
});
}
class YooKassa {
YooMoneyCheckoutWidget _checkoutWidget;
YooKassa({String confirmation_token,String return_url}):_checkoutWidget = YooMoneyCheckoutWidget(YooMoneyCheckoutWidgetParams(confirmation_token: confirmation_token, return_url: return_url, customization: {'colors': {'controlPrimary':'#00BF96'}},error_callback: null));
void render(String viewID) => _checkoutWidget.render(viewID);
}
then trying to call the constructor for a JS code
final widget = YooKassa(confirmation_token: 'ct-2834a83d-000f-5000-9000-1316627a4610',return_url: 'https://app.moneyhat.ru/');
and then render it in DivElement in a HTMLElement
final wrapper = html.DivElement()
..style.width = '100%'
..style.height = '100%'
..id = 'pay-form';
ui.platformViewRegistry.registerViewFactory(
viewID,
(int viewId) => wrapper,
);
widget.render('pay-form');
return Scaffold(
body: SizedBox(
height: 500,
child: HtmlElementView(
viewType: viewID,
),
));
}
What's wrong here? Flutter raises an error - YooMoneyCheckoutWidget is not a constuctor
I have a class in Dart like this
import 'package:js/js.dart';
import 'dart:html';
import 'dart:js' as js;
class VistorianTab {
void showMatrix() {
var dataset = new networkcube.DataSet({
name: dataSetName,
nodeTable: [...],
linkTable: [...],
nodeSchema: {...},
linkSchema: {...}
});
}
I get the error because networkcube isn't defined, I imported the library in the index.html.
The library is this : https://github.com/networkcube/vistorian/blob/master/core/networkcube.js
I'm new to Dart, I'm sorry if I repeteaded a question.
Thank you for your time.
I want to display static block in html login popup during checkout, but there is a problem.
This is the html template which is called from js, this js is called from phtml, and this phtml template called from xml
layout.
( xml -> phtml -> js -> html)
So the question is how to send custom content block from the phtml or xml throught js to html template
vendor/magento/module-catalog/view/frontend/layout/default.xml
This file is calling pthml template with
<block class="Magento\Customer\Block\Account\AuthenticationPopup" name="authentication-popup" as="authentication-popup" template="Magento_Customer::account/authentication-popup.phtml">
vendor/magento/module-customer/view/frontend/templates/account/authentication-popup.phtml
This file is calling js layout with code:
<script type="text/x-magento-init">
{
"#authenticationPopup": {
"Magento_Ui/js/core/app": <?= /* #noEscape */ $block->getJsLayout() ?>
}
}
</script>
vendor/magento/module-customer/view/frontend/web/js/view/authentication-popup.js
this file is called the last html template where should be a static block from admin panel, with code:
define([
'jquery',
'ko',
// ......... //
], function ($, ko, /* ... ... ... .... ... */) {
'use strict';
return Component.extend({
registerUrl: window.authenticationPopup.customerRegisterUrl,
forgotPasswordUrl: window.authenticationPopup.customerForgotPasswordUrl,
autocomplete: window.authenticationPopup.autocomplete,
modalWindow: null,
isLoading: ko.observable(false),
defaults: {
template: 'Magento_Customer/authentication-popup'
},
});
});
this is how i get this block in php
<?php echo $this->getLayout()->createBlock('Magento\Cms\Block\Block')->setBlockId('reset_password_notice')->toHtml(); ?>
I tried to paste it to phtml, it doesn't work !!!
The problem is solved by myself.
So for the first step i started looking for data provider which helps to send data from pthml throught js to html in vendor/module-customer/
There i found file vendor/module-customer/Model/Checkout/ConfigProvider.php. That was exectly what i need.
Following this link i create:
1) app/code/Theme/Customer/etc/frontend/di.xml with code:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Magento\Customer\Controller\Account\CreatePost"
type="Theme_Name\Customer\Controller\Account\CreatePost" />
<type name="Magento\Checkout\Model\CompositeConfigProvider">
<arguments>
<argument name="configProviders" xsi:type="array">
<item name="cms_block_config_provider" xsi:type="object">Theme_Name\Customer\Model\Checkout\ConfigProvider</item>
</argument>
</arguments>
</type>
</config>
2) The next step was to create a class which is called in item tag: Theme_Name/Customer/Model/Checkout/ConfigProvider.php
with code that extends
vendor/module-customer/Model/Checkout/ConfigProvider.php
Note! They both implement the same ConfigProviderInterface. So in new ConifgProvider.php we use the same interface to extend data-provider correctly
<?php
namespace Theme_Name\Customer\Model\Checkout;
use Magento\Checkout\Model\ConfigProviderInterface;
use Magento\Framework\View\LayoutInterface;
class ConfigProvider implements ConfigProviderInterface
{
/** #var LayoutInterface */
protected $_layout;
public function __construct(LayoutInterface $layout)
{
$this->_layout = $layout;
}
public function getConfig()
{
$cmsBlockId = 'block_ID'; // id of cms block to use
return [
'cms_block_message' => $this->_layout->createBlock('Magento\Cms\Block\Block')->setBlockId($cmsBlockId)->toHtml()
];
}
}
Good. Provider is configured.
3)The last one was need to override frontend html KO template:
app/design/frontend/theme_name/Magento_Customer/web/template/authentication-popup.html
Write the next:
<div data-bind="html: window.checkoutConfig.cms_block_message"></div>
You need to put this code into your phtml file.
<?php echo $this->getLayout()->createBlock('Magento\Cms\Block\Block')->setBlockId('reset_password_notice')->toHtml(); ?>
And now it show what you write into this block.
How correctly to make a wrapper? I need to wrap this method:
js:
var columnDefs = [
{
floatingFilterComponentParams: {
suppressFilterButton: true, // <--- это
},
},
];
I try this option:
#JS('ColumnDef.floatingFilterComponentParams')
//class floatingFilterComponentParams extends ColumnDef {
class floatingFilterComponentParams {
external set suppressFilterButton(bool value);
}
If this is correct, how do I run it in dart code? There is no such method in columnDefs.
You can use the js_util library in js package. The following code should work:
import 'package:js/js.dart';
import 'package:js/js_util.dart' as js_util;
#JS()
external List get columnDef;
set suppressFilterButton(bool value) {
final floatingFilterComponentParams = js_util.getProperty(columnDef[0], 'floatingFilterComponentParams');
js_util.setProperty(floatingFilterComponentParams, suppressFilterButton, value)
}
I want to call CsharpFunction, a C# function in code-behind, from JavaScript. I tried the code below but whether the JavaScript condition is True or False, CsharpFunction was called regardless!
JavaScript code:
if (Javascriptcondition > 0) {
<%CsharpFunction();%>
}
C# code behind:
protected void CsharpFunction()
{
// Notification.show();
}
How do I call a C# function from JavaScript?
You can use a Web Method and Ajax:
<script type="text/javascript"> //Default.aspx
function DeleteKartItems() {
$.ajax({
type: "POST",
url: 'Default.aspx/DeleteItem',
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#divResult").html("success");
},
error: function (e) {
$("#divResult").html("Something Wrong.");
}
});
}
</script>
[WebMethod] //Default.aspx.cs
public static void DeleteItem()
{
//Your Logic
}
.CS File
namespace Csharp
{
public void CsharpFunction()
{
//Code;
}
}
JS code:
function JSFunction() {
<%#ProjectName.Csharp.CsharpFunction()%> ;
}
Note :in JS Function when call your CS page function.... first name of project then name of name space of CS page then function name
A modern approach is to use ASP.NET Web API 2 (server-side) with jQuery Ajax (client-side).
Like page methods and ASMX web methods, Web API allows you to write C# code in ASP.NET which can be called from a browser or from anywhere, really!
Here is an example Web API controller, which exposes API methods allowing clients to retrieve details about 1 or all products (in the real world, products would likely be loaded from a database):
public class ProductsController : ApiController
{
Product[] products = new Product[]
{
new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 },
new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },
new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }
};
[Route("api/products")]
[HttpGet]
public IEnumerable<Product> GetAllProducts()
{
return products;
}
[Route("api/product/{id}")]
[HttpGet]
public IHttpActionResult GetProduct(int id)
{
var product = products.FirstOrDefault((p) => p.Id == id);
if (product == null)
{
return NotFound();
}
return Ok(product);
}
}
The controller uses this example model class:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public decimal Price { get; set; }
}
Example jQuery Ajax call to get and iterate over a list of products:
$(document).ready(function () {
// Send an AJAX request
$.getJSON("/api/products")
.done(function (data) {
// On success, 'data' contains a list of products.
$.each(data, function (key, item) {
// Add a list item for the product.
$('<li>', { text: formatItem(item) }).appendTo($('#products'));
});
});
});
Not only does this allow you to easily create a modern Web API, you can if you need to get really professional and document it too, using ASP.NET Web API Help Pages and/or Swashbuckle.
Web API can be retro-fitted (added) to an existing ASP.NET Web Forms project. In that case you will need to add routing instructions into the Application_Start method in the file Global.asax:
RouteTable.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = System.Web.Http.RouteParameter.Optional }
);
Documentation
Tutorial: Getting Started with ASP.NET Web API 2 (C#)
Tutorial for those with legacy sites: Using Web API with ASP.NET Web Forms
MSDN: ASP.NET Web API 2
Use Blazor
http://learn-blazor.com/architecture/interop/
Here's the C#:
namespace BlazorDemo.Client
{
public static class MyCSharpFunctions
{
public static void CsharpFunction()
{
// Notification.show();
}
}
}
Then the Javascript:
const CsharpFunction = Blazor.platform.findMethod(
"BlazorDemo.Client",
"BlazorDemo.Client",
"MyCSharpFunctions",
"CsharpFunction"
);
if (Javascriptcondition > 0) {
Blazor.platform.callMethod(CsharpFunction, null)
}
Server-side functions are on the server-side, client-side functions reside on the client.
What you can do is you have to set hidden form variable and submit the form, then on page use Page_Load handler you can access value of variable and call the server method.
More info can be found here
and here
If you're meaning to make a server call from the client, you should use Ajax - look at something like Jquery and use $.Ajax() or $.getJson() to call the server function, depending on what kind of return you're after or action you want to execute.
You can't. Javascript runs client side, C# runs server side.
In fact, your server will run all the C# code, generating Javascript. The Javascript then, is run in the browser. As said in the comments, the compiler doesn't know Javascript.
To call the functionality on your server, you'll have to use techniques such as AJAX, as said in the other answers.