Forums

Custom PHP code in field Value

Kenjy-15 05 Dec, 2016
Hi everybody, I'm creating a new form to record the samples received in a laboratory. In this form, I need to generate an id (SampleID) with this style : 201612058.
2016 for the current year.
12 for the current month.
058 is the number of sample received in the laboratory during the current year.

I installed the Sourcerer extension to add custom PHP code.

Now, I want to generate automatically the SampleID in a disabled Text Box (for user information).
How can I do this ?
I have already tried to paste my custom PHP code in the field Value of my Text Box but it doesn't work...

Second question,
I want to add this ID (and others fields) in my database when I click on Submit button. DB Save is working on all fields except my custom code..

Thanks for your help !
GreyHead 05 Dec, 2016
Answer
Hi Kenjy-15,

First, you don't need the Sourcerer extension as CF supports PHP in most places.

You have a problem in using this kind of 'serial' ID in when the form loads. You can’t be sure at that point if the form will be submitted at all - or if there will be another form submitted after this was loaded and before it submits :-(

If you have to use a serial id then you should generate that after the form submits. (IMHO, it is easier to use unique random IDs).

You can generate the id after the form submits. When you save the record, CF will add the new record ID to the $form->data array - you could use that to look up the serial number of the previous record, then increment that:
<?php
$db = \JFactory::getDBO();
$cf_id = $form->data['cf_id'] - 1;
$query = "
    SELECT `serial_no`
        FROM `#__some_table`
        WHERE `cf_id` = '{$cf_id}' ;
";
$db->setQuery($query);
$serial  = $db->loadResult();
$serial = $serial + 1;
$form->data['serial'] = $serial;
$form->data['serial_string'] = date('Y-m-').$serial;
// add code here to update the record with the new values.
?>
This assumes that you have both 'serial' and 'serial_string' as columns in your table and that the primary key column is called cf_id.

Bob
Kenjy-15 05 Dec, 2016
Thanks you GreyHead !
I will increment my serial number and and update it after submitting the form !

Thanks again for your quick answer !

Kenjy-15
GreyHead 05 Dec, 2016
Hi Kenjy-15,

PS I forgot to say earlier that to make a value show but not be editable you need to set the input element to 'readonly' - if you set it to disabled then it is not submitted at all.

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