8 – How to notify user using ->messenger() and ajax?

I would like to send a message to the user on an event in the backend without a refresh. I have a 2fa login form that will send a token text. That form has a “did not receive sms” button/link using ajax that causes the text to be sent again. I would like to inform the customer of the incoming message.

You can send a notification to the user using the MessengerInterface. But this requires a refresh to show the message.

Drupal::messenger()->addStatus('Some conditional message to the user');

I would imagine that there is a way to send a message to the user using ajax/XHR? Which would not require a refresh.

My form has a wrapping div which I can target, the button/link has an '#ajax' element with, as far as I know, all the prerequisite elements:

'#ajax' => (
  'callback' => '::ajaxCallback',
  'event' => 'click',
  'wrapper' => 'twofa_wrapper',
),

I found this comment on the Drupal forum but using this code, with obvious replacements, does nothing apart from sending a XHR response, visible in the network tab. The json response contains a number of things one being the html for the form which contains the message that I would like to show, but it doesn’t show this content on the actual page.

public function ajaxCallback(array &$form, FormStateInterface $form_state) {
  $response = new AjaxResponse();
  // This by some Drupal magic gets the messages
  $messages = ('#type' => 'status_messages'); 
  $messages = Drupal::service('renderer')->render($message);
  $response->addCommand(new HtmlCommand('#twofa_wrapper', $messages));
  $response->addCommand(new ReplaceCommand(null, $form));
  return $response;
}

What am I missing?

edit:


The wrapping element was (is) not rendering for some reason, if I include it in the template the callback shows the messages in that element at the top of the form.

The problem is that I need to renew the entire form because the contents might change on the ajax call. Replacing the contents works when I actually enclose the form in the wrapper element, but then the messages are no longer included.

I can see that the messages are part of the response but separate from the form contents. Second element messages third element the new form. The strange thing is the message are also not shown on a refresh.

enter image description here

wp query – Get user first name from custom endpoint

I am trying to set up a custom endpoint which only returns some user data instead of the default data sent back by the users endpoint. But I don’t know how to get the first and last name of the user from WP_User_Query

add_action( 'rest_api_init', function () {
  register_rest_route( 'myplugin/v1', 'some-endpoint', array(
    'methods' => 'GET',
    'callback' => 'my_awesome_func',
  ) );
} );

function my_awesome_func( $request) {

            $user_fields = array( 'user_nicename', 'user_url', 'first_name' );
            $wp_user_query = new WP_User_Query( array( 'role' => 'subscriber', 'fields' => $user_fields ) );
            $members = $wp_user_query->get_results();

    return new WP_REST_Response(
        array(
            'status' => 200,
            'response' => $members
        )
    );
    
    return $response;
}

If I remove ‘first_name’ from my array then I get back user_nicename and user_url in the response for all users. But with first_name in there I just get an empty response. I also tried firstname instead of first_name but still no joy.

Also, this only returns a handful of users. How do I show them all or 10, 20, 30 etc.

javascript – Created a basic User Profile List using an API (React)

I’m relatively new when it comes to programming in React and in JavaScript, but have a surface level understanding of what things do. I’ve created a basic program that fetches user data from an API that generates random users, and appends the users to a list when you click a button. I was wondering if what I’m writing is good enough to be considered for a Jr. React Dev position, and if there’s anything I can improve upon the code such as implementation, name convention, readability, efficiency, etc. In particular, in the UserProfile component, I’m mapping through the state that holds the JSON object that was fetched from the API to output the profile picture and name. I’m not sure if there’s anyway to do it better, but it doesn’t feel quite right to me. Any feed back is much appreciated.

UserProfile.jsx

import React, { useState, useEffect } from "react";

const UserProfile = () => {
  const (userData, setUserData) = useState(());

  const fetchUserData = () => {
    fetch("https://randomuser.me/api")
      .then((resp) => resp.json())
      .then((data) => setUserData(data.results));
  };

  //Creates userProfile with picture/full name
  const userProfile = (userMeta) => {
    const {
      name: { first, last },
      picture: { medium }
    } = userMeta;

    return (
      <>
        <img src={medium} alt="" />
        <p>
          {first}, {last}
        </p>
      </>
    );
  };

  //Fetch API data on component mount
  useEffect(() => {
    fetchUserData();
  }, ());

  return (
    <>
      {userData.map((userMeta, idx) => {
        return <div key={idx}>{userProfile(userMeta)}</div>;
      })}
    </>
  );
};

export default UserProfile;

UserList.jsx

import React, { useState } from "react";
import UserProfile from "./UserProfile";

const UserList = () => {
  const (userList, setUserList) = useState(());

  //Appends UserProfile to List
  const addUser = () => {
    setUserList((prevState) => {
      return (...prevState, <UserProfile />);
    });
  };

  return (
    <div>
      <button onClick={addUser}>Add User</button>
      {userList.map((user, idx) => {
        return <React.Fragment key={idx}> {user} </React.Fragment>;
      })}
    </div>
  );
};

export default UserList;

App.js

import React from "react";
import UserList from "./UserList";

export default function App() {
  return (
    <div className="App">
      <p>USER LIST COMPONENT</p>
      <UserList />
    </div>
  );
}

user interface – Powershell: GUI input to text file

I’ve created an input box with PowerShell. When I want to save the input to a text file I get this in the text file:

path=System.Windows.Forms.TextBox, Text: MYINPUTTEDTEXT.text

Code to output the text:

$PSDefaultParameterValues['Out-File:Encoding'] = 'ascii'
$textinput="$textfieldfolder.text"
write-output "path=$textinput" >> User-Generatedpreferences.ini

But I would like to have only:

path=MYINPUTTEDTEXT

Thanks for your help!

JJB

sql server – Cant delete a user

You can find it here:

enter image description here

Or you can query the Database this way:

SELECT
      sp.name AS OwningLogin
    , dp.name AS OwningUser
    , s.name AS SchemaName
FROM sys.schemas AS s
JOIN sys.database_principals AS dp ON
    dp.principal_id = s.principal_id
JOIN sys.server_principals AS sp ON
    sp.sid = dp.sid;

I don’t think you have to delete the users before migration.
Users cannot be migrated from on-prem to Azure SQL Database and you need to recreate them.

I suggest you to keep them and just recreate them later on Azure: https://techcommunity.microsoft.com/t5/azure-database-support-blog/lesson-learned-35-how-to-transfer-the-login-and-user-from/ba-p/369031

Ultimate Member – Show List of Posts (Post Type) by all users that current logged in user follows

I am new to the ‘Ultimate Member’ plugin and I am using the ‘UM Followers’ extension plugin.

My users can all generate posts (post type).

I would like to set up a page-template in which the current logged in user can see a list of all posts sorted by most recent, only by users that he/she follows.

I had a look at the following template that generates a list of users using their avatars. But can’t figure out how I could use this to generate the list of posts by users my logged in user follows.

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

if ( $following ) {

    foreach ( $following as $k => $arr ) {
        /**
         * @var $user_id1;
         */
        extract( $arr );

        um_fetch_user( $user_id1 ); ?>
    
        <div class="um-followers-user">
    
            <a href="<?php echo esc_url( um_user_profile_url() ); ?>" class="um-followers-user-photo" title="<?php echo esc_attr( um_user( 'display_name' ) ); ?>">
                <?php echo get_avatar( um_user('ID'), 50 ); ?>
            </a>
        
            <div class="um-followers-user-name">
                <a href="<?php echo esc_url( um_user_profile_url() ); ?>" title="<?php echo esc_attr( um_user('display_name') ); ?>">
                    <?php echo esc_html( um_user( 'display_name' ) ); ?>
                </a>
            
                <?php do_action('um_following_list_post_user_name', $user_id, $user_id1 );

                if ( um_user( 'ID' ) == get_current_user_id() ) { ?>
                    <span class="um-followers-user-span"><?php _e( 'You', 'um-followers' ); ?></span>
                <?php } elseif ( UM()->Followers_API()->api()->followed( get_current_user_id(), $user_id1 ) ) { ?>
                    <span class="um-followers-user-span"><?php _e( 'Follows you', 'um-followers' ); ?></span>
                <?php }

                do_action('um_following_list_after_user_name', $user_id, $user_id1 ); ?>
            </div>
        
            <div class="um-followers-user-btn">
                <?php if ( $user_id1 == get_current_user_id() ) {
                    echo '<a href="' . esc_url( um_edit_profile_url() ) . '" class="um-follow-edit um-button um-alt">' . __( 'Edit profile', 'um-followers' ) . '</a>';
                } else {
                    echo UM()->Followers_API()->api()->follow_button( $user_id1, get_current_user_id() );
                } ?>
            </div>
        
            <?php do_action( 'um_following_list_pre_user_bio', $user_id, $user_id1 ); ?>
        
            <div class="um-followers-user-bio">
                <?php echo um_get_snippet( um_filtered_value( 'description' ), 25 ); ?>
            </div>
        
            <?php do_action( 'um_following_list_post_user_bio', $user_id, $user_id1 ); ?>
        
        </div>
    
    <?php }

} else { ?>

    <div class="um-profile-note">
        <span><?php echo ( $user_id == get_current_user_id() ) ? __( 'You did not follow anybody yet.', 'um-followers' ) : __( 'This user did not follow anybody yet.', 'um-followers' ); ?></span>
    </div>

<?php }```

thanks to anyone who could assist :)

user interface – Java Programming II Course GUI doesn’t work

I’m doing the Java Programming II MOOC course, and I’m having some problems with the section on GUIs. Whenever I copy and paste the code for the GUI into netbeans, it just results in a bunch of errors, and I have no idea how to fix them. The errors are like “package javafx.application does not exist,” and I don’t know how to make it exist. Do I need to install or import something to make it work?

Here’s a screenshot of what my code looks like right now. It’s just copy and pasted from the website, but you can see where the errors are:
GUI code in Netbeans

A c++ program to take the size and components of an Array from user and return the reversed Array

I have written this code that should take the size and components of the array from the user and then return the reverse of the Array but not able to identify and fix the error.
My best guess is that the while loop is causing trouble, but I am not sure.

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;


// function to reverse given array
void reverseArray(int arr(), int start, int end){

while (start<=end){
    int temp = arr(start);
    arr(start) = arr(end);
    arr(end) = temp;
    start++;
    end--;
       
}

}


// function to print given array
void printArray(int arr(), int size){
   for (int i = 0; i < size; i++)
   cout << arr(i) << " ";
}


int main() {
    int n;
    cin >> n;
    int mainarray() = {n} ; 
    n = sizeof(mainarray);

    for (int i=0; i<n; i++) {
        cin >> mainarray(i);
    }

reverseArray(mainarray , 0, n-1);
printArray(mainarray ,n);

    return 0;
}

8 – Create a layout on a user route

I’m trying to add a Moderation Dashboard tab to the user page like the Moderation Dashboard module, but I can’t use Panels. Is it possible to create a layout on a route using layout builder?

I’ve created the route in msk_module/my_module.routing.yml with

my_module.moderation_dashboard:
  path: '/user/{user}/dashboard'
  defaults:
    _title: 'Moderation Dashboard'
    _controller: 'Drupalmy_moduleControllerMyModuleDashboardController::index'
  requirements:
    _user_is_logged_in: 'TRUE'

And the links task in msk_module/my_module.links.task.yml with

my_module.moderation_dashboard:
  route_name: my_module.moderation_dashboard
  base_route: entity.user.canonical
  title: 'Moderation Dashboard'
  weight: 30

And started the controller in msk_module/src/Controller/MyModuleDashboardController.php with

<?php

namespace Drupalmy_moduleController;

use DrupalCoreControllerControllerBase;
use SymfonyComponentHttpKernelExceptionNotFoundHttpException;

/**
 * Controller for moderation dashboard.
 */
class MyModuleDashboardController extends ControllerBase {

  /**
   * Display the markup.
   *
   * @return array
   *   Return markup array.
   */
  public function index() {
    return (
      '#type' => 'markup',
      '#markup' => $this->t('Hello, World!'),
    );
  }

}

So the tab is where I want it. The contents for the tab are the block views displays from the views from Moderation Dashboard. I suppose I can use hook_theme() and a template and some small amount of CSS. Just wondering if layout builder can do the same thing as the panel in page manager can do?