Forums

Add data to users table

otinane 21 Sep, 2011
Hello,

I am new to Chronoforms and i wanted to ask how can i do this:

I have made a field to users table named Alert(text field) and i would like there to store data when users fill a chrono form with checkboxes.

Example:

A user with name Demo logs in to site and he chooses to fill the form that has 2 checkboxes.
[]Test
[]Another Test
After the sumbit the field Alert in users table under user with name Demo must contain the checkboxes data as
Test,Another Test
GreyHead 21 Sep, 2011
Hi otihane,

I strongly recommend that you do *not* hack the core Joomla! tables as this can damage your site and cause problems with upgrades. Instead you can either add the data to the User Params column in the user table or use a second table and link it to the User ID. I have a help document that you can buy here explaining how to do this.

The ChronoForms DB Save will let you write date to any table including jos_users; with a CheckBox group you need to make sure that you have a Handle Arrays acion (in CFv4) or set 'Let ChronoForms Handle arrays' to Yes (in CFv3).

Bob
otinane 21 Sep, 2011
Really appreciate your help

The thing is that i already use extra fields on users table and i strongly need to have the data of Alert field inside users table.

How can i update this data of Alert field using Chrono forms?

Thanks in advance
GreyHead 21 Sep, 2011
Hi otinane,

The ChronoForms DB Save will let you write date to any table including jos_users; with a CheckBox group you need to make sure that you have a Handle Arrays acion (in CFv4) or set 'Let ChronoForms Handle arrays' to Yes (in CFv3).



Bob
otinane 21 Sep, 2011
I do have it as "YES" on ChronoForms handle my posted arrays option and there is no problem on that it does put the checkboxes data seperated with a comma in the field i want.

The problem is that it creates a new entry with all fields blank and the field Alert as the checkboxes say.What i want is to UPDATE an already existing entry(a user) and add on the field Alert the checkboxes data.

Thanks again for your replies
GreyHead 21 Sep, 2011
Hi otinane,

You either need to pre-load the form with the existing values; or to get the existing values from the jos_user table and add them to the new form results before they are re-saved.

Bob
otinane 21 Sep, 2011
And how can i do that ? I know i am a pain in the #%! but i am new to this one. Sorry and thanks again.
GreyHead 21 Sep, 2011
Hi otinane,

Do which?

Bob
otinane 21 Sep, 2011

You either need to pre-load the form with the existing values; or to get the existing values from the jos_user table and add them to the new form results before they are re-saved.



Do this🙂
GreyHead 21 Sep, 2011
Hi otinane,

Yes - but that says either (a) or (b) - which is it that you want to do?

Bob
otinane 21 Sep, 2011
I suppose (b) so that the user wont see any info of him in the form apart from the checkboxes ?
GreyHead 21 Sep, 2011
Hi otinane,

Please try something like this in a Custom Code action in the On Submit event.
<?php
if ( $form->data['Alert'] ) {
	$new_alerts = $form->data['Alert'];
	$user =& JFactory::getUser();
	$db =& JFactory::getDBO();
	$query = "
	SELECT `Alert`
	  FROM `#__users`
	  WHERE `id` = '{$user->id}' ;
	";
	$db->setQuery($query);
	$alerts = $db->loadResult();
	$alerts = explode(',', $alerts);
	$alerts = array_merge($alerts, $new_alerts);
	$form->data['Alert'] = implode(',', $alerts);
}
?>

This is CFv4 code, it's not tested and will need debugging. Also I've had to guess at the formats, field names and column names so you need to check those carefully.

Bob
otinane 21 Sep, 2011
1) This code should go in the Core/View Form Settings -> Form tag attachment: something like onSubmit()?

2) The $form->data['Alert'] i suppose takes the value from checkboxes right ? if my checkboxes have name="Alert[]" i should use that code?

3) Really really thanks for once more :mrgreen:
GreyHead 22 Sep, 2011
Hi otinane,

1) No, you don't need anything in the Form Tag Attachment box.

2) The [] are just used in the Form HTML to set up an array name - one that will return several results in an array. You don't' need the [] in the code I posted.

Bob
otinane 22 Sep, 2011
My setup till now:

The view of the form:
[attachment=2]4.jpg[/attachment]

The form html code:
[attachment=1]5.jpg[/attachment]

The Events setup:
[attachment=0]1.jpg[/attachment]

The OnSubmit code that u told me:



The DB Save code:



What happens when i submit the form:



plus:
1) in the userstest table the entry is a new entry not an update of the logged in users entry
2) the field Alert of the user is NULL,nothing is written there even in the new entry
3) the userstest table contains the fields id for the user id,Alert to contain the form data seperated by comma (Market,Gaming,e.t.c)
The other fields i dont think we need them for the code/form

Any ideas of what is wrong ?
GreyHead 22 Sep, 2011
Hi otinane,

I missed a } at the end. I've updated my post.

Bob
otinane 22 Sep, 2011
I still get errors:

Data Array:
Array
(
    [Alert] => Array
        (
            [0] => choice Aerospace
            [1] => choice Gaming
        )

    [input_submit_1] => Submit
    [0a5db2f09920e71a9e978c610d5aadf5] => 1
    [option] => com_chronoforms
    [chronoform] => Alert
    [event] => submit
    [Itemid] => 
)


Warning: array_merge() [function.array-merge]: Argument #2 is not an array in /home/****/public_html/****/administrator/components/com_chronoforms/form_actions/db_save/db_save.php on line 81

Warning: implode() [function.implode]: Invalid arguments passed in /home/****/public_html/****/libraries/joomla/database/database/mysqli.php on line 557
Debug Data
Tableuserstest::bind failed. Invalid from argument

EDIT: And again it adds a new entry with new id,whereas i want to update an already existing entry of a user
GreyHead 22 Sep, 2011
Hi otinane,

Then you get to start debugging the code so that it works and does what you want.

Bob
otinane 22 Sep, 2011
Any suggestions for the debug ? Where to look at for example?
GreyHead 22 Sep, 2011
Hi otinane,

Start with the error messages. Add echo statements to show you what is actually happening. Use the PHP manual to check if the syntax is correct.

Bob
otinane 22 Sep, 2011
This is the code so far that is working:

<?php
     
   if ( $form->data['Alert'] ) {

   $new_alerts = $form->data['Alert'];
   JFactory::getApplication()->enqueueMessage( $new_alerts );


   $user =& JFactory::getUser();
   $userid = $user->id ;
   JFactory::getApplication()->enqueueMessage( $userid );

  
   $db =& JFactory::getDBO();
   $query = "
   SELECT Alert
     FROM #__userstest
     WHERE id = '$userid' ;
   ";
   $db->setQuery($query);
   $alerts = $db->loadResult();
   JFactory::getApplication()->enqueueMessage( $alerts );

 
}
 
?> 


After running this code i get

Enque message : Gaming,Market (these are the 2 checkboxes that i choose)
Enque message : 65 (this is the id of the logged in user that fills the form)
Enque message : Otinane (this is what exists already in that user Alert field)


Data Array: 
Array
(
    [Alert] => Gaming,Market
    [input_submit_1] => Submit
    [9e0d38e09ca1b8f9ebd7dcb18a385368] => 1
    [option] => com_chronoforms
    [chronoform] => Alert
    [event] => submit
    [Itemid] => 
    [Alert[]] => Array
        (
            [cf_uid] => 99d55040cb030e4e21fa648b37fb8bd0
            [cf_created] => 2011-09-22 19:28:38
            [cf_ipaddress] => 79.130.105.64
            [cf_user_id] => 65
            [Alert] => Gaming,Market
            [input_submit_1] => Submit
            [9e0d38e09ca1b8f9ebd7dcb18a385368] => 1
            [option] => com_chronoforms
            [chronoform] => Alert
            [event] => submit
            [Itemid] => 
            [id] => 6823
        )

    [alert[]_id] => 6823
)


if i add the following line in the code
$alerts = array_merge($alerts, $new_alerts);


i get those 2 messages:

Warning: array_merge() [function.array-merge]: Argument #1 is not an array in /home/***/public_html/***/administrator/components/com_chronoforms/form_actions/custom_code/custom_code.php(18) : eval()'d code on line 24

Warning: array_merge() [function.array-merge]: Argument #2 is not an array in /home/***/public_html/***/administrator/components/com_chronoforms/form_actions/custom_code/custom_code.php(18) : eval()'d code on line 24


Why those errors ?
otinane 23 Sep, 2011
Ok i updated my code to this:

<?php
     
   if ( $form->data['Alert'] ) {

   $new_alerts = $form->data['Alert'];
   JFactory::getApplication()->enqueueMessage( $new_alerts );


   $user =& JFactory::getUser();
   $userid = $user->id ;
   JFactory::getApplication()->enqueueMessage( $userid );

  
   $db =& JFactory::getDBO();
   $query = "
   SELECT Alert
     FROM #__userstest
     WHERE id = '$userid' ;
   ";
   $db->setQuery($query);
   $alerts = $db->loadResult();
   JFactory::getApplication()->enqueueMessage( $alerts );

   $alerts = explode(',', $alerts);
   print_r($alerts);
    
   $alerts = array_merge((array)$alerts, (array)$new_alerts);
   print_r($alerts);

   $form->data['Alert'] = implode(',', $alerts);

 
}
 
?> 



What i get as output is:


Aerospace,Gaming,Market //The 3 enque messages
65
Otinane

Array ( [0] => Otinane ) // This is the print_r($alerts) message from explode
Array ( [0] => Otinane [1] => Aerospace,Gaming,Market ) // This is the print_r($alerts) message from the merge of arrays
Array // This is the new data stored in userstest table
(
    [Alert] => Otinane,Aerospace,Gaming,Market
    [input_submit_1] => Submit
    [12c174c52941cbdb4dba5f1af2badd3c] => 1
    [option] => com_chronoforms
    [chronoform] => Alert
    [event] => submit
    [Itemid] => 
    [Alert[]] => Array
        (
            [cf_uid] => 25d425dfe1eeadcafdb002a8948c67ff
            [cf_created] => 2011-09-23 11:06:04
            [cf_ipaddress] => 79.130.109.203
            [cf_user_id] => 65
            [Alert] => Otinane,Aerospace,Gaming,Market
            [input_submit_1] => Submit
            [12c174c52941cbdb4dba5f1af2badd3c] => 1
            [option] => com_chronoforms
            [chronoform] => Alert
            [event] => submit
            [Itemid] => 
            [id] => 6833
        )

    [alert[]_id] => 6833
)


As u can see above now the code works almost as it should,joining the logged in users Alert field with the data that we provide in the form.One big problem though...
The code still generates a new entry in userstest table under new id,whereas what i want is update the already existing entry of the logged in user under the field Alert.
Any ideas?

P.S. Just to provide some future help,the problem with the errors of the previous post i solved it by using array(),array() in each argument at array_merge arguements ((array)$alerts,(array)$new_alerts) due to PHP 5
otinane 26 Sep, 2011
Any ideas of how can i get update of user data and not new entry data with above code?
GreyHead 26 Sep, 2011
Hi otinane,

You can usually turn off PHP warnings and notices by setting Error Reporting to System Default or None in the site Global Configuration.

To avoid creating a new record you need to make sure that the current record id is included in the dataset to be saved. Usually this can be doen by adding a hidden input to the form, or by adding the value after submission.

Bob

Note: In general it's not a good idea to save data to the #__users table. Use the Joomla! Users methods instead to avoid possible damage to the site.
otinane 27 Sep, 2011
if u could provide some help i would be gratefull
GreyHead 27 Sep, 2011
Hi otinane,

I have told you what you need to do. I still think that adding columns to the jos_users table is a really bad idea.

Tell me what you have done, what isn't working and ask a specific question and I'll try to help.

Bob
otinane 27 Sep, 2011
The code that i use is this:

<?php
/**
* @version		
* @package		
* @author		erezavny@gmail.com
* @copyright	weba.co.il 2010. All rights reserved.
* @license		GNU/GPL, see LICENSE.php
*/

// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport( 'joomla.plugin.plugin' );

$mainframe->registerEvent( 'onAfterContentSave', 'plgContentNotification' );

function plgContentNotification(&$article, $isNew){

	$app =& JFactory::getApplication();
	$config = &JFactory::getConfig();
	// Only on front 
	if($app->getName()!='site'){
		return;
	}
	
	$plugin			= &JPluginHelper::getPlugin('content', 'plg_content_notification');
	$pluginParams   = new JParameter( $plugin->params );
	
	// Plugin Setting Validation
	if ($pluginParams->get('Notify_New',0)==0 && $isNew){
		return;
	}
	
	if ($pluginParams->get('Notify_Update',0)==0 && !$isNew){
		return;
	}
	
	
	
	// Language upload
	$lang = & JFactory::getLanguage();
	$lang->load('plg_content_notification', JPATH_ADMINISTRATOR);
	
	
	if ($isNew){
		$mail_subject = JText::_('New Mail Subject');
		$mail_body = JText::_('New Mail Subject').'<br>';
	}else{
		$mail_subject = JText::_('UPDATE MAIL SUBJECT');
		$mail_body = JText::_( 'UPDATE MAIL SUBJECT' ).'<br>';
		
	}
	
	$articleid = $article->id;
	
	$mail_body .=JText::_('Article Title').': '.addslashes($article->title)."<br>";
	$mail_body .=JText::_('Article Link').': '.JText::_('http://www.glimlag.gr/balkans/index.php?option=com_content&view=article&id=').$articleid."<br>";


	$catid = $article->catid;
	JFactory::getApplication()->enqueueMessage( $catid );
	
	
	switch($catid)
	{
	case 2:	
	case 3:
	case 4:
	case 5:
	case 6:
	case 7:
	case 8:
	case 9:
	$temp='Aerospace';
	break;
	
	case 218:
	$temp='Market';
	break;
	
	default:
	$temp='tadaafdgaxdgadsfsf';
	break;
	}
	
	$mail =& JFactory::getMailer();
	$mail->isHTML(true);
	
	
	$db		= & JFactory::getDBO();
	$query 	= "SELECT id, Email
		  		FROM #__userstest
			WHERE Alert LIKE '%$temp%' ";
	$db->setQuery($query);
	$users = $db->loadObjectList();
	
	foreach ($users as $user){
		$mail->addRecipient($user->Email);
	}
	
	$mail->setSubject( $mail_subject);
	$mail->setBody( $mail_body );
	
	$mail->Send();
	
	
	return;
	
	
} // EOF plgContentNotification	


What it does: Lookup at the users table under Alert field and see depending on the category id of the article that is created and send him a mail with the Title and link of the article.

If i change this code:

$db		= & JFactory::getDBO();
	$query 	= "SELECT id, Email
		  		FROM #__userstest
			WHERE Alert LIKE '%$temp%' ";
	$db->setQuery($query);
	$users = $db->loadObjectList();
	
	foreach ($users as $user){
		$mail->addRecipient($user->Email);
	}


to this:

$db		= & JFactory::getDBO();
	$query 	= "SELECT id, Email
		  		FROM #__test
			WHERE Alert LIKE '%$temp%' ";
	$db->setQuery($query);
	$users = $db->loadObjectList();
	
	foreach ($users as $user){
		$mail->addRecipient($user->Email);
	}



where test table is a table created by me (for testing purposes in the database) that has 3 fields,the Alert field, plus the Email field and id field that are foreign keys linked to the users table.This code is not working.
GreyHead 27 Sep, 2011
Hi otinane,

As far as I can see this has nothing to do with ChronoForms??

If you code isn't working then you need to debug it . . .

Bob
otinane 29 Sep, 2011

To avoid creating a new record you need to make sure that the current record id is included in the dataset to be saved



Sorry again for asking you all those questions,but i am new to all this code.

How can i include the current record id in the dataset that needs to be saved?How can i get the id of current record?

Again thanks in advance
GreyHead 29 Sep, 2011
Hi otinane,

It it's the same as the User ID then you can always get it from the Joomla! User object.
<?php
$user = Jfactory:;getUser();
$id = $user->id;
?>

Bob
otinane 29 Sep, 2011
I am a bit confused.
Lets say i get the user id.To make sure that it will be included in the dataset to be saved,i have to make it as Event while on Submit?And if yes ,while using the above custom code?
GreyHead 29 Sep, 2011
Hi otinane,

Sorry, I've no idea what code you are using where any more. I've probably looked at a hundred posts in between.

The code I posted will give you the value of the current User ID and can be used anywhere that PHP is allowed - most of the ChronoForms boxes.

Bob
This topic is locked and no more replies can be posted.