How to auto-fill field with user's name?

The recommended method of customizing your AppGini-generated application is through hooks. But sometimes you might need to add functionality not accessible through hooks. You can discuss this here.
Post Reply
artemisia
Veteran Member
Posts: 59
Joined: 2013-10-01 15:50

How to auto-fill field with user's name?

Post by artemisia » 2013-10-24 20:02

I have read the documentation and all of the forum messages, but I can't see how to do this task: User logs on, goes to submit a new record, and the required "Reporter" field would be already filled with his Full Name (Custom1 from user_membership). I tried some variations on sql in all of the relevant hook php files, to no avail (no error, but no effect). There was a hint in one old message that it can be done with javascript, but I'm not sure which php file to do this in, nor what the javascript would look like.

Can anyone point me in the right direction for this enhancement? I'm sure it'd be useful to others as well.

Thanks,
~Bob

User avatar
dilitimor
Veteran Member
Posts: 36
Joined: 2013-01-10 02:45
Location: Jakarta, Indonesia
Contact:

Re: How to auto-fill field with user's name?

Post by dilitimor » 2014-03-28 10:09

You can use "automatic value"

benzoD
Veteran Member
Posts: 69
Joined: 2013-01-31 21:16

Re: How to auto-fill field with user's name?

Post by benzoD » 2014-04-04 15:37

Agreed. You could create a read-only field that had an automatic value of <created by username> that wouldn't fill out until the record was saved.

artemisia
Veteran Member
Posts: 59
Joined: 2013-10-01 15:50

Re: How to auto-fill field with user's name?

Post by artemisia » 2014-04-06 17:41

Please note that I wish to use "Full Name", not login or username. I have not been able to make this work, despite several different attempts. The field needs to show the current user's Full Name immediately, and I'd like to reserve the option to keep the Reporter's dropdown active to give the user the option of selecting another name from the list. I'm sure this can be done, but not sure whre the code mod needs to be made.

omackeytech
Veteran Member
Posts: 35
Joined: 2014-06-04 13:18

Re: How to auto-fill field with user's name?

Post by omackeytech » 2014-07-05 03:09

I was able to make this work, it took a while but here's what I did:

Code: Select all

[code]
function Time_Entry_before_insert(&$data, $memberInfo, &$args){
		$mi = getMemberInfo();
		$data['E_Name'] = $mi['custom'][0];
		return TRUE;
	}
[/code]

First thing is to retrieve the member-info array: $mi = getMemberInfo()
Then set the field you want the name in (E_Name in my case) to the member info custom field.

See http://bigprof.com/appgini/help/advance ... Info-array

artemisia
Veteran Member
Posts: 59
Joined: 2013-10-01 15:50

Re: How to auto-fill field with user's name?

Post by artemisia » 2014-07-05 21:36

Didn't work for me (appgini v5.23 & 5.30, copies of same db): field remains empty (default) on new record entry dialog. Note that my drop-down is a lookup to another table using "username" (memberID) as primary key, so my code looks like this:

Code: Select all

$mi = getMemberInfo(); 
$data['Reporter'] = $mi['username'];
I tried it in these functions in the hook file: tablename_init(), _before_insert()

User logged on and entering new record (not updating existing) needs to see their full name (custom1) in the Reporter dropdown before submitting, but can select another name from the list if needed.

~Bob

User avatar
a.gneady
Site Admin
Posts: 1281
Joined: 2012-09-27 14:46
Contact:

Re: How to auto-fill field with user's name?

Post by a.gneady » 2014-07-10 10:12

the before_insert hook applies the change after submitting the form. If you want to display the username before submission, use the automatic value "Created by username" in AppGini. See this screenshot: http://screencast.com/t/giYpcvZcPJK
:idea: AppGini plugins to add more power to your apps:
  • DataTalk is an innovative AppGini plugin based on ChatGPT that allows you to interact with your AppGini database using natural language questions, without writing any SQL. Check the demo video
  • Mass Update plugin: Update multiple records at once and improve your workflow efficiency.
  • Check our other plugins and get a generous discount of up to 30% when buying 2 or more plugins.

artemisia
Veteran Member
Posts: 59
Joined: 2013-10-01 15:50

Re: How to auto-fill field with user's name?

Post by artemisia » 2014-07-10 16:18

I'll explain what I've already done, which prompted my original question starting this thread:

1. Using auto value of either created by or edited by username, for a dropdown field not linked to any other table, results in the username, not the Fullname from Custom 1. The field becomes readonly and not changeable by the user.

2. Since membership_users is not available for selection in Parent Table, I created a copy called membership_users2, which is updated each time any user logs in to keep it synced with membership_users. That way I can simply link the Reporter dropdown with Custom1 and present users with a dropdown of all Fullnames in the table. Each user selects their own Fullname (but can select anyone else's too).
This is what I have in production now.

3. Adding an autovalue to scenario #2 doesn't work - I get a blank field with no data or dropdown, looks like auto value is not designed to work with parent table lookups; I would have thought that since MemberID is the primary key, it would find Custom1 given a MemberID value. When I look at the table data containing the Reporter field, I see mostly userids (MemberIDs) but also some integers (not sure why the latter).

Hopefully this explanation makes clearer what I am trying to accomplish. Again, what I'd like to see when a user is creating a new empty record (not a copy from existing record) is the dropdown Reporter field filled with all active Fullnames from Custom1 of membership_users, but preselected with with the logged-on user's Fullname. This will be a convenience for them to have their own name prefilled (very few users will need to select a name other than their own, but I need to leave open that possibility).

Thanks!

User avatar
a.gneady
Site Admin
Posts: 1281
Joined: 2012-09-27 14:46
Contact:

Re: How to auto-fill field with user's name?

Post by a.gneady » 2014-07-10 22:23

Hmm ... So, you've already created a copy of membership_users table in AppGini and named it membership_users2 as far as I understand ... and you used this to create a lookup field in another table where users would select the reporter full name and you want it pre-populated based on the current username. So if user john_doe is creating a new record, he should find "John Doe" pre-selected in that drop down, right?

If so, here is a simple way to do it ... Let's assume your lookup field is named "Reporter" and you table is named "Time_Entry" ... you should use the Time_Entry_header() hook to insert the following javascript code into the table view:

Code: Select all

$js_code = '<script>jQuery(function(){' . 
    'jQuery("form").append(\'<input name="filterer_Reporter" type="hidden">\');' .
    'jQuery("input[name=filterer_Reporter]").val("' . $memberInfo['username'] . '");' .
'});</script>';
I haven't tested the above code fully but the idea is to inject a hidden input field named filterer_fieldname into the form and set its value to the username. This will be submitted as part of the form when a user clicks "Add new" and would cause the lookup field to pre-select the item whose primary key was assigned to the filterer variable.
:idea: AppGini plugins to add more power to your apps:
  • DataTalk is an innovative AppGini plugin based on ChatGPT that allows you to interact with your AppGini database using natural language questions, without writing any SQL. Check the demo video
  • Mass Update plugin: Update multiple records at once and improve your workflow efficiency.
  • Check our other plugins and get a generous discount of up to 30% when buying 2 or more plugins.

artemisia
Veteran Member
Posts: 59
Joined: 2013-10-01 15:50

Re: How to auto-fill field with user's name?

Post by artemisia » 2014-07-10 22:44

Can you confirm that I'm testing the code in the right place? I placed it at the top of the Header section of the hook php file, but before the default code starting with $header='';
So far it's doing nothing that I can see, but if it's in the right place I'll work on the code itself.
~Bob

User avatar
a.gneady
Site Admin
Posts: 1281
Joined: 2012-09-27 14:46
Contact:

Re: How to auto-fill field with user's name?

Post by a.gneady » 2014-07-11 12:17

In addition, you should modify the tableview part of the function as follows:

Code: Select all

case 'tableview':
    $header = '<%%HEADER%%>' . $js_code;
For more info, please see http://bigprof.com/appgini/help/advance ... ame_header
:idea: AppGini plugins to add more power to your apps:
  • DataTalk is an innovative AppGini plugin based on ChatGPT that allows you to interact with your AppGini database using natural language questions, without writing any SQL. Check the demo video
  • Mass Update plugin: Update multiple records at once and improve your workflow efficiency.
  • Check our other plugins and get a generous discount of up to 30% when buying 2 or more plugins.

artemisia
Veteran Member
Posts: 59
Joined: 2013-10-01 15:50

Re: How to auto-fill field with user's name?

Post by artemisia » 2014-08-10 22:40

Tried this, and nothing happens (no error messages either).

TheCodeRed
Posts: 26
Joined: 2014-05-01 12:57

Re: How to auto-fill field with user's name?

Post by TheCodeRed » 2014-08-12 16:02

Seems like you guys are over thinking this in my eyes. The easiest way to do this is to have it auto record the username into a hidden field and then in After_Insert () hook, simply run a lookup of the full name using the members_users table. SELECT `Custom_Field1` FROM `Membership_Users` where memberID = "Value from hidden field w/ Autofill userID". Fill the Full name field in with the returned value.

This would not show to the user until AFTER the record has been saved or officially created.

artemisia
Veteran Member
Posts: 59
Joined: 2013-10-01 15:50

Re: How to auto-fill field with user's name?

Post by artemisia » 2014-08-13 16:29

I thank all readers who've made suggestions. However, before adding your advice or question here please read my original question and the entire thread.
The goal is to show the logged-on user's full name (Custom1) in the dropdown field while they are editing a new entry, not after they save it.

TheCodeRed
Posts: 26
Joined: 2014-05-01 12:57

Re: How to auto-fill field with user's name?

Post by TheCodeRed » 2014-08-15 17:45

Good call. This would not show results until saved record. My apologies for jumping in without re-reading the OP. AJAX with a temp table would probably be the best solution.

artemisia
Veteran Member
Posts: 59
Joined: 2013-10-01 15:50

Re: How to auto-fill field with user's name?

Post by artemisia » 2014-08-15 19:57

Can you be more specific on how to implement using AJAX? As far as web page manipulation goes I am far from an expert.
Thanks!

TheCodeRed
Posts: 26
Joined: 2014-05-01 12:57

Re: How to auto-fill field with user's name?

Post by TheCodeRed » 2014-09-04 17:36

I too am not an AJAX expert and would not be the best person to provide accurate solution using it.

omackeytech
Veteran Member
Posts: 35
Joined: 2014-06-04 13:18

Re: How to auto-fill field with user's name?

Post by omackeytech » 2014-09-15 04:17

OK, I noticed that the field I was writing to was editable. When I changed it to read only this code:

Code: Select all

$mi = getMemberInfo();
	 $data['E_Name'] = $mi['custom'][0];
will not work.
So after a few attempts I came up with the following and it will write to a read only field since it writes directly into the database.

Code: Select all

	function TableName_after_insert($data, $memberInfo, &$args){
		$mi = getMemberInfo(); $uname = $mi['custom'][0];
		$myID = $data['selectedID'];
		sql("UPDATE TableName Set FieldName = '$uname' Where ID = $myID", $eo);
		$myID = "";		
		return TRUE;}
Hope this works for your application.

omackeytech
Veteran Member
Posts: 35
Joined: 2014-06-04 13:18

Re: How to auto-fill field with user's name?

Post by omackeytech » 2014-09-16 02:19

My mistake, this still does not prefill the field. It only fills it after saving.

Sorry.

User avatar
shasta59
AppGini Super Hero
AppGini Super Hero
Posts: 231
Joined: 2013-01-08 19:40
Location: Calgary, Alberta, Canada

Re: How to auto-fill field with user's name?

Post by shasta59 » 2014-12-24 03:13

I needed this to work also. When a user creates a certain new record I need the name to be automatically put in. I am using ajax, javascript and a php file to do this. It works fine but is not very polished. I have to have this done in about 2 weeks and when I have it working nicely I will publish how to do it again. But if you are in a rush this works.

Basically what I have done is add code to the template file, do an ajax call to run a php file which returns the info and then it gets put into the field. Here is the raw info - I am sure it will change when I am done. But for now this works.

In tablename_templateDV.html I add the following at the end:

Code: Select all

<script>
//Browser Support Code
function ajaxFunction(){
	var ajaxRequest;  // The variable that makes Ajax possible!
	
	try{
		// Opera 8.0+, Firefox, Safari
		ajaxRequest = new XMLHttpRequest();
	} catch (e){
		// Internet Explorer Browsers
		try{
			ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try{
				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e){
				// Something went wrong
				alert("Your browser broke!");
				return false;
			}
		}
	}
	// Create a function that will receive data sent from the server
	ajaxRequest.onreadystatechange = function(){
		if(ajaxRequest.readyState == 4){
			document.getElementById('name').value=ajaxRequest.responseText;
		}
	}
	ajaxRequest.open("GET", "http://url_of_file/filename.php", true);
	ajaxRequest.send(); 
}
</script>
('name') is the id of the field I am putting the data into.

My php script for testing is just getting the user name as put in when they registered. I will be rewriting it to get their full name from their user profile which they have to create before they can do anything else.

Here is the php script I use. Again this is all preliminary but it works. The sql request will change and the file will be setup so it cannot be accessed by anyone else for security purposes. Again this is all preliminary but working.

Code: Select all

<?php
// file used to get the data I want to put into the name field on my form. 
$currDir=dirname(__FILE__);
	include("$currDir/lib.php");
	
$mi = getMemberInfo();
echo $mi['custom'][0];


?>
When I have it working better I will post this method again. There is more than 1 way to do this but this updates as soon as another field is changed. I will be updating it to insert the full user name as soon as the form is opened so it is seamless to the end user.

I also have another the same template file which is used by supervisors for this system where it shows all the names of all the members and they can pick and choose the name they want. This could not work for individual members so this is the method I used. (This came about because I was having some members type in their own name and a few made a spelling mistake and it messed up scripts in the hooks file since the user did not spell their own name correctly. ) This gave me greater flexibility overall. Meant other code changes but improved the efficiency of the system.

Currently I am trigging the inserting of the name using an onChange call in one of the other fields so I can test the code easily. As mentioned above this will change when I have fully tested it.

Any questions just ask.

Alan Sopczak
Calgary, Alberta, Canada - Using Appgini 5.50 -

User avatar
shasta59
AppGini Super Hero
AppGini Super Hero
Posts: 231
Joined: 2013-01-08 19:40
Location: Calgary, Alberta, Canada

Re: How to auto-fill field with user's name? #2

Post by shasta59 » 2014-12-26 22:41

Ok

Next chapter in this. This is all still along the line of cheap and dirty but working. A quick but not perfect solution.
Here is what I have done now.
The field I want to have auto filled when the table is opened has been set to read only manually. NOT USING APPGINI to do this. Here is how that is done.
Take a look at the attached code below and you will see where I have added the readonly. The rest is left the same and by doing it using this method it allows quick changes. This is done in the template file for the table.

(The other reason is this table has fields I need the end user to see but not be able to change. Another exact same template file exists which only certain groups can access and allows them to change fields. For example: A confirmed field. I cannot have an end user confirming/approving their own entry. But, I do need them to know when it has been confirmed. When a supervisor confirms the entry an email is sent to the end user letting them know and they can look at the record again to see it is checked off if they wish. It also allows for searching all confirmed/approved records. I also use this for a registration database when the registration has been confirmed. The organizer checks confirmed).

Code: Select all

<div class="form-group">
					<label for="name" class="control-label col-lg-3">Name<span class="text-danger"><%%TRANSLATION(*)%%></span></label>
					<div class="col-lg-4">
						<input tabindex="1" maxlength="40" type="text"  class="form-control" name="name" id="name"   value="<%%VALUE(name)%%>" required readonly="readonly" />
					</div>
				</div>
I left the required qualifier in there to insure it is filled in. (Would mess things up if missing).

Next I changed the header file a tiny bit. Remember this is cheap and dirty so it is not perfect but works fine. Refinements will come when I have rest of system done and can get down to the fine points of proper design. But, again, it works.

To the header.php file I added in:

Code: Select all

<body onLoad="ajaxFunction();">
Just look for the body tag and add in your function you want to run after the word body.

This will then run my function after the page is loaded. I then duplicated and renamed this file headerinci.php. The inci just refers to my table incident report. The next step is my php file to get the info I want. I want to pull the first and last names from the table which contains this info. (Users are forced to fill this table in with their info before they get more access.)

(Yes I can do a bunch of this in the hook file but doing it this way for now was a lot faster as I am under the gun time wise)

Here is my php file to get the data from the table with the user first and last name. (Again this is cheap and dirty code but it works and most should be able to follow the logic I hope)

Code: Select all

<?php

$currDir=dirname(__FILE__);
	include("$currDir/lib.php");
	$mid = getLoggedMemberID();
	

mysql_connect("[b]localhost[/b]", "[b]user[/b]", "[b]pass[/b]") or die(mysql_error()); 
 mysql_select_db("[b]dbname[/b]") or die(mysql_error());
 
$result1 = mysql_query("SELECT * FROM membership_userrecords WHERE memberID = '$mid'") or die(mysql_error());
while($row1 = mysql_fetch_array($result1)){
$p1 = $row1["pkValue"];
}

$result2 = mysql_query("SELECT * FROM employee_info WHERE id = '$p1'") or die(mysql_error());
while($row2 = mysql_fetch_array($result2)){
$f1 = $row2["first_name"];
$f2 = $row2["last_name"];
$f3 = ($f1 . " " . $f2);
echo $f3;
}

?>
Okay here is how the above works. Again this is not elegant but it does work. Since the entire system is in a closed environment, at this point, I can be a tiny bit lax on security.

First part is to get the logged members id
Next is the access to the database - this is the mysql_connect
Next is the first query which gets the only record and its pkvalue. (There can only be one record. The app does not allow a user to have more than one member record. Makes sense, why would a user need two records with their member info. If changes are needed just change the first one)
Next the second query uses the pkvalue to get the member record and extract their first name and last name from the record then joins them together.

Next I need to make sure this table view file open the correct header file. So find the line in the file yourtablename_view.php that looks like this:

Code: Select all

if(!$headerCode){
		include_once("$currDir/headerinci.php"); //changes made here
	}else{
		ob_start(); include_once("$currDir/header.php"); $dHeader=ob_get_contents(); ob_end_clean();
		echo str_replace('<%%HEADER%%>', $dHeader, $headerCode);
	}
In the above you can see where I added inci after header and before .php
This will insure the correct header file is loaded. (Yes I know I can do this with hooks but at this point I needed to do it this way for cheap and dirty reasons).

Then see my previous post in this thread and also add in the code function ajaxFunction.... as described in that post.

I know this is probably clear as mud but I am doing it between taking breaks from doing the work for my client. Hope this works for someone. My app is up and running and starting tomorrow it is going live. All of this works and has passed the necessary tests today by the client. Refinements and making pretty start tomorrow.

Enjoy (and I hope it is able to be understood but if not....)

Any questions just ask.

Alan
Calgary, Alberta, Canada - Using Appgini 5.50 -

Post Reply