chasegiunta / craft-jason Goto Github PK
View Code? Open in Web Editor NEWA field type for displaying & editing JSON data.
License: Other
A field type for displaying & editing JSON data.
License: Other
Nice plugin!
We run into a usability issue when there is a load of nested data where it's really hard to navigate the fields and know where you are.
For our case the base data structure is like:
{
ivr: {
f: { // gender female
18: {
standard: 23.00,
premium: 25.00
},
19: {},
20: {},
…
},
m: { // gender male
…
},
},
tfk: {…},
wair: {…},
}
For each ivr, tfk and wair there are two genders and below that each entry corresponds to an age and range from 18 to 60. So quite a lot of data.
The problem is because there are so many entries you do not see on which branch you are and it's quite hard to edit those entries and knowing if you are in the correct branch:
One possible solution which could help, that you cold collapse the children so that you can drill in and know on which branch you are. Similar like code folding works:
Another possible solution would be to always have the property name visible at the specific position:
Of course these are just ideas and need to validated if they work as intended and maybe there is even another better solution.
I'd like to know what you think of that? Do you even want to support such large structures with this plugin?
I'm trying to use a Jason field inside Commerce attached to an order, and I was running into a situation where the field would not appear in the UI when reviewing an order, but it would appear when I tried to "Edit" the Order.
Took me a long time to figure out what was going on.
Turns out that unlike the content parts Craft, Commerce has kind of a "preview screen" when first reviewing the contents of an order so that admins don't accidentally change things without intentionally meaning to. This also applies to reviewing Drafts of non-Commerce entries as well.
Craft calls the getInputHtml()
function when it needs to display a field that is ready to accept user input, but not when it wants to display the read only contents of a field.
When it wants the read only version it calls the getStaticHtml()
function associated with each field - https://docs.craftcms.com/api/v3/craft-fields-baserelationfield.html#public-methods
This is a relatively trivial function to implement since Jason already has the functionality to display a field as read-only.
So for the most part, it's a straight-up duplication of getInputHtml()
with a couple of namespace changes with forced settings on readonly
and allowRawEditing
public function getStaticHtml($value, ElementInterface $element = null): string {
if (is_array($value)) {
$json = Json::encode($value);
$valid = true;
} else {
// Assume we're accessing from control panel
$json = json_decode($value);
if ($json === null) {
$json = $value;
$valid = false;
} else {
$json = Json::encode($json);
$valid = true;
}
}
// Register our asset bundle
Craft::$app->getView()->registerAssetBundle(JasonFieldAsset::class);
// Get our id and namespace
$id = Craft::$app->getView()->formatInputId($this->handle) . '-static';
$namespacedId = Craft::$app->getView()->namespaceInputId($id);
Craft::$app->getView()->registerJs("var staticEvent = new CustomEvent('build', { detail: '$namespacedId' }); window.dispatchEvent(staticEvent);");
// Render the input template
return Craft::$app->getView()->renderTemplate(
'jason/_components/fields/JasonField_input',
[
'name' => $this->handle,
'value' => $json,
'valid' => $valid,
'field' => $this,
'id' => $id,
'namespacedId' => $namespacedId,
'readonly' => true,
'allowRawEditing' => false
]
);
}
The above could absolutely be refactored so that you don't have as much duplication between the two functions, but this would be a great addition as-is in the meantime.
When a jason field is added to a section, it trigger field modification warning automatically even if no modification is made to the entry.
** Step to reproduce
Edit detail entry. Reload the page or click another navigation item. The modification warning popup.
I understand the message will show if I change something on the jason field but it's not always the case.
Thank you.
Hi,
Im attempting to update your jason field with my JSON data (stringified) through graphql, but Im receiving the (unhelpful) error "Error: GraphQL error: Internal server error" when i call the mutation.
Do you know of any reason why the JASON field will not accept a string type when populated using graphql?
Additional info:
If i change the fieldtype from Jason to a Plain Text field the mutation runs successfully (as expected) and the field is populated:
and then when i change the fieldtype back to Jason the data is displayed correctly:
So we know the data ima attempting to send is valid for your fieldtype.
I'm adding data to a Jason field via AJAX by posting to a controller in another plugin. I noticed Jason Field expects a String as it does a JSON.decode()
by default.
Maybe this could be altered and have an extra check for the Array type?
If I pass a JavaScript object in my fetch data like this: fields[jasonFieldHandle]
the JasonField gets its data as an Array.
Now I need to have an extra JSON.stringify()
in my JS code, which is not terrible, but it is weird from a developer point of view that I cannot pass valid JSON to a JSON field :)
For updating this for Craft 4 x
Hi!
May I ask why the field content is not normalized when the request is an action request (https://github.com/chasegiunta/craft-jason/blob/master/src/fields/JasonField.php#L126)?
We are displaying Jason contents on a page which also includes a MailChimp subscribe form. After posting the subscribe form and returning to the page, the Jason content is not decoded and is causing errors now.
We noticed a small problem when saving an entry containing the field jason for a multisite project.
The jason field is configured for use on all project sites.
By default in Craft, during the first backup, the translatable fields are copied for all sites. Then, the modification is done by site and the content remains static for the other sites.
The problem is that the jason field does not seem to propagate properly like the other native Craft fields.
Is this feature wanted?
Thank you for your plugin
When adding the field to a Matrix Block, the lightswitches don't show.
<jason-switch>
is left rendered in the template, so I suspect you just need to make sure your component is mounting within Matrix.
Note: if you try save the field at this point, it will reload with an error because those fields are required – but at that point the switches render, so you can set the values.
I would like to know if there a way to make a directive that convert a string to a formatted JSON. I’m using this plugin to get a JSON structure. When querying the corresponding field GraphQL expect a value of type String but it received an StdClass. I tried to cast it using a custom directive JsonFormatter but it doesn’t seems to work.
Is there a way to update this plugin to make it compatible with GraphQL using a GraphQL directive or by updating the plugin itself?
Hi,
We are using your plugin to manage i18n text for your client.
It seem to have a issue with the table cell height when the plugin field is inside another tab not active on page load.
On load of an entry in the control panel, if the tab containing the jason field is active, the cell height is correct. But if we load an entry with any other tab active and then change the tab to show the jason field, the jason table cell show only one line. We have to reload to show the table correctly.
Here the correct behavior (Tab is active on page load)
Here is the problem (Change tab after page load)
Take note that resizing the window fix the problem.
Thanks for your plugin.
Sorry for create another issue, but we very like your plugin and use it a lot.
One problem we noticed is the display of the table in content editing mode.
For some unknown reason, some columns are wider than others, making editing complicated (this gives the impression that there are more levels of nesting) which is not the case.
On the next image, we see the problem on the line COLORFUL, DONOR and SURVIVOR.
Is there a reason why columns are not equal even if there is room for more content?
Thank you for your support.
I get the following error when trying to install:
Problem 1
- Root composer.json requires chasegiunta/craft-jason ^2.0 -> satisfiable by chasegiunta/craft-jason[2.0.0, 2.0.1].
- chasegiunta/craft-jason[2.0.0, ..., 2.0.1] require craftcms/cms ^3.4 -> found craftcms/cms[3.4.0-beta.1, ..., 3.7.59] but it conflicts with your root composer.json require (4.3.1).
For an unknown reason, the Jason plugin returns a javascript error when creating fields: Uncaught TypeError: Can not read property 'call' of undefined.
The only way to fix the problem is to disable the plugin, or to comment $this->js in the file assetbundles/jasonfield /JasonFieldAsset.php
For the moment, it is impossible to save the field since the lightswitch is not displayed and must be required.
See image below for more information.
Maybe is related to the Craft version : 3.1.30
Trying to set a field in a plugin, using the following:
$entry->setFieldValue('json', Json::encode($variable));
JSON value is a string and in this format:
{
"Some Title": {
"question": "What is Foo?",
"answer": "hello\r\n\r\nthis \r\n\r\nis a multi-line!"
},
"Another Title": {
"question": "What is bar?",
"answer": "This is another answer to the question."
}
}
Error is below when trying to store an already formatted JSON string using:
"name": "Exception",
"message": "json_decode(): Argument #1 ($json) must be of type string, array given",
"code": 0,
"error": "json_decode(): Argument #1 ($json) must be of type string, array given",
"exception": "TypeError",
"file": "/home/zadro/www/clientname/vendor/chasegiunta/craft-jason/src/fields/JasonField.php",
"line": 127
https://github.com/chasegiunta/craft-jason/issues/108
I can confirm the fix @stevecomrie proposes #108 is a working solution.
However, the fix is required on both lines 127 and 425 in JasonField.php
Is there a reason why php8.1 is required in composer requirements?
"require": {
"craftcms/cms": "^4.0.0",
"php": "^8.1.0"
},
Because Craft requirements are
"require": {
"php": "^8.0.2",
....
I ask because we cannot use version 8.1 at the moment. So I can't use the plugin.
Is it possible for you to follow Craft's requirements or is there a specific reason for using php 8.1?
Any chance this plugin will include Craft 4 support in the near future, @chasegiunta? Otherwise we need to look into alternatives to update our sites.
For a project we are constantly running into the 64 KB limit of the JSON field. It would be great if the plugin could be made to support MEDIUMTEXT for the field. We first addressed this by shortening the data stored in the field, but now there are cases where this is not an option any more. All the problems could be avoided if the field used larger database fields.
CP errors with Couldn’t save field
, field options also aren't showing but think that's a 3.4 style change thing.
I have created a Jason field in my craft 4.0 website without issue. As I went back to edit my field, this error is displayed.
`Invalid Configuration – yii\base\InvalidConfigException
An asset bundle that depends on 'craft\web\assets\cp\CpAsset' has a higher javascript file position configured than 'craft\web\assets\cp\CpAsset'.`
I found in this file: production/htdocs/vendor/chasegiunta/craft-jason/src/fields/JasonField.php that if I change the view position at this line, the page will be correctly display.
Craft::$app->getView()->registerAssetBundle(JasonFieldAsset::class, View::POS_BEGIN );
to
Craft::$app->getView()->registerAssetBundle(JasonFieldAsset::class, View::POS_END );
I'm not sure how this could affect the others functionalities of the plugin, but so far I don't see anything weird.
It's not possible to set a Jason field value programmatically from another plugin (calling the setFieldValue
method on an element for this field), you get the following error json_decode() expects parameter 1 to be string, array given
in the method public function validateIsJSON(ElementInterface $element, array $params = null)
.
Apparently it is due to how the normalizeValue method is implemented (the request is identified as a site request and is returned as an array causing the validateIsJSON method to fail). I've fixed it by checking if it's an action request:
public function normalizeValue($value, ElementInterface $element = null)
{
if (Craft::$app->request->getIsSiteRequest() &&
!Craft::$app->request->getIsActionRequest()) {
return json_decode($value, true);
} else {
return $value;
}
}
This is the command causing the error:
$user = User::find()->email('whateveremail')->one();
$user->setFieldValue('myFieldName', 'jsoninstringformat');
Craft::$app->getElements()->saveElement($user); <---- Error
This is the stacktrace with the error:
2020-03-12 05:38:12 [-][-][-][error][yii\base\ErrorException:2] yii\base\ErrorException: json_decode() expects parameter 1 to be string, array given in /.../vendor/chasegiunta/craft-jason/src/fields/JasonField.php:432
Stack trace:
#0 /.../vendor/craftcms/cms/src/web/ErrorHandler.php(74): yii\base\ErrorHandler->handleError(2, 'json_decode() e...', '/home/...', 432)
#1 [internal function]: craft\web\ErrorHandler->handleError(2, 'json_decode() e...', '/home/...', 432, Array)
#2 /.../vendor/chasegiunta/craft-jason/src/fields/JasonField.php(432): json_decode(Array)
#3 /.../vendor/craftcms/cms/src/base/Element.php(1383): chasegiunta\jason\fields\JasonField->validateIsJSON(Object(craft\elements\User), NULL)
#4 [internal function]: craft\base\Element->validateCustomFieldAttribute('field:subscrDat...', Array, Object(yii\validators\InlineValidator))
#5 /.../vendor/yiisoft/yii2/validators/InlineValidator.php(72): call_user_func(Array, 'field:subscrDat...', Array, Object(yii\validators\InlineValidator))
#6 /.../vendor/yiisoft/yii2/validators/Validator.php(257): yii\validators\InlineValidator->validateAttribute(Object(craft\elements\User), 'field:subscrDat...')
#7 /.../vendor/yiisoft/yii2/base/Model.php(367): yii\validators\Validator->validateAttributes(Object(craft\elements\User), Array)
#8 /.../vendor/craftcms/cms/src/services/Elements.php(1987): yii\base\Model->validate()
I'm happy to create a PR for this if you can confirm this is the right approach to fix it.
Thanks.
When a Jason type field is associated with a Resource, the field does not work properly.
In the assets sections, to display the details of an asset, with the double click, the field jason is displayed correctly.
However, if you close the modal window and open the same or another asset, the Jason field is not displayed.
No error appears javascript is displayed in the console.
Probably this field was not thought for this kind of display.
Would it be possible to solve this problem?
Thank you !
When this plugin is used within a matrix field, only the last time it is used is rendered.
This is caused by the id's used to fill the window.JasonField
object are the same for all fields:
When i change this to use the namespace as key instead, it works as desired:
I will prepare a PR that implements this, is this a desired solution?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.