Jump to content
Juergen

[SOLVED] Problem saving values from dynamic created inputfields in the database

Recommended Posts

Hello @ all,

I am creating a new inputfield/fieldtype to store opening hours, but I am struggeling to save values from multiple dynamic created inputfields in 1 column of the database.

Scenario:

The user can enter one or more opening times per day in a UI.

Fe:

  • Monday open from 08:00 to 12:00 and from 14:00 to 17:00
  • Tuesday open from 08:00 to 12:00 and from 14:00 to 19:00 and so on

skizze.jpg.02d04c57464b88d20cd79a599fa064fd.jpg

Via a little JavaScript you can add as much opening times as you need per day - the additional inputfield will be created dynamically.

After form submission all the values are in the POST array -> this works (see example below):

ProcessWire\WireInputData Object
(
	[openinghours_mo-0-start] => 09:00
    [openinghours_mo-0-finish] => 13:00
    [openinghours_mo-1-start] => 14:00
    [openinghours_mo-1-finish] => 18:00
    [openinghours_mo-2-start] => 21:00
    [openinghours_mo-2-finish] => 23:00
    [openinghours_tu-0-start] => 09:00
    [openinghours_tu-0-finish] => 13:00
    [openinghours_tu-1-start] => 14:00
    [openinghours_tu-1-finish] => 18:00
    [openinghours_we-0-start] => 09:00
    [openinghours_we-0-finish] => 13:00
    [openinghours_we-1-start] => 14:00
    [openinghours_we-1-finish] => 18:00
    [openinghours_th-0-start] => 09:00
    [openinghours_th-0-finish] => 13:00
    [openinghours_th-1-start] => 14:00
    [openinghours_th-1-finish] => 18:00
    [openinghours_fr-0-start] => 09:00
    [openinghours_fr-0-finish] => 13:00
    [openinghours_fr-1-start] => 14:00
    [openinghours_fr-1-finish] => 18:00
    [openinghours_sa-0-start] => 
    [openinghours_sa-0-finish] => 
    [openinghours_so-0-start] => 
    [openinghours_so-0-finish] => 
)

The property name is always the name attribute of the field 😉 . If the property is empty means closed on that day.

Now I need to combine all those values into 1 array (or json array) and store it in the database in 1 column called 'hours' in my case (see screenshot below):

Screenshot(4).png.03b4e61c044030eaa905530e1e80f80b.png

In my ___processInput(WireInputData $input) method I have tried to make it work like this:

public function ___processInput(WireInputData $input): self
    {

        $name = $this->attr('name');
        $value = $this->attr('value');

        //input object includes always every input on the page, so lets filter out only inputs from this field
        //we need to do this, because the number of values is variable - so extract only values that starts with $name.'_'
        $nameAttributes = [];
        foreach($input as $key=>$value){
          if(substr($key, 0, strlen($name.'_')) === $name.'_'){
            $nameAttributes[$key] = $value;
          }
        }

        // loop through all inputfields of this fieldtype
        $time_values = [];
        foreach($nameAttributes as $nameAttr => $value) {
            $time_values[$nameAttr] = $value;
          }
        }

        //save it in the database
        $input->set('hours', serialize($time_values));
        return $this;

    }

The only important part of this code is the last part with the serialize function.

After saving it will create a record in the database, but the value is always NULL (default value) (see below).

Screenshot(5).png.dbc818090e35e9be9669df84f33ca8a1.png

Checking $time_values returns all the values, but printing out "$this" shows me that the property "hours" inside the Openinghours object is empty (see below) - so the mistake must be there, but I dont know where?!?!?!?

[title] => Home
                            [openinghours] => ProcessWire\OpeningHours Object
                                (
                                    [data] => Array
                                        (
                                            [hours] => 
                                        )

                                )

If I check the sleepValue() method or the sanitizeValue() - they are also empty. So it seems that the values will not reach these methods. I havent found a clear documentation of whats going on behind the saving process of an inputfield.

As far as I know the saving process starts with the form submission. The values are in the POST array and will be processed by the processInput() method. Before they will be saved in the database they will be sanitized by the sanitizeValue() mehtod and afterwards they will be prepared for storage in the sleepValue() method.  The last step is the storage itself.

Has someone an idea what is missing by storing values from multiple fields into 1 database column or has someone a working example of such a scenario on github to help me out.

A clear explanation of the storage process will be also helpful.

Thanks and best regards

Share this post


Link to post
Share on other sites

OK, I am 1 step forward :-)

Adding

$this->value['hours'] = $time_values;

to the processInput() method adds the values to the object

Here is the complete code of this method:

public function ___processInput(WireInputData $input): self
    {

        $name = $this->attr('name');
        $value = $this->attr('value');

        //input object includes always every input on the page, so lets filter out only inputs from this field
        //we need to do this, because the number of values is variable - so extract only values that starts with $name.'_'
        $nameAttributes = [];
        foreach($input as $key=>$value){
          if(substr($key, 0, strlen($name.'_')) === $name.'_'){
            $nameAttributes[$key] = $value;
          }
        }



        // loop through all inputfields and set the value (if changed or not) back
        $time_values = [];
        foreach($nameAttributes as $nameAttr => $value) {
            $time_values[$nameAttr] = $value;
        }

        //add it to the object
        $this->value['hours'] = $time_values;

        return $this;

    }

Now the values are also reachable in sleepValue() method and the sanitizeValue() method.

ProcessWire\OpeningHours Object
(
    [data] => Array
        (
            [hours] => Array
                (
                    [openinghours_mo-0-start] => 09:00
                    [openinghours_mo-0-finish] => 13:00
                    [openinghours_mo-1-start] => 14:00
                    [openinghours_mo-1-finish] => 18:00
                    [openinghours_mo-2-start] => 21:00
                    [openinghours_mo-2-finish] => 23:00
                    [openinghours_tu-0-start] => 09:00
                    [openinghours_tu-0-finish] => 13:00
                    [openinghours_tu-1-start] => 14:00
                    [openinghours_tu-1-finish] => 18:00
                    [openinghours_we-0-start] => 09:00
                    [openinghours_we-0-finish] => 13:00
                    [openinghours_we-1-start] => 14:00
                    [openinghours_we-1-finish] => 18:00
                    [openinghours_th-0-start] => 09:00
                    [openinghours_th-0-finish] => 13:00
                    [openinghours_th-1-start] => 14:00
                    [openinghours_th-1-finish] => 18:00
                    [openinghours_fr-0-start] => 09:00
                    [openinghours_fr-0-finish] => 13:00
                    [openinghours_fr-1-start] => 14:00
                    [openinghours_fr-1-finish] => 18:00
                    [openinghours_sa-0-start] => 
                    [openinghours_sa-0-finish] => 
                    [openinghours_so-0-start] => 
                    [openinghours_so-0-finish] => 
                    [openinghours_ho-0-start] => 
                    [openinghours_ho-0-finish] => 
                )

        )

)

Nevertheless the value in the DB is NULL :-( 

Share this post


Link to post
Share on other sites

OK, I figured it out.

I transformed the values of the inputfields inside the sleepValue function to a json array and now the values will be stored in the database.

public function sleepValue(Page $page, Field $field, $value)
    {
      // throw error if value is not of the right type
      if (!$value instanceof OpeningHours) {
          throw new \Exception($this->_('Expecting an instance of OpeningHours'));
      }
      $content = json_encode($value->data['hours']);
      $sleepValue = ['hours' => $content];
      return $sleepValue;
    }

So the responsible lines are

$content = json_encode($value->data['hours']);
$sleepValue = ['hours' => $content];

 

Screenshot(6).png.e61b8d90f245d99774ae43da04876465.png

The problem of the storage was that the column 'hours' was not defined in the sleepValue method. This was the important part because without it the system doesnt know where to store the value.

 

  • Like 2

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By jploch
      Hey folks,
      Iam working on a module that extends InputfieldPageTable. I use PageTableExtended as a starting point and all went well so far, except I can't access my config values outside of the module file. The config values allways return the defaults, and not the values in the pw field settings. 

      Here is the code that sets the defaults inside my inputfield module file:
      public function init() { parent::init(); // defaults $this->set('gridMaxWidth', '1600'); $this->set('gridColumns', '12'); } Here is how I add the config field:
      public function ___getConfigInputfields() { $inputfields = parent::___getConfigInputfields(); $fieldsetGrid = $this->modules->get('InputfieldFieldset'); $fieldsetGrid->label = $this->_('Default Grid Settings'); $f = $this->wire('modules')->get('InputfieldText'); $f->attr('name', 'gridMaxWidth'); $f->attr('value', $this->gridMaxWidth); $f->label = $this->_('Container max width'); $f->description = $this->_('Grid container max width in px'); // page name format description $f->notes = $this->_('default is 1600'); // page name format notes $fieldsetGrid->append($f); $inputfields->append($fieldsetGrid); return $inputfields; } Accessing the values outside my module files like this (this gives me the default: 1600, even if I insert another value in the backend field settings):
      $default = $this->wire('modules')->get('InputfieldPageGrid'); $default->gridMaxWidth; Any Ideas?
    • By xportde
      How does one enable executables to be uploaded to the File field? Just adding the file extension to the accepted extensions does not seem to work.

      screenshot attached (ignore the label 'video')

    • By MoritzLost
      This module allows you to integrate hCaptcha bot / spam protection into ProcessWire forms. hCaptcha is a great alternative to Google ReCaptcha, especially if you are in the EU and need to comply with privacy regulations.

      The development of this module is sponsored by schwarzdesign.
      The module is built as an Inputfield, allowing you to integrate it into any ProcessWire form you want. It's primarily intended for frontend forms and can be added to Form Builder forms for automatic spam protection. There's a step-by-step guide for adding the hCaptcha widget to Form Builder forms in the README, as well as instructions for API usage.
      Features
      Inputfield that displays an hCaptcha widget in ProcessWire forms. The inputfield verifies the hCaptcha response upon submission, and adds a field error if it is invalid. All hCaptcha configuration options for the widget (theme, display size etc) can be changed through the inputfield configuration, as well as programmatically. hCaptcha script options can be changed through a hook. Error messages can be translated through ProcessWire's site translations. hCaptcha secret keys and site-keys can be set for each individual inputfield or globally in your config.php. Error codes and failures are logged to help you find configuration errors. Please check the README for setup instructions.
      Links
      Github Repository and documentation InputfieldHCaptcha in the module directory Screenshots (configuration)

      Screenshots (hCaptcha widget)

       
       

       
    • By Juergen
      Hello @ all,
      I have created an inputfield with a configuration field in the backend where you can set a time format for every language (see screenshot below).

      As you can see both language values (default and German) have the default value(%R), but I have set different values, which were correctly stored in the DB (see screenshot below):

      As you can see the values are '%R' and '%r'.
      I have created the configuration inputfield like this:
      /** @var InputfieldText $f */ $languages = $this->wire('languages'); $f = $this->wire('modules')->get('InputfieldText'); $f->attr('name+id', 'timeformat'); $f->label = $this->_('Timeformat on frontend'); $f->initValue = '%R';//default value $f->attr('value', $this->timeformat ? $this->timeformat : '%R'); $this->message($this->get('timesformat')); if($languages) { $f->useLanguages = true; foreach($languages as $language) { if($language->isDefault()) continue; $f->set("value$language", (string) $this->get("timeformat$language->id")); } } $f->inputType = 'text'; $f->description = $this->_('Please enter the time format that the times should appear on the frontend in strftime format.'); $f->notes = sprintf($this->_('For example shows the time as 08:00, as 08:00 AM. You can find more examples at %s.'), '<a href="https://www.php.net/manual/de/function.strftime.php">https://www.php.net/manual/de/function.strftime.php</a>'); $f->columnWidth = 100; The important part here is:
      if($languages) { $f->useLanguages = true; foreach($languages as $language) { if($language->isDefault()) continue; $f->set("value$language", (string) $this->get("timeformat$language->id")); } } I have borrowed the code from the DateTimeInputfield (https://github.com/processwire/processwire/blob/master/wire/modules/Inputfield/InputfieldDatetime/InputfieldDatetime.module), but the field values will be always populated with the default value ('%R').
      Are I am missing something? Does anyone has experience with multilanguage fields and could help me out?
      Thanks in advance.
    • By Juergen
      Hello @ all!
      I want to share a simple fieldtype and inputfield to store address data with you.
      I have created this inputfield for learning purposes and it has no fancy functionality. It is simply for storing address data such as street, number, postalcode and so on in one table. As an addition you can store latitude and longitude too, so you can use them in maps.
      Here is a screenshot of what it looks like:

      You can select which fields are mandatory and you can choose if the inputs for longitude and latitude should be displayed. These settings can be configured in the field configuration.
      If you find this inputfield useful you can download it at https://github.com/juergenweb/FieldtypeSimpleAddress
      There you will find a detailed explanation. If you have an idea of an usefull feature that can be added or you have detected a bug, please report it in my github account.
       
×
×
  • Create New...