Update text in block with Nodejs integration module in drupal 8 - javascript

Below is information what I have done till now and what I am trying to do.
What I have done till now
Nodejs module and drupal 8 done. Example modules are working fine.
Created a simple module in drupal 8 consists of a form called simple
form. On its submit function, called nodejs module function to enqueue my message to the channel.
Javascript callback function created defined in nodejs enqueue message.
What I have been trying to acheive
When submitting a text form. Just to update the block in drupal 8.( Update the block content with hello world.)
Problem
My javascript callbacks associated with nodejs aren't being called.
Below are my codes.
Submit Function Code
public function submitForm(array &$form, FormStateInterface $form_state) {
/*$message->broadcast = TRUE;
* This would normally be replaced by code that actually does something
* with the title.
*/
$title = $form_state->getValue('title');
$message = (object) array(
'channel' => 'example',
'broadcast' => TRUE,
'callback' => 'example',
'data' => array(
'message' => 'Hello World'
),
);
nodejs_enqueue_message($message);
drupal_set_message(t('You specified a title of %title.', ['%title' => $title]));
}
Javascript callback code
(function ($) {
Drupal.Nodejs.callbacks.example = {
//grab the message and inject into the header
callback: function (message) {
console.log('simple example');
if(message.channel == 'example') {
$('#nodejs-selector').html(message.data.body);
}
}
};
})(jQuery);
Any help on this, I would be very grateful. I would love to provide more information on this, if anyone needed.

You should modify $message as
$message = (object) array(
'channel' => 'example',
'broadcast' => TRUE,
'callback' => 'example',
'data' => array(
'body' => 'Hello World'
),
);
To access the message body as message.data.body

Related

How to get the current post type in JavaScript?

I want to change several background colors via "post type".
I don't know how to query the "post type".
I know, that my code is 100% wrong. I searched the web for a solution. But couldn't find any, that would work.
(function() {
var elements, posttype;
function init() {
elements = document.querySelectorAll('.color');
posttype = get_post_type();
}
function checkColor() {
if (posttype === 'veranstaltung') {
element.classList.add('pink');
element.classList.remove('color');
} else if (posttype === 'ausstellung') {
element.classList.add('green');
element.classList.remove('color')
} else if (posttype === 'digitale-events') {
element.classList.add('red');
element.classList.remove('color')
}
}
init();
checkColor();
})();
One method is javascript if you create a function inside function.php which you have to call all the custom post type and return all the post with ajax in javascript which I do not suggest, the second method is to create a custom page and display all the custom post type with php, and then you have to do a condition to check which post type is the post and then add a custom class to each custom post type.*Note: This get all posts of a custom type use:
$posts = get_posts([
'post_type' => 'custom',
'post_status' => 'publish',
'posts_per_page' => -1,
'order' => 'ASC'
]);

How to handle error from controller using PJAX in YII2?

I am using Yii2 Pjax widget which is unable to throw error from controller due to which I am unable to log error for users when there is any error coming from the controller.
PJAX code
<?php Pjax::begin([
'id' => 'createBucketPjax',
'timeout' => 4000,
'formSelector' => '#createBucketForm',
'enablePushState' => false,
'clientOptions' => [
'skipOuterContainers' => true,
'error' => new JsExpression("function(event) {
alert('Anything');
}"),
]
]); ?>
CONTROLLER code:
if(!$fieldModel->save()){
$transaction->rollBack();
//Here I want to send error
$error = $fieldModel->getErrorsString();
return [
'success' => false,'error' => $error
];
}else{
return $this->renderAjax('create', [
'model' => $model
]);
}
I have tried below clientOptions but not working
'error' => new JsExpression("function(event) {
alert('Please work');
}"),
Also used javascript but no help :-
$(document).on('pjax:error', function(event) {
console.log(event);
})
Is there any way from which I can send 404 from controller in yii2 ? That can actually resolve my problem
From the Yii2 Pjax docs.
In responding to the AJAX request, Pjax will send the updated body content (based on the AJAX request) to the client which will replace the old content with the new one. The browser's URL will then be updated using pushState. The whole process requires no reloading of the layout or resources (js, css)
You must deal with full form content and not with json.
So you code must look like following (always return the form html back):
if(!$model->save()){
$transaction->rollBack();
}
return $this->renderAjax('create', [
'model' => $model
]);

Create/update lead using Javascript for Intercom?

We would like to create/update a lead in Intercom via Javascript, we can do it through the PHP, but I have no idea how to do the same with Javascript, because we are using Unbounce landing page and when visitor fill out the form we would like send it to Intercom and create the lead for us.
We can use Zapier integration inside the Unbounce but passing the UTM parameters is not allowed, so we want to use the Intercom API/Javascript directly.
Below is the PHP script that we are using to create lead through WP Intercom API
Anyone how to do the same using Javascript? so I can put inside the Unbounce page script manager.
$client = new IntercomClient('xxxxxxxxxxxxx=', null);
try {
// First check if this already exists
$leads = $client->leads->getLeads(['email' => $post['email']]);
foreach ($leads->contacts as $lead) {
$id = $lead->id;
}
if(!$id) {
$id = '';
}
$client->leads->update([
"id" => $id,
"email" => $post['email'],
"name" => preg_replace("/[^a-zA-Z0-9\s]/", "", ucwords($post['first_name'])),
"last_request_at" => time(),
"last_seen_ip" => $_SERVER['REMOTE_ADDR'],
"utm_campaign" => $post['Utm_campaign],
"utm_content" => $post['Utm_content'],
"utm_medium" => $post['Utm_medium'],
"utm_source" => $post['Utm_source'],
"utm_term" => $post['Utm_term'],
'Form Message' => preg_replace("/[^a-zA-Z0-9\s]/", "", $post['description'])]
]);
} catch(ClientException $e) {
$response = $e->getResponse();
$statusCode = $response->getStatusCode();
if ($statusCode == '404') {
// Handle 404 error
return;
} else {
throw $e;
}
}

How to add js-file to wordpress widget?

I try to add test.js file to my widget in front-end part. But it's nothing happens. The file contain alert. What's wrong with my code?
class PPNDR_new_widget extends WP_Widget{
function __construct(){
$args = array(
'name' => 'new widget',
'description' => 'this is my first widget',
'classname' => 'ppndr-new-widget'
);
parent::__construct('my_first', '', $args);
}
//front-end display of widget
public function widget($args, $instance) {
add_action('wp_enqueue_scripts', 'CounDounJS_enqueue_js');
function CounDounJS_enqueue_js() {
wp_enqueue_script('resize', plugins_url('/assets/js/test.js', __FILE__));
}
return;
}
}
add_action( 'widgets_init', function() {
register_widget('PPNDR_new_widget');
} );
I had a similar problem and google led me here -- What ended up working for me was eliminating the add_action('wp_enqueue_scripts.. and simply enqueuing my scripts and styles in the widget function.
for example:
//front-end display of widget
public function widget($args, $instance) {
wp_enqueue_script('resize', plugins_url('/assets/js/test.js', __FILE__));
}
There is the problem of not being able to dequeue the script, but I suspect the need for this would be slim.
Hope this helps.

Call a function in JS file from drupal

I have included a javascript in the module "myid" I've been developing in drupal by using this code:
function myid_init() {
drupal_add_js(drupal_get_path("module", "myid") . "js/myid.js");
}
This is my Javascript file "myid.js":
function myid_js_start(){
alert("hello world");
}
Below is the code that creates a button that invokes an alert function:
$form['add_button'] = array(
'#type' => 'button',
'#value' => 'Take a picture',
'#attributes' => array('onclick' => 'myid_js_start()'),
);
I dont know where did I go wrong. The button shows up but doesn't fire any alert function. Can anyone help me with this?
If you have followed the proper drupal directory structures and everything is where it supposed to be then it could be you are setting the attributes[onclick] as 'myid_js_start()'. Try doing it like
$form['add_button'] = array(
'#type' => 'button',
'#value' => 'Take a picture',
'#attributes' => array('onclick' => 'myid_js_start'),
);
Maybe that will solve it.
I don't have a drupal system setup at the moment to test your code. It could be something else but worth a try.
Attach the .js file to the form itself using #attach.
$form['#attached']['js'] = array(
drupal_add_js(drupal_get_path("module", "myid") . "js/myid.js"),
);

Categories

Resources