I want to change the name of the comment from the users account name to use the real name of the user (I am using RealName and CCK fields).
This should be simple, however it is not correctly saving my values.
function mymodule_comment(&$a1, $op) {
switch ($op) {
case 'insert':
case 'update':
$realname = realname_get_user($a1['uid']);
if ($realname) {
$a1['name'] = $realname->name;
}
break;
case 'view':
$realname = realname_get_user($a1->uid);
if ($realname) {
$a1->name = $realname->name;
}
break;
}
}
If I dump a1 in both cases, the name is what I want it to be. This is not what is saved to the database, however.
How can I change the values so they are actually inserted?
Please provide info about realname_get_user function or else you can try below snippet
function mymodule_comment(&$a1, $op) {
global $user;
switch ($op) {
case 'insert':
case 'update':
$realname = $user->name;
if ($realname) {
$a1['name'] = $realname;
}
break;
case 'view':
$realname = $user->name;
if ($realname) {
$a1->name = $realname;
}
break;
}
}
Related
Do you know if there is way to implement global message handlers that can support commands like stop, bye, cancel, exit Virtual assistant bot ? I am trying to implement something like this.
I have a virtual assistant built already and it has couple of Skills or Skill Bots.
When user is in the multi turn conversation with a Skill, user should be able to exit out of skill by commands like stop, bye, cancel, exit.
I found old v3 doc but nothing for v4.
Check the documentations provided here Handling User Interruption They explain how to handle user interruption for SDK v4
Find below an example of how you can configure this in the Virtual Assistant.
In your MainDialog.cs
Add the following for your OnContinueDialogAsync: Keeping in mind that you can change and edit this as you see fit just be sure to check the OnInterruptDialogAsync result (status in this example) before you continue
protected override async Task<DialogTurnResult> OnContinueDialogAsync(DialogContext innerDc, CancellationToken cancellationToken = default(CancellationToken))
{
var status = await OnInterruptDialogAsync(innerDc, cancellationToken).ConfigureAwait(false);
if (status == InterruptionAction.Resume)
{
// Resume the waiting dialog after interruption
await innerDc.RepromptDialogAsync().ConfigureAwait(false);
return EndOfTurn;
}
else if (status == InterruptionAction.Waiting)
{
// Stack is already waiting for a response, shelve inner stack
return EndOfTurn;
}
else
{
var activity = innerDc.Context.Activity;
if (activity.IsStartActivity())
{
await OnStartAsync(innerDc).ConfigureAwait(false);
}
switch (activity.Type)
{
case ActivityTypes.Message:
{
// Note: This check is a workaround for adaptive card buttons that should map to an event (i.e. startOnboarding button in intro card)
if (activity.Value != null)
{
await OnEventAsync(innerDc).ConfigureAwait(false);
}
else
{
var result = await innerDc.ContinueDialogAsync().ConfigureAwait(false);
switch (result.Status)
{
case DialogTurnStatus.Empty:
{
await RouteAsync(innerDc).ConfigureAwait(false);
break;
}
case DialogTurnStatus.Complete:
{
// End active dialog
await innerDc.EndDialogAsync().ConfigureAwait(false);
break;
}
default:
{
break;
}
}
}
// If the active dialog was ended on this turn (either on single-turn dialog, or on continueDialogAsync) run CompleteAsync method.
if (innerDc.ActiveDialog == null)
{
await CompleteAsync(innerDc).ConfigureAwait(false);
}
break;
}
case ActivityTypes.Event:
{
//do something for event activity
break;
}
case ActivityTypes.Invoke:
{
// Used by Teams for Authentication scenarios.
break;
}
default:
{
await OnSystemMessageAsync(innerDc).ConfigureAwait(false);
break;
}
}
return EndOfTurn;
}
}
And override OnInterruptDialogAsync like below example:
This example includes LUIS but you can do whatever you want in OnInterruptDialogAsync
protected override async Task<InterruptionAction> OnInterruptDialogAsync(DialogContext dc, CancellationToken cancellationToken = default(CancellationToken))
{
var result = InterruptionAction.NoAction;
if (dc.Context.Activity.Type == ActivityTypes.Message && !string.IsNullOrEmpty(dc.Context.Activity.Text))
{
// get current activity locale
var localeConfig = _services.GetCognitiveModels();
// check general luis intent
localeConfig.LuisServices.TryGetValue("General", out var luisService);
if (luisService == null)
{
throw new Exception("The specified LUIS Model could not be found in your Skill configuration.");
}
else
{
var luisResult = await luisService.RecognizeAsync<GeneralLuis>(dc.Context, cancellationToken);
var topIntent = luisResult.TopIntent();
if (topIntent.score > 0.5)
{
switch (topIntent.intent)
{
case GeneralLuis.Intent.Cancel:
{
result = await OnCancel(dc);
break;
}
case GeneralLuis.Intent.Help:
{
result = await OnHelp(dc);
break;
}
case GeneralLuis.Intent.Logout:
{
result = await OnLogout(dc);
break;
}
}
}
}
}
return result;
}
On the time of page loaded get_switch() function which globally created on app.js page will be call then return a method. i want to execute these return methods.
demo.js
const return_functions = get_switch('BTC');
function get_btc()
{
console.log('btc');
}
function get_bch()
{
console.log('bch');
}
app.js
global.get_switch=function(coin_name){
switch(coin_name){
case 'BTC':
return 'get_btc()';
break;
case 'BCH':
return 'get_bth()';
break;
default:
console.log('default');
}
}
As shown in example above i have passed BTC in get_switch. and that function return us get_btc() function. so i want to call get_btc function on same time.
If this is not possible in this way so please guide me with your idea and suggest me how can i do this.
demo.js
var obj = {
get_btc: function get_btc() {
console.log('btc');
},
get_bth: function get_bth() {
console.log('get_bth');
}
}
const return_functions = get_switch('BTC');
if (return_functions) {
obj[return_functions]();
}
app.js
global.get_switch = function (coin_name) {
switch (coin_name) {
case 'BTC':
return 'get_btc';
break;
case 'BCH':
return 'get_bth';
break;
default:
console.log('default');
}
}
var get_switch=function(coin_name){
switch(coin_name){
case 'BTC':
get_btc();
break;
case 'BCH':
get_bth();
break;
default:
console.log('default');
}
}
get_switch('BTC');
function get_btc() {
console.log('btc');
}
function get_bch() {
console.log('bch');
}
I am using asp,net core and have used the tutorial to create sorted, paged and search page (Index). Once I edit an item from this page the controller always dumps me back to the default index page. How do I return to the previous URL. Many thanks.
Here is a section of my controller file.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, Bind("id,UserPassword,user")] UserProfiles userProfiles)
{
var users = from u in _context.UserProfiles
select u;
if (id != userProfiles.id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(userProfiles);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!UserProfilesExists(userProfiles.id))
{
return NotFound();
}
else
{
throw;
}
}
// ***************
// Redirect to the previous URL,i.e. the Index
return Redirect(TempData["PreviousURL"].ToString()) ;
}
return View(userProfiles);
}
public async Task<IActionResult> Index(string sortOrder, string currentFilter, string searchString, int? page)
{
ViewData["CurrentSort"] = sortOrder;
ViewData["NameSortParm"] = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
// paging
if (searchString != null)
{
page = 1;
}
else
{
searchString = currentFilter;
}
// search
ViewData["CurrentFilter"] = searchString;
var users = from u in _context.UserProfiles
select u;
if (!String.IsNullOrEmpty(searchString))
{
users = users.Where(u => u.user.Contains(searchString)
);
}
//sort
switch (sortOrder)
{
case "name_desc":
users = users.OrderByDescending(u => u.user);
break;
default:
users = users.OrderBy(s => s.user);
break;
}
// ***************
// store the current path and query string in TempData["PreviousURL" session variable
TempData["PreviousURL"] = HttpContext.Request.Path.ToString() + HttpContext.Request.QueryString.ToString();
return View(await PaginatedList<UserProfiles>.CreateAsync(users.AsNoTracking(), page ?? 1, pageSize));
}
This is my first MVC project.
It depends on your logic where controller takes you after saving data.
You need to pass search, sort and paging related data to controller when saving data. You can send them as part of extra post data, as query string parameters or as part of the model itself which is being posted.
After saving data retrieve data based on those parameters and populater your view with that paged, filtred and sorted data.
I solved my problem with the use of session variables: ViewData, ViewBag and TempData. The following two pages were very useful:
https://www.codeproject.com/Articles/476967/What-is-ViewData-ViewBag-and-TempData-MVC-Option
http://andrewlock.net/an-introduction-to-session-storage-in-asp-net-core/
Please see edited question above for the solution.
How can we clone an object in Polymer?
Example
this.colorsAsc.push({color: 'red'});
this.colorsDesc = this.colorsAsc.reverse();
this.colorsDesc[0].color = 'blue'; // Both will be blue doing this
I can do it in these many functionalities What is the most efficient way to deep clone an object in JavaScript? but I wonder if there is a way in Polymer to do that?
Angular does it https://docs.angularjs.org/api/ng/function/angular.copy
You can try the following hack:
this.colorsDesc = JSON.parse(JSON.stringify(this.colorsAsc.reverse());
I have had the same question here, where I have finally also found and posted an answer.
Short version:
newElement = element.cloneNode(true);
for(var i in element.properties) {
newElement[i] = element[i]
}
To clone a utility via Polymer
Full implementation:
(function(callBackFn) {
Polymer({
//Component Name
is: 'my-cloner',
properties: {
//Declare a published property
cloneableObject: { //Placeholder for Object to be cloned
reflectToAttribute: true,
type: Object,
notify: true
}
},
attached: function() {
//Hide if this component got attached
this.hidden = true;
},
getClone: function(incomingcloneableObject) { //Will be called to get the Clone
this.cloneableObject = this.cloneableObject || incomingcloneableObject;
switch (typeof this.cloneableObject) {
case "undefined":
return null;
break;
case "object":
var localClone = this.cloneNode();
return (localClone.cloneableObject);
break;
case "boolean":
return new Boolean(this.cloneableObject).valueOf();
//Other possible way
//return(this.cloneableObject ? true : false);
break;
case "number": //NaN is taken care of
return new Number(this.cloneableObject).valueOf();
//Other possible way
//return(this.cloneableObject * 1);
break;
case "string":
return new String(this.cloneableObject).valueOf();
//Other possible way
//return(this.cloneableObject + '');
break;
default:
return null;
}
}
});
//adding Util into window
callBackFn();
})(function() {
window.cloneUtil = document.createElement('my-cloner');
});
//To use this util
//window.cloneUtil.getClone();
I am trying to modify comment body before saving or updating in drupal 6. I am trying to use following code:
function mymodule_comment(&$a1, $op) {
switch ($op) {
case 'insert':
case 'update':
$a1['comment'] = myfunction($a1['comment']);
break;
}
}
But it is not updating the comment body after save. I also tried following code and it works:
function mymodule_comment(&$a1, $op) {
switch ($op) {
case 'insert':
$a1['comment'] = myfunction($a1['comment']);
comment_save($a1);
break;
}
}
But in case of update it is showing error:
function mymodule_comment(&$a1, $op) {
switch ($op) {
case 'update':
$a1['comment'] = myfunction($a1['comment']);
comment_save($a1);
break;
}
}
Any idea or help is very appreciated.
Ok I got the work around. first create a hook_form_alter function:
mymodule_form_alter($form,$form_state,$form_id){
if ($form_id == 'comment_form') {
$form['#submit'][] = 'mymodule_comment_form_submit';
}
}
Then create hook_comment_form_submit function and do your modification:
mymodule_comment_form_submit($form, $form_state){
$form_state['values']['comment'] = myfunciton($form_state['values']);
comment_save($form_state['values']);
}
I dont know whether it is a good idea or not but I found few of post in which this approach is used.