Jump to content

MarkE

Members
  • Posts

    1,082
  • Joined

  • Last visited

  • Days Won

    12

Everything posted by MarkE

  1. The hack in the quoted post is quite simple @Krlos - you may wish to try it and see if it fixes your problem. If not, you can revert. Or you could just try \ProcessWire\_(“….”)
  2. Github issue opened at https://github.com/processwire/processwire-issues/issues/1502 Suggested fix is to amend the regexes in $sanitizer->float() to not remove 'E-', 'E+', 'e-' or 'e+', but I have (yet?) to devise a suitable regex. If anyone is a regex whizz then please save me some head-scratching ? EDIT: I have also suggested, in the GIthub, a simple fix to deal with the internally-generated scientific notation that causes the InputfieldFloat problem. That's what I'm using for now, otherwise I consider InputfieldFloat is unsafe for live use! (I appreciate that may sound a bit dramatic, but I cannot risk major calculation errors).
  3. Will do @Jan Romero. I'm pretty sure that the problem is with $sanitizer->float() since hacking that to just return (float)$value fixes the problem with float fields.
  4. This might possibly be connected with an issue that I raised here https://github.com/ryancramerdesign/ProcessHannaCode/issues/26 and here but I haven’t received any response
  5. If I have a float or double field in the Admin with a value such as -0.00001253 then saving initially shows this as -1.253E-5, which is fine, but saving again changes it to -1.2535 (v3.0.184 and 3.0.190) In my FieldtypeMeasurement module I have fixed this (in a not yet released version) by using a text field and using (float)$value in the wakeupValue rather than $sanitizer because $sanitizer->float($value) returns -1.2535 from -1.253E-5. Is this a bug or is there something subtle that I don't understand here? It seems to me that InputfieldFloat may be using $sanitizer->float() which does not convert the scientific notation.
  6. For some reason, in the new site I am building, every time I use the front-end editor on a field, I have to save the changes twice - the first time just reloads the module with the previous value. I've not come across this before. I disabled hooks and auto-save but it still happens. Any ideas?
  7. https://processwire.com/modules/inputfield-runtime-only/ ?
  8. Added the inputfield renderValue() method, wich may be required if the rendered output when the field is locked. (Otherwise, for example in my FieldtypeMeasurement module, a locked field just displays the class name).
  9. Page (Autocomplete Single) works very nicely. Thanks @Robin S. Just one thought - is it possible to add 'selectOnce' to the existing hints under the settings box - no worries if not, just "a nice to have".
  10. Import/Export has a number of problems and fails to deal with some field types properly. Not wishing to detract from RockMigrations, which is excellent, but there is also my module ProcessDbMigrate. It is different in concept in that it is UI-based rather than code-based. It does handle 'uninstallation' of migrations and also database comparisons, but there are some features of RockMigrations that it does not have. In it I used some code from Import/Export but ditched or fixed quite a bit.
  11. Sorry @Robin S- it was late at night and the error only happened after I installed ConnectPageFields. On closer inspection this morning, it seems that the error might have been caused by something else. Will report back. EDIT: The problem seems to be with Repeaters, not ConnectPageFields. Not pursued this further as my solution was to use hidden visibility (which does not cause errors) together with another excellent little module: FieldtypeRuntimeOnly to display the hidden field in a non-editable way, with the link back ?
  12. This is a real go-to module - I have used on almost every site! Today maybe I was trying to be a bit too clever and have one of the fields locked (visibility: Open when populated + Closed when blank + Locked (not editable)). I just want the back-link to be viewable, not editable. However, this threw up a fatal error: Too few arguments to function ProcessWire\RepeaterPageArray::__construct(), 0 passed in M:\laragon\www\Cider\wire\core\WireData.php on line 438 and exactly 2 expected search► Is there any way of doing this? I guess I can restrict access for certain user types - is that the only way?
  13. Thanks muchly @BitPoet! The first was rather obvious - should have spotted that! The second was more subtle. Inspecting the php.ini from the laragon panel, it looked ok. Opened it directly in an editor and the extensions clearly weren't enabled. Odd, but all working now, thanks.
  14. Since it looked like others have successfully upgraded to PHP 8, I decided to give it a try. I use Laragon on the dev machine so started with that. Succesfully added PHP 8.0 and got Apache running OK. Tried two sites which noth returned similar fatal error messages: Site 1 Fatal error: Uncaught Error: Undefined constant "ProcessWire\HTTP_HOST" in M:\laragon\www\processwire\site-ncog\config.php:191 Stack trace: #0 M:\laragon\www\processwire\wire\core\ProcessWire.php(1246): require() #1 M:\laragon\www\processwire\index.php(33): ProcessWire\ProcessWire::buildConfig('M:/laragon/www/...') #2 {main} thrown in M:\laragon\www\processwire\site-ncog\config.php on line 191 Site 2 Breaking news… Fatal Error: Uncaught Error: Undefined constant PDO::MYSQL_ATTR_INIT_COMMAND in M:\laragon\www\BawdHall\wire\core\WireDatabasePDO.php:240 #0 M:\laragon\www\BawdHall\wire\core\ProcessWire.php(514): WireDatabasePDO::getInstance(Object(Config)) #1 M:\laragon\www\BawdHall\wire\core\ProcessWire.php(313): ProcessWire->load(Object(Config)) #2 M:\laragon\www\BawdHall\index.php(52): ProcessWire->__construct(Object(Config)) #3 {main} thrown (line 240 of M:\laragon\www\BawdHall\wire\core\WireDatabasePDO.php) Reverted to PHP 7.2 and all is fine. Both sites are on PW 3.0.184 and are in (separate) multi-site installations. Any suggestions? Thanks.
  15. New version 0.0.7 at https://github.com/MetaTunes/FieldtypeMeasurement This has lots of improvements, including permitting different details in different template contexts of the same field and a much-extended API So, for example, complex, dimensionally-analysed chains can be called such as in the following (illustrative, albeit rather artificial) script (execute in Tracy console): $m = $modules->get('FieldtypeMeasurement'); $speed = $m->measurement('Speed', 'furlong per fortnight', 1000); $time = $m->measurement('Time', 'hour', 3); $length = $speed->multiplyBy($time); $length2 = $m->measurement('Length', 'yard', 2); $area = $length2->power(2); $length3 = $m->measurement(); $length3->productOf($speed, $time); $speed2 = $m->measurement('Speed', 'mile per hour', 1); $speed3 = $m->measurement('Speed')->sumOf($speed2, $speed); $speed4 = $m->measurement(); $speed4 = $speed2->subtract($speed); $multi = $m->measurement('Length', 'yard') ->convertFrom( $area->add( $length2->subtract( $speed4->multiplyBy($time) ) ->power(2) )->divideBy($length3) ); d($multi); Result is 'magnitude' => 5590.1092160249345 'quantity' => 'Length' 'unit' => 'yard' 'baseUnit' => 'metre' 'dimension' => MetaTunes\MeasurementClasses\Dimension #814 'baseMagnitude' => 5111.5958671332 'shortLabel' => 'yd' where the dimension object has property dimensionArray ['length' => 1] This is still alpha, albeit with hopefully fewer bugs. I'll use it in a live app before progressing further.
  16. FWIW, my solution to this was to use a $config setting rather than a session var. Thanks for the help @adrian
  17. I have updated the post to reflect this and also added the following:
  18. Fieldtype modules Not really a tutorial, but a bunch of stuff I learnt in building a fieldtype module (FieldtypeMeasurement). That module is used as a starting point for many of the examples. Happy to take corrections and improvements ? Basics For a (full-featured) module, you actually need two module files: FieldtypeModuleName.module; and InputfieldModuleName.module The Fieldtype module defines the general settings for the fieldtype (how it appears in the setup->field page), together with how it interacts with the database, while the Inputfield module defines how the field appears when editing it in a page. In addition, for complex fields, you can define a class to hold your field values in an object. This allows you to provide custom methods for use in the API. Otherwise you can store field values as any existing type or ProcessWire object The chart below summarises the interactions of these elements and the subsequent sections describe the methods in more detail. Fieldtype Module The important methods are described below. __construct() Generally not much is required here (apart from parent::__construct();). If you have a php script with the field object then include it (require_once() ). SQL database interaction getDatabaseSchema(Field $field) This is essential. It states what data will be saved to the SQL database (via the sleepValue function - see below). An example is: public function getDatabaseSchema(Field $field) { $schema = parent::getDatabaseSchema($field); $schema['data'] = 'double NOT NULL'; // value in base units $schema['magnitude'] = 'varchar(64)'; // value in current units - needs to be text to store composite values $schema['unit'] = 'text NOT NULL'; $schema['quantity'] = 'text NOT NULL'; return $schema; } 'data' is required and is a primary key field which means that 'text' cannot be used, although varchar(64) is OK. Often (as here) it would be a numeric field of some type. Other items can be defined as required. ___sleepValue(Page $page, Field $field, $value) This determines how the ProcesssWire field object is mapped to the SQL schema. You need to return an array where the keys are the elements defined in the schema, e.g.: $sleepValue = array( 'data' => $data, 'magnitude' => $magnitude, 'unit' => $value->unit, 'quantity' => $value->quantity ); return $sleepValue; ___wakeupValue(Page $page, Field $field, $value) This is basically the inverse of sleepValue - mapping the array from the database into the field object. In the example below, the field object (Measurement) extends WireData. Properties in WireData objects can be stored in the 'data' property via 'get' and 'set' methods. getBlankValue() (see next section) performs the initial setting of these - config values for the field (see below) can be set, but otherwise the settings are just placeholders. Properties set to a WireData object can also be set or accessed directly, like $item->property or using array access like $item[$property] public function ___wakeupValue(Page $page, Field $field, $value) { // if for some reason we already get a valid value, then just return it if($value instanceof Measurement) return $value; // start a blank value to be populated $measurement = $this->getBlankValue($page, $field); // if we were given a blank value, then we've got nothing to do: just return a blank Measurement object if(empty($value) || !is_array($value)) return $measurement; // create new Measurement object $measurement->quantity = $value['quantity']; // ... custom processing ... $measurement->baseMagnitude = $value['data']; if($value['unit']) { $measurement->unit = $value['unit']; $units = $measurement->getUnits(); if(array_key_exists($value['unit'], $units) && isset($value['magnitude'])) { $measurement->magnitude = explode('|', $value['magnitude']); } else { $measurement->magnitude = $measurement->baseMagnitude; $measurement->unit = $measurement->units->base; $this->error('... error msg ...'); } } else { //... } if(!is_array($measurement->magnitude)) $measurement->magnitude = [$measurement->magnitude]; return $measurement; } getBlankValue(Page $page, Field $field) This should return an empty item of the appropriate type. For instance, if your field object is an array, just return array(); If the field type is an object then you will need to return a 'new ObjectClassName()'. Pre-fill any config values from the Fieldtype settings but leave blank those which are set in the Inputfield, In the above example, the field object data was set as follows: public function getBlankValue(Page $page, Field $field) { /* @var $field FieldtypeMeasurement */ $measurement = new Measurement($field->quantity, null, []); if ($field->quantity) $measurement->set('quantity', $field->quantity); $measurement->set('magnitude', []); $measurement->set('shortLabel', null); $measurement->set('plural', null); return $measurement; } If your object has configurable fields that can be modified according to context (as defined in getConfigAllowContext() - see below), then you will need to deal with this in getBlankValue too, e.g. : public function getBlankValue(Page $page, Field $field): Measurement { //NB Field details may differ between templates so we need to get the field in context $context = ($page && $page->id) ? $field->getContext($page->template) : $field; ... $measurement = new Measurement($context->quantity, null, []); ... return $measurement; } But note that this does not completely deal with the situation where the field is in repeater matrix items where the types might have different contexts - there you might need: public function getBlankValue(Page $page, Field $field): Measurement { //NB Field details may differ between templates so we need to get the field in context $context = ($page && $page->id) ? $field->getContext($page->template) : $field; ... // if($page instanceof RepeaterMatrixPage) { // This does not always work - see edit note if($page->template->pageClass == 'RepeaterMatrixPage') { if($page->getField($field->name)) { $context = $page->fieldgroup->getFieldContext($field, "matrix$page->repeater_matrix_type"); } } ... $measurement = new Measurement($context->quantity, null, []); ... return $measurement; } See this post for more details. Configuration ___getConfigInputfields(Field $field) This defines how the Details tab in the field setup page will look. The best thing to do here is to find a fieldtype module that is similar to the one you want if you are uncertain. Broadly the process is: define the config object - $inputfields = parent::___getConfigInputfields($field); for each config item, use the appropriate input field, e.g . $f = $this->modules->get("InputfieldSelect"); assign the relevant attributes. $f->name = $f_name; is important as it enables the item to be subsequently referred to as $field->f_name in, for example, getBlankValue(). append each item ($inputfields->append($f);) and return $inputfields; ___getConfigAllowContext(Field $field) This determines if the above input fields are allowed to have unique values per Fieldgroup assignment enabling the user to configure them independently per template in the admin, rather than sharing the same setting globally. E.g. public function ___getConfigAllowContext(Field $field) { $a = array('quantity', 'units', 'hide_quantity', 'show_update'); return array_merge(parent::___getConfigAllowContext($field), $a); } In this example the settings 'quantity', 'units', 'hide_quantity' and 'show_update' can be varied in different template contexts. Link with the Inputfield module This is done with getInputfield(Page $page, Field $field) e.g.: public function getInputfield(Page $page, Field $field) { $inputfield = $this->wire('modules')->get('InputfieldMeasurement'); $inputfield->setField($field); return $inputfield; } If you want to reference the current page in the inputfield, you will also need to include $inputfield->setPage($page); If your fieldtype is an object and you want full context flexibility including for different repeater matrix item types, then you may need to use this: public function getInputfield(Page $page, Field $field): Inputfield { $inputfield = $this->wire('modules')->get('InputfieldMeasurement'); if($page->template->pageClass == 'RepeaterMatrixPage') { if($page->getField($field->name)) { $field_in_context = $page->fieldgroup->getFieldContext($field, "matrix$page->repeater_matrix_type"); if($field_in_context) { $field = $field_in_context; } } } $inputfield->setField($field); $inputfield->setPage($page); return $inputfield; } Inputfield Module __construct() Generally not much is required here (apart from parent::__construct();). If you have a php script with the field object then include it (require_once() ). Configuration ___getConfigInputfields() This is pretty much exactly the same construction as the similar method in the Fieldtype class. The only difference is that these settings will appear in the 'input' tab of the fieldtype settings, rather than the 'details' tab. ___getConfigAllowContext(Field $field) This is the equivalent to the Fieldtype::getConfigAllowContext() method, but for the "Input" tab rather than the "Details" tab. Input and output The key methods for this module are to render it from the fieldtype and database and to process the user inputs. ___render() $field = $this->field will have the field config settings from the fieldtype module. $this->attr('value') will have the current values for the field. If there is no current values then, if using a field object, you will need to create a new object, e.g.: if($this->attr('value')) $value = $this->attr('value'); // Measurement object else { $value = new Measurement(); } You can then use $field and $value to display the inputfield (which might be a fieldset) as required using the appropriate pre-existing inputfield modules. (Again, find an existing module that is similar, if you are uncertain). renderValue() This is required where the field is locked (not editable) and therefore render() does not apply. Get the value with $value = $this->attr('value'); and then apply the required formatting, returning the output string. ___processInput(WireInputData $input) Here you take the inputs and update the field values. As in render(), set $value = $this->attr('value') ; and then modify $value for the inputs. For example, set $name = $this->attr('name'); and then assign the inputs thus: $input_names = array( 'magnitude' => "{$name}_magnitude", 'unit' => "{$name}_unit", 'quantity' => "{$name}_quantity", 'update' => "{$name}_update" ); You can then loop through the inputs and carry out the required updates. The example below is slightly convoluted but illustrates this: foreach($input_names as $key => $name) { if(isset($input->$name) && $value->$key != $input->$name) { if($key == 'magnitude') { $input->$name = trim($input->$name); if(!is_numeric($input->$name)) { $magnitude = explode('|', $input->$name); $magnitude = array_filter($magnitude, 'is_numeric'); $value->set($key, $magnitude); } else { $value->set($key, [$input->$name]); } } else { $value->set($key, $input->$name); } $this->trackChange('value'); } } When all is done, return $this; Custom classes As mentioned earlier, for complex field types it may be useful to set up custom classes to hold the data. Typically a custom class would extend WireData, which is ProcessWire's class designed for runtime data storage. It provides this primarily through the built-in get() and set() methods for getting and setting named properties to WireData objects. The most common example of a WireData object is Page, the type used for all pages in ProcessWire. Properties set to a WireData object can also be set or accessed directly, like $item->property or using array access like $item[$property]. If you foreach() a WireData object, the default behaviour is to iterate all of the properties/values present within it. Do not declare any such properties in your class (or declare properties with the same name) otherwise you will end up with two properties, one in the 'data' array and one outside it and endless confusion will result. It is advisable to put any such classes in your own namespace. In that case, you will need to include 'use' statements in your script - e.g. use ProcessWire\{FieldtypeMeasurement, WireData}; use function ProcessWire\{wire, __}; and also include use statements in your module scripts, e.g. use MetaTunes\MeasurementClasses\Measurement;
  19. Doh! Thanks for making me think @kongondo. Re-reading the docs, it is clear that there should be no difference between -> and get(). That is, unless you have inadvertantly declared a property with the same name as a data item..... ?
  20. Thanks for that @kongondo. It's just that I thought there may be some extra subleties because on some occasions $object->property did not work, but $object->get('property') did and I couldn't understand why. Unfortunately it is a bit difficult to build an example outside of a rather complex context (my FieldtypeMeasurement module), but I'll see if I can find a way of simply illustrating this behaviour.
  21. Having used PW for a while now, I'm still confused about when to use get and set for WireData objects and when to just use object operators. As I understand it, WireData objects have a 'data' property with associated 'get' and 'set' methods: /** * Array where get/set properties are stored * */ protected $data = array(); /** * Set a value to this object’s data * * ~~~~~ * // Set a value for a property * $item->set('foo', 'bar'); * * // Set a property value directly * $item->foo = 'bar'; * * // Set a property using array access * $item['foo'] = 'bar'; * ~~~~~ It also seems that you can access the data items directly using the object operator -> However, I recall situations (which I can't replicate in this simple example) where the object operator does not return the data item. Am I imagining things? Is there any guidance on when to use 'get' and 'set' rather than the operator (which is much easier in the IDE)?
  22. Hi @adrian. What did you do to get an error in a template file - I can't replicate that? See above post - executes correctly with no errors - the code in the template was: $data = include_once 'M:\laragon\www\BawdHall\site-admin\modules\FieldtypeMeasurement\Config\Temperature.php'; bd($data, 'data 1'); if($data === true) { $data = $session->get('quantity' . '_data'); } else { $session->set('quantity' . '_data', $data); } bd($data, 'data 2'); $data = include_once 'M:\laragon\www\BawdHall\site-admin\modules\FieldtypeMeasurement\Config\Temperature.php'; bd($data, 'data 1'); if($data === true) { $data = $session->get('quantity' . '_data'); } else { $session->set('quantity' . '_data', $data); } bd($data, 'data 2'); The link you provided yielded no insights as it failed to catch the supposed error. Also, it seems like the 'error' is not caught by tracyConsoleShutdownHandler() in CodeProcessor.php, so I'm not sure how further to track it down.
  23. Thanks @adrian. That's curious because I'm not getting the exception in a template file. It executes normally with the correct result and no exceptions: DATA1 is the result of the include_once and DATA2 is after the test - i.e. if DATA1 is == true it is the session variable. Also, even in the console panel everything executes normally - the exception message seems to be spurious. However, I will investigate the stackoverflow link and report back anything of interest. EDIT - should have expanded that second DATA2 to show the closure:
×
×
  • Create New...