yii2 dynamic-form wbraganca call javascript function - javascript

I have read some articles about yii2 dynamic-form and javascript function. The solution given by InsaneSkull is perfect. But i have one question.
example :
i'm using dynamic-form from wbraganca and trying to call function onchange event (javascript). My code like this
<?= $form->field($detail, "[{$i}]qty")->widget(\yii\widgets\MaskedInput::className(),
[
'clientOptions' => [
'alias' => 'numeric',
'groupSeparator' => ',',
'digits' => 0,
'autoGroup' => true,
'removeMaskOnSubmit' => true,
'rightAlign' => false,
],
'options' => [
'class' => 'form-control',
'onchange' => 'Info($(this))',
]
]) ?>
First, i try to register Info function like below
<?php
$script = <<< JS
function Info(item){
var index = item.attr("id").replace(/[^0-9.]/g, "");
alert(index);
};
JS;
$this->registerJs($script);
?>
It gave error because Info function not defined yet.
Second, I registered in AppAsset and it worked.
My question : what is the differences? *(I think it was the scope).
How to define the function beside register in AppAsset ?

Where dou you register above script? If in view after use widget, default position at which JS is register is POS_READY public void registerJs ( $js, $position = self::POS_READY, $key = null ) Try to use position POS_BEGIN or POS_HEAD if you want to put the script after use widget. Otherwise You can override widget class and put this script into init method of the widget which is execute before run method rendered widget.

Related

Is there a way to have a wordpress post category that is functional but not visible?

I would like to display categories in posts and in post excepts, however I would alo like to use categories that help organise the display of posts around the site but are not visible.
For example a 'featured' category that may be applied to a range of posts in unconnected categories, but that are the most valuable posts to show in a particular area. I don't want the category 'featured' to show to the user.
you're looking at custom taxonomies. Custom taxonomies can be applied to multiple posts. You can control their behaviour by using arguments.
CTs looks somewhat like that and are declared in your function.php file
<?php
/**
* Add CT to CPT
*/
add_action( 'init', 'custom_taxonomy_langues' );
function custom_taxonomy_langues() {
$taxonomy = '_related_CPT_goes_here';
$singular = '_CT_singular_name';
$plural = '_CT_plural_name';
$labels = array(
'name' => $plural,
'singular_name' => $singular,
);
$args = array(
'labels' => $labels,
'description' => '',
'hierarchical' => 1,
'public' => false,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => false,
'rewrite' => array( 'slug' => strtolower( $plural ), 'hierarchical' => 1 ),
);
register_taxonomy( strtolower( $plural ), strtolower( $taxonomy ), $args );
}; ?>
As you can see you can control pretty every regarding the behaviour, can you query them, do they have an archive page, do you want them to show up in the admin ui, if so where ... etc
A bunch of article already exist, you can take a look at this one https://wordpress.stackexchange.com/questions/92430/can-multiple-custom-post-types-share-a-custom-taxonomy in regards to connecting multiple CPTs to a single CT.
Use a custom taxonomy instead.One can specify that they are not public, but still use them for querying and grouping. https://developer.wordpress.org/reference/functions/register_taxonomy/

Wordpress Gutenberg ACF Blocks How to Add JS When Block is Opened

I'm using ACF Blocks and have the following block.
acf_register_block_type(array(
'name' => 'columns',
'title' => __('Columns'),
'description' => __('For complex multi colomn rows.'),
// 'category' => 'formatting',
'render_template' => get_template_directory() . '/includes/blocks/templates/columns.php',
'enqueue_style' => get_template_directory_uri() . '/includes/blocks/css/columns.css',
'enqueue_script' => get_template_directory_uri() . '/includes/blocks/js/columns.js',
'keywords' => array('rows', 'content', 'column'),
'supports' => array('align' => array('wide', 'full')),
'mode' => 'auto',
));
I need to run some JS when I click on the block in the editor to open it for editing. I don't know if there is a standard way of doing this so I thought I could just use a click event to run my function, but it won't fire. Here is a pic of the block in the DOM.
Block HTML
I added the script following the docs here. (At the bottom there is a "Adding block scripts" example)
Here is my trimmed down JS...
(function($){
var initializeBlock = function ($block) {
$('body').on('click', 'div[data-type="acf/columns"]', function () {
console.log('teeeeeeeest');
});
//... Other JS put here works
}
if (window.acf) {
window.acf.addAction('render_block_preview/type=columns', initializeBlock);
}
})(jQuery);
How come this click function won't fire? Is there another way of doing this?

Shopify script_tag API - how to pass the variable?

I have some javascript code in my ShopifyApp which I'm adding to the ShopifyShop using script_tag API:
$response = $client->request(
'POST',
"https://{$store}/admin/script_tags.json",
[
'headers' => [
'X-Shopify-Access-Token' => $access_token
],
'form_params' => [
'script_tag' => [
"event" => "onload",
"src" => $scriptUrl
]
]
]);
Script:
var _smid = 'someValue';
(function(a,b,c,d,e) {...})
My problem is that I need to pass var _smid there which is different per App instalation (generated server side) - is there any way to do it or maybe some other way to actually pass script as variable from php and not as url to .js file?
Modify your script tag to do a callback to an App Proxy. That way, your App gets the store name, and any other data you need to pass to it.

Google Maps API MissingKeyMapError via Magento Plugin

I've had a look through the forum already, but can't seem to find an answer for my specific problem.
So, I've installed a third party 'store locator' plugin on my Magento store but I keep getting a js error message about MissingKeyMapError. I've already applied for an API key - but my problem is I'm not sure where in the code I should put this key.
API Key
I'm in Googlemap.php in the app folder for this particular plugin and I think it should go in here somewhere but not entirely sure.
This is what's contained in Googlemap.php:
class Clarion_Storelocator_Block_Adminhtml_Storelocator_Edit_Tab_Googlemap extends Mage_Adminhtml_Block_Widget_Form
{
protected function _prepareForm()
{
$model = Mage::registry('storelocator_data');
$form = new Varien_Data_Form();
$this->setForm($form);
$fieldset = $form->addFieldset('form_General_Googlemap', array('legend'=>Mage::helper('clarion_storelocator')->__('Google Map')));
$radiusConfigValue = Mage::getStoreConfig('clarion_storelocator_general_setting/clarion_storelocator_display_setting/default_radius');
$fieldset->addField('radius', 'text', array(
'label' => Mage::helper('clarion_storelocator')->__('Radius'),
'note' => Mage::helper('clarion_storelocator')->__('Radius is in miles. If kept blank then default configured radius will be used (System > Configuration > Store Locator)'),
'name' => 'radius',
'value' => $radiusConfigValue,
));
$fieldset->addField('latitude', 'text', array(
'label' => Mage::helper('clarion_storelocator')->__('Latitude'),
'class' => 'validate-number',
'required' => true,
'name' => 'latitude',
));
$fieldset->addField('longitude', 'text', array(
'label' => Mage::helper('clarion_storelocator')->__('Longitude'),
'class' => 'validate-number',
'required' => true,
'name' => 'longitude',
));
$zoomLevelConfigValue = Mage::getStoreConfig('clarion_storelocator_general_setting/clarion_storelocator_display_setting/zoom_level');
$fieldset->addField('zoom_level', 'text', array(
'label' => Mage::helper('clarion_storelocator')->__('Zoom Level '),
'note' => Mage::helper('clarion_storelocator')->__('If kept blank then default configured zoom level will be used (System > Configuration > Store Locator)'),
'name' => 'zoom_level',
'value' => $zoomLevelConfigValue,
));
$data = $model->getData();
if(!empty($data)) {
$form->setValues($data);
}
return parent::_prepareForm();
}
}**
Any help/suggestions would be much appreciated!
Thanks in advance,
Letitia
I also had same issue with this extension just find the xml file under your theme layout mainly named with clarion_storelocator.xml in this find google api path under script tag in line no #32 replace with src="//maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&key=YOUR_API_KEY" async="" defer="defer" type="text/javascript"> under script tag
Remember to put your api key.
Enjoy Coding :)

YII2. Using URL's in js

I have the following javascript code
$(".order-event-btn").click(function(e) {
$.ajax({
url: "URL",
type: "POST",
data: {
eventId: $(e.target).attr('data-event-id'),
},
success: function(data) {
//Some code
},
error: function(data) {
//Some code
},
});
});
I include this script using "BookAsset".
Here
url: "URL",
I need URL to the action "book-event" in the controller Book.
On the server, I can do this:
Url::to('/book/book-event')
But how do I get URL on client side?
There is an solution:
1. js file include via BookAsset.
2. in view file I register bundle:
\frontend\assets\BookAsset::register($this);
3. in view file define a bookEventURL variable. Now it is available in the js-file.
$this->registerJs('var bookEventURL = ' . Url::to('/book/book-event') . ';');
But I do not like this solution.
What will happen when I use this script in many views. I have to define a variable bookEventURL in each view?
My Question. Is it possible to bind js-variables to my BookAsset. When I register my BookAsset in the view, in page source code automatically insert next code:
<script>var bookEventURL = "http://example.com/book-event/";</script>
A proper way of doing this is to add the needed information in your button tag, e.g. :
<?= Button::widget([
'label' => 'Order',
'options' => [
'class' => 'order-event-btn',
'data' => [
'url' => Url::to(['book/book-event']),
],
],
]) ?>
And in your js code :
$(".order-event-btn").click(function(e) {
var url = $(this).data('url');
// ...
});
But if you really want to "bind js-variables" to your BookAsset, you could simply override register() :
public static function register($view)
{
parent::register($view);
$view->registerJs('var bookEventURL = ' . json_encode(Url::to(['book/book-event'])) . ';');
}
If you wanna use it in different places of your application than I guess you should place it in the layout.

Categories

Resources