QGIS API Documentation 3.28.0-Firenze (ed3ad0430f)
qgsvaluerelationfieldformatter.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsvaluerelationfieldformatter.cpp - QgsValueRelationFieldFormatter
3
4 ---------------------
5 begin : 3.12.2016
6 copyright : (C) 2016 by Matthias Kuhn
8 ***************************************************************************
9 * *
10 * This program is free software; you can redistribute it and/or modify *
11 * it under the terms of the GNU General Public License as published by *
12 * the Free Software Foundation; either version 2 of the License, or *
13 * (at your option) any later version. *
14 * *
15 ***************************************************************************/
17
18#include "qgis.h"
19#include "qgsproject.h"
20#include "qgsvectorlayer.h"
22#include "qgsapplication.h"
24#include "qgsvectorlayerref.h"
26#include "qgsmessagelog.h"
27#include "qgsvariantutils.h"
28
29#include <nlohmann/json.hpp>
30using namespace nlohmann;
31
32#include <QSettings>
33
35{
36 return qgsVariantLessThan( p1.key, p2.key );
37}
38
40{
41 return qgsVariantLessThan( p1.value, p2.value );
42}
43
45{
47}
48
50{
51 return QStringLiteral( "ValueRelation" );
52}
53
54QString QgsValueRelationFieldFormatter::representValue( QgsVectorLayer *layer, int fieldIndex, const QVariantMap &config, const QVariant &cache, const QVariant &value ) const
55{
56 ValueRelationCache vrCache;
57
58 if ( cache.isValid() )
59 {
61 }
62 else
63 {
65 }
66
67 if ( config.value( QStringLiteral( "AllowMulti" ) ).toBool() )
68 {
69 QStringList keyList;
70
71 if ( layer->fields().at( fieldIndex ).type() == QVariant::Map )
72 {
73 //because of json it's stored as QVariantList
74 keyList = value.toStringList();
75 }
76 else
77 {
78 keyList = valueToStringList( value );
79 }
80
81 QStringList valueList;
82
83 for ( const QgsValueRelationFieldFormatter::ValueRelationItem &item : std::as_const( vrCache ) )
84 {
85 if ( keyList.contains( item.key.toString() ) )
86 {
87 valueList << item.value;
88 }
89 }
90
91 return valueList.join( QLatin1String( ", " ) ).prepend( '{' ).append( '}' );
92 }
93 else
94 {
95 if ( QgsVariantUtils::isNull( value ) )
96 {
98 }
99
100 for ( const QgsValueRelationFieldFormatter::ValueRelationItem &item : std::as_const( vrCache ) )
101 {
102 if ( item.key == value )
103 {
104 return item.value;
105 }
106 }
107 }
108
109 return QStringLiteral( "(%1)" ).arg( value.toString() );
110}
111
112QVariant QgsValueRelationFieldFormatter::sortValue( QgsVectorLayer *layer, int fieldIndex, const QVariantMap &config, const QVariant &cache, const QVariant &value ) const
113{
114 return QgsVariantUtils::isNull( value ) ? QString() : representValue( layer, fieldIndex, config, cache, value );
115}
116
117QVariant QgsValueRelationFieldFormatter::createCache( QgsVectorLayer *layer, int fieldIndex, const QVariantMap &config ) const
118{
119 Q_UNUSED( layer )
120 Q_UNUSED( fieldIndex )
121 return QVariant::fromValue<ValueRelationCache>( createCache( config ) );
122
123}
124
126 const QVariantMap &config,
127 const QgsFeature &formFeature,
128 const QgsFeature &parentFormFeature )
129{
130 ValueRelationCache cache;
131
132 const QgsVectorLayer *layer = resolveLayer( config, QgsProject::instance() );
133
134 if ( !layer )
135 return cache;
136
137 QgsFields fields = layer->fields();
138 int ki = fields.indexOf( config.value( QStringLiteral( "Key" ) ).toString() );
139 int vi = fields.indexOf( config.value( QStringLiteral( "Value" ) ).toString() );
140
141 QgsFeatureRequest request;
142
144 QgsAttributeIds subsetOfAttributes { ki, vi };
145
146 const QString descriptionExpressionString = config.value( "Description" ).toString();
147 QgsExpression descriptionExpression( descriptionExpressionString );
149 descriptionExpression.prepare( &context );
150 subsetOfAttributes += descriptionExpression.referencedAttributeIndexes( layer->fields() );
151 request.setSubsetOfAttributes( qgis::setToList( subsetOfAttributes ) );
152
153 const QString filterExpression = config.value( QStringLiteral( "FilterExpression" ) ).toString();
154
155 // Skip the filter and build a full cache if the form scope is required and the feature
156 // is not valid or the attributes required for the filter have no valid value
157 // Note: parent form scope is not checked for usability because it's supposed to
158 // be used into a coalesce that retrieve the current value of the parent
159 // from the parent layer when used outside of an embedded form
160 if ( ! filterExpression.isEmpty() && ( !( expressionRequiresFormScope( filterExpression ) )
161 || expressionIsUsable( filterExpression, formFeature ) ) )
162 {
163 QgsExpressionContext filterContext = context;
164 if ( formFeature.isValid( ) && QgsValueRelationFieldFormatter::expressionRequiresFormScope( filterExpression ) )
165 filterContext.appendScope( QgsExpressionContextUtils::formScope( formFeature ) );
166 if ( parentFormFeature.isValid() && QgsValueRelationFieldFormatter::expressionRequiresParentFormScope( filterExpression ) )
167 filterContext.appendScope( QgsExpressionContextUtils::parentFormScope( parentFormFeature ) );
168 request.setExpressionContext( filterContext );
169 request.setFilterExpression( filterExpression );
170 }
171
172 QgsFeatureIterator fit = layer->getFeatures( request );
173
174 QgsFeature f;
175 while ( fit.nextFeature( f ) )
176 {
177 QString description;
178 if ( descriptionExpression.isValid() )
179 {
180 context.setFeature( f );
181 description = descriptionExpression.evaluate( &context ).toString();
182 }
183 cache.append( ValueRelationItem( f.attribute( ki ), f.attribute( vi ).toString(), description ) );
184 }
185
186 if ( config.value( QStringLiteral( "OrderByValue" ) ).toBool() )
187 {
188 std::sort( cache.begin(), cache.end(), orderByValueLessThan );
189 }
190 else
191 {
192 std::sort( cache.begin(), cache.end(), orderByKeyLessThan );
193 }
194
195 return cache;
196}
197
198
199QList<QgsVectorLayerRef> QgsValueRelationFieldFormatter::layerDependencies( const QVariantMap &config ) const
200{
201 QList<QgsVectorLayerRef> result;
202 const QString layerId { config.value( QStringLiteral( "Layer" ) ).toString() };
203 const QString layerName { config.value( QStringLiteral( "LayerName" ) ).toString() };
204 const QString providerName { config.value( QStringLiteral( "LayerProviderName" ) ).toString() };
205 const QString layerSource { config.value( QStringLiteral( "LayerSource" ) ).toString() };
206 if ( ! layerId.isEmpty() && ! layerName.isEmpty() && ! providerName.isEmpty() && ! layerSource.isEmpty() )
207 {
208 result.append( QgsVectorLayerRef( layerId, layerName, layerSource, providerName ) );
209 }
210 return result;
211}
212
213QVariantList QgsValueRelationFieldFormatter::availableValues( const QVariantMap &config, int countLimit, const QgsFieldFormatterContext &context ) const
214{
215 QVariantList values;
216
217 if ( auto *lProject = context.project() )
218 {
219 const QgsVectorLayer *referencedLayer = qobject_cast<QgsVectorLayer *>( lProject->mapLayer( config[QStringLiteral( "Layer" )].toString() ) );
220 if ( referencedLayer )
221 {
222 int fieldIndex = referencedLayer->fields().indexOf( config.value( QStringLiteral( "Key" ) ).toString() );
223 values = qgis::setToList( referencedLayer->uniqueValues( fieldIndex, countLimit ) );
224 }
225 }
226 return values;
227}
228
229QStringList QgsValueRelationFieldFormatter::valueToStringList( const QVariant &value )
230{
231 QStringList checkList;
232 if ( value.type() == QVariant::StringList )
233 {
234 checkList = value.toStringList();
235 }
236 else
237 {
238 QVariantList valuesList;
239 if ( value.type() == QVariant::String )
240 {
241 // This must be an array representation
242 auto newVal { value };
243 if ( newVal.toString().trimmed().startsWith( '{' ) )
244 {
245 //normal case
246 valuesList = QgsPostgresStringUtils::parseArray( newVal.toString() );
247 }
248 else if ( newVal.toString().trimmed().startsWith( '[' ) )
249 {
250 //fallback, in case it's a json array
251 try
252 {
253 for ( auto &element : json::parse( newVal.toString().toStdString() ) )
254 {
255 if ( element.is_number_integer() )
256 {
257 valuesList.push_back( element.get<int>() );
258 }
259 else if ( element.is_number_unsigned() )
260 {
261 valuesList.push_back( element.get<unsigned>() );
262 }
263 else if ( element.is_string() )
264 {
265 valuesList.push_back( QString::fromStdString( element.get<std::string>() ) );
266 }
267 }
268 }
269 catch ( json::parse_error &ex )
270 {
271 QgsMessageLog::logMessage( QObject::tr( "Cannot parse JSON like string '%1' Error: %2" ).arg( newVal.toString(), ex.what() ) );
272 }
273 }
274 }
275 else if ( value.type() == QVariant::List )
276 {
277 valuesList = value.toList( );
278 }
279
280 checkList.reserve( valuesList.size() );
281 for ( const QVariant &listItem : std::as_const( valuesList ) )
282 {
283 QString v( listItem.toString( ) );
284 if ( ! v.isEmpty() )
285 checkList.append( v );
286 }
287 }
288 return checkList;
289}
290
291
292QSet<QString> QgsValueRelationFieldFormatter::expressionFormVariables( const QString &expression )
293{
294 std::unique_ptr< QgsExpressionContextScope > scope( QgsExpressionContextUtils::formScope() );
295 QSet< QString > formVariables = qgis::listToSet( scope->variableNames() );
296 const QSet< QString > usedVariables = QgsExpression( expression ).referencedVariables();
297 formVariables.intersect( usedVariables );
298 return formVariables;
299}
300
302{
303 std::unique_ptr< QgsExpressionContextScope > scope( QgsExpressionContextUtils::parentFormScope() );
304 QSet< QString > formVariables = qgis::listToSet( scope->variableNames() );
305 const QSet< QString > usedVariables = QgsExpression( expression ).referencedVariables();
306 formVariables.intersect( usedVariables );
307 return formVariables;
308}
309
311{
312 return !( expressionFormAttributes( expression ).isEmpty() && expressionFormVariables( expression ).isEmpty() );
313}
314
316{
317 return !( expressionParentFormAttributes( expression ).isEmpty() && expressionParentFormVariables( expression ).isEmpty() );
318}
319
321{
322 QSet<QString> attributes;
323 QgsExpression exp( expression );
324 std::unique_ptr< QgsExpressionContextScope > scope( QgsExpressionContextUtils::parentFormScope() );
325 // List of form function names used in the expression
326 const QSet<QString> formFunctions( qgis::listToSet( scope->functionNames() )
327 .intersect( exp.referencedFunctions( ) ) );
328 const QList<const QgsExpressionNodeFunction *> expFunctions( exp.findNodes<QgsExpressionNodeFunction>() );
329 QgsExpressionContext context;
330 for ( const auto &f : expFunctions )
331 {
332 QgsExpressionFunction *fd = QgsExpression::QgsExpression::Functions()[f->fnIndex()];
333 if ( formFunctions.contains( fd->name( ) ) )
334 {
335 const QList<QgsExpressionNode *> cExpressionNodes { f->args( )->list() };
336 for ( const auto &param : std::as_const( cExpressionNodes ) )
337 {
338 attributes.insert( param->eval( &exp, &context ).toString() );
339 }
340 }
341 }
342 return attributes;
343}
344
345QSet<QString> QgsValueRelationFieldFormatter::expressionFormAttributes( const QString &expression )
346{
347 QSet<QString> attributes;
348 QgsExpression exp( expression );
349 std::unique_ptr< QgsExpressionContextScope > scope( QgsExpressionContextUtils::formScope() );
350 // List of form function names used in the expression
351 const QSet<QString> formFunctions( qgis::listToSet( scope->functionNames() )
352 .intersect( exp.referencedFunctions( ) ) );
353 const QList<const QgsExpressionNodeFunction *> expFunctions( exp.findNodes<QgsExpressionNodeFunction>() );
354 QgsExpressionContext context;
355 for ( const auto &f : expFunctions )
356 {
357 QgsExpressionFunction *fd = QgsExpression::QgsExpression::Functions()[f->fnIndex()];
358 if ( formFunctions.contains( fd->name( ) ) )
359 {
360 const QList<QgsExpressionNode *> cExpressionNodes { f->args( )->list() };
361 for ( const auto &param : std::as_const( cExpressionNodes ) )
362 {
363 attributes.insert( param->eval( &exp, &context ).toString() );
364 }
365 }
366 }
367 return attributes;
368}
369
371 const QgsFeature &feature,
372 const QgsFeature &parentFeature )
373{
374 const QSet<QString> attrs = expressionFormAttributes( expression );
375 for ( auto it = attrs.constBegin() ; it != attrs.constEnd(); it++ )
376 {
377 if ( feature.fieldNameIndex( *it ) < 0 )
378 return false;
379 }
380
381 if ( ! expressionFormVariables( expression ).isEmpty() && feature.geometry().isEmpty( ) )
382 return false;
383
384 if ( parentFeature.isValid() )
385 {
386 const QSet<QString> parentAttrs = expressionParentFormAttributes( expression );
387 for ( auto it = parentAttrs.constBegin() ; it != parentAttrs.constEnd(); it++ )
388 {
389 if ( ! parentFeature.attribute( *it ).isValid() )
390 return false;
391 }
392 if ( ! expressionParentFormVariables( expression ).isEmpty() && parentFeature.geometry().isEmpty( ) )
393 return false;
394 }
395 return true;
396}
397
398QgsVectorLayer *QgsValueRelationFieldFormatter::resolveLayer( const QVariantMap &config, const QgsProject *project )
399{
400 QgsVectorLayerRef ref { config.value( QStringLiteral( "Layer" ) ).toString(),
401 config.value( QStringLiteral( "LayerName" ) ).toString(),
402 config.value( QStringLiteral( "LayerSource" ) ).toString(),
403 config.value( QStringLiteral( "LayerProviderName" ) ).toString() };
404 return ref.resolveByIdOrNameOnly( project );
405}
static QString nullRepresentation()
This string is used to represent the value NULL throughout QGIS.
static QgsExpressionContextScope * parentFormScope(const QgsFeature &formFeature=QgsFeature(), const QString &formMode=QString())
Creates a new scope which contains functions and variables from the current parent attribute form/tab...
static QgsExpressionContextScope * formScope(const QgsFeature &formFeature=QgsFeature(), const QString &formMode=QString())
Creates a new scope which contains functions and variables from the current attribute form/table form...
static QList< QgsExpressionContextScope * > globalProjectLayerScopes(const QgsMapLayer *layer)
Creates a list of three scopes: global, layer's project and layer.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
void appendScope(QgsExpressionContextScope *scope)
Appends a scope to the end of the context.
void setFeature(const QgsFeature &feature)
Convenience function for setting a feature for the context.
A abstract base class for defining QgsExpression functions.
QString name() const
The name of the function.
An expression node for expression functions.
Class for parsing and evaluation of expressions (formerly called "search strings").
bool prepare(const QgsExpressionContext *context)
Gets the expression ready for evaluation - find out column indexes.
QList< const T * > findNodes() const
Returns a list of all nodes of the given class which are used in this expression.
QSet< QString > referencedVariables() const
Returns a list of all variables which are used in this expression.
QSet< QString > referencedFunctions() const
Returns a list of the names of all functions which are used in this expression.
QVariant evaluate()
Evaluate the feature and return the result.
bool isValid() const
Checks if this expression is valid.
QSet< int > referencedAttributeIndexes(const QgsFields &fields) const
Returns a list of field name indexes obtained from the provided fields.
Wrapper for iterator of features from vector data provider or vector layer.
bool nextFeature(QgsFeature &f)
This class wraps a request for features to a vector layer (or directly its vector data provider).
QgsFeatureRequest & setFlags(QgsFeatureRequest::Flags flags)
Sets flags that affect how features will be fetched.
QgsFeatureRequest & setSubsetOfAttributes(const QgsAttributeList &attrs)
Set a subset of attributes that will be fetched.
QgsFeatureRequest & setFilterExpression(const QString &expression)
Set the filter expression.
@ NoGeometry
Geometry is not required. It may still be returned if e.g. required for a filter condition.
QgsFeatureRequest & setExpressionContext(const QgsExpressionContext &context)
Sets the expression context used to evaluate filter expressions.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition: qgsfeature.h:56
int fieldNameIndex(const QString &fieldName) const
Utility method to get attribute index from name.
Definition: qgsfeature.cpp:353
QgsGeometry geometry
Definition: qgsfeature.h:67
bool isValid() const
Returns the validity of this feature.
Definition: qgsfeature.cpp:219
QVariant attribute(const QString &name) const
Lookup attribute value by attribute name.
Definition: qgsfeature.cpp:338
A context for field formatter containing information like the project.
QgsProject * project() const
Returns the project used in field formatter.
Flags flags() const
Returns the flags.
@ CanProvideAvailableValues
Can provide possible values.
void setFlags(const Flags &flags)
Sets the flags.
QVariant::Type type
Definition: qgsfield.h:58
Container of fields for a vector layer.
Definition: qgsfields.h:45
int indexOf(const QString &fieldName) const
Gets the field index from the field name.
Definition: qgsfields.cpp:207
QgsField at(int i) const
Returns the field at particular index (must be in range 0..N-1).
Definition: qgsfields.cpp:163
bool isEmpty() const
Returns true if the geometry is empty (eg a linestring with no vertices, or a collection with no geom...
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::MessageLevel::Warning, bool notifyUser=true)
Adds a message to the log instance (and creates it if necessary).
static QVariantList parseArray(const QString &string)
Returns a QVariantList created out of a string containing an array in postgres array format {1,...
Encapsulates a QGIS project, including sets of map layers and their styles, layouts,...
Definition: qgsproject.h:104
static QgsProject * instance()
Returns the QgsProject singleton instance.
Definition: qgsproject.cpp:477
static QgsVectorLayer * resolveLayer(const QVariantMap &config, const QgsProject *project)
Returns the (possibly NULL) layer from the widget's config and project.
static QSet< QString > expressionFormVariables(const QString &expression)
Returns a list of variables required by the form context expression.
static bool expressionRequiresFormScope(const QString &expression)
Check if the expression requires a form scope (i.e.
QString id() const override
Returns a unique id for this field formatter.
static bool expressionRequiresParentFormScope(const QString &expression)
Check if the expression requires a parent form scope (i.e.
QString representValue(QgsVectorLayer *layer, int fieldIndex, const QVariantMap &config, const QVariant &cache, const QVariant &value) const override
Create a pretty String representation of the value.
QVariant sortValue(QgsVectorLayer *layer, int fieldIndex, const QVariantMap &config, const QVariant &cache, const QVariant &value) const override
If the default sort order should be overwritten for this widget, you can transform the value in here.
QVariant createCache(QgsVectorLayer *layer, int fieldIndex, const QVariantMap &config) const override
Create a cache for a given field.
QList< QgsVectorLayerRef > layerDependencies(const QVariantMap &config) const override
Returns a list of weak layer references to other layers required by this formatter for the given conf...
static QSet< QString > expressionParentFormVariables(const QString &expression)
Returns a list of variables required by the parent form's form context expression.
static QSet< QString > expressionParentFormAttributes(const QString &expression)
Returns a list of attributes required by the parent form's form context expression.
static QStringList valueToStringList(const QVariant &value)
Utility to convert a list or a string representation of an (hstore style: {1,2...}) list in value to ...
static QSet< QString > expressionFormAttributes(const QString &expression)
Returns a list of attributes required by the form context expression.
static bool expressionIsUsable(const QString &expression, const QgsFeature &feature, const QgsFeature &parentFeature=QgsFeature())
Check whether the feature has all values required by the expression, optionally checks for parentFeat...
QVariantList availableValues(const QVariantMap &config, int countLimit, const QgsFieldFormatterContext &context) const override
Returns a list of the values that would be possible to select with this widget type On a RelationRefe...
QVector< QgsValueRelationFieldFormatter::ValueRelationItem > ValueRelationCache
QgsValueRelationFieldFormatter()
Constructor for QgsValueRelationFieldFormatter.
static bool isNull(const QVariant &variant)
Returns true if the specified variant should be considered a NULL value.
Represents a vector layer which manages a vector based data sets.
QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest()) const FINAL
Queries the layer for features specified in request.
QgsFields fields() const FINAL
Returns the list of fields of this layer.
QSet< QVariant > uniqueValues(int fieldIndex, int limit=-1) const FINAL
Calculates a list of unique values contained within an attribute in the layer.
bool qgsVariantLessThan(const QVariant &lhs, const QVariant &rhs)
Compares two QVariant values and returns whether the first is less than the second.
Definition: qgis.cpp:119
QgsSQLStatement::Node * parse(const QString &str, QString &parserErrorMsg, bool allowFragments)
bool orderByKeyLessThan(const QgsValueRelationFieldFormatter::ValueRelationItem &p1, const QgsValueRelationFieldFormatter::ValueRelationItem &p2)
bool orderByValueLessThan(const QgsValueRelationFieldFormatter::ValueRelationItem &p1, const QgsValueRelationFieldFormatter::ValueRelationItem &p2)
QSet< int > QgsAttributeIds
_LayerRef< QgsVectorLayer > QgsVectorLayerRef
TYPE * resolveByIdOrNameOnly(const QgsProject *project)
Resolves the map layer by attempting to find a matching layer in a project using a weak match.