29#include <nlohmann/json.hpp>
30using namespace nlohmann;
46 setFlags(
flags() | QgsFieldFormatter::CanProvideAvailableValues );
51 return QStringLiteral(
"ValueRelation" );
58 if ( cache.isValid() )
67 if ( config.value( QStringLiteral(
"AllowMulti" ) ).toBool() )
71 if ( layer->
fields().
at( fieldIndex ).
type() == QMetaType::Type::QVariantMap )
74 keyList = value.toStringList();
81 QStringList valueList;
85 if ( keyList.contains( item.key.toString() ) )
87 valueList << item.value;
91 return valueList.join( QLatin1String(
", " ) ).prepend(
'{' ).append(
'}' );
102 if ( item.key == value )
109 return QStringLiteral(
"(%1)" ).arg( value.toString() );
120 Q_UNUSED( fieldIndex )
121 return QVariant::fromValue<ValueRelationCache>(
createCache( config ) );
126 const QVariantMap &config,
138 const int keyIdx = fields.
indexOf( config.value( QStringLiteral(
"Key" ) ).toString() );
139 const int valueIdx = fields.
indexOf( config.value( QStringLiteral(
"Value" ) ).toString() );
146 const int groupIdx = fields.
lookupField( config.value( QStringLiteral(
"Group" ) ).toString() );
149 subsetOfAttributes << groupIdx;
152 const QString descriptionExpressionString = config.value(
"Description" ).toString();
153 QgsExpression descriptionExpression( descriptionExpressionString );
155 descriptionExpression.
prepare( &context );
159 const QString filterExpression = config.value( QStringLiteral(
"FilterExpression" ) ).toString();
184 if ( descriptionExpression.
isValid() )
187 description = descriptionExpression.
evaluate( &context ).toString();
189 const QVariant group = groupIdx > -1 ? f.
attribute( groupIdx ) : QVariant();
193 if ( config.value( QStringLiteral(
"OrderByValue" ) ).toBool() )
208 QList<QgsVectorLayerRef> result;
209 const QString layerId { config.value( QStringLiteral(
"Layer" ) ).toString() };
210 const QString layerName { config.value( QStringLiteral(
"LayerName" ) ).toString() };
211 const QString providerName { config.value( QStringLiteral(
"LayerProviderName" ) ).toString() };
212 const QString layerSource { config.value( QStringLiteral(
"LayerSource" ) ).toString() };
213 if ( ! layerId.isEmpty() && ! layerName.isEmpty() && ! providerName.isEmpty() && ! layerSource.isEmpty() )
215 result.append(
QgsVectorLayerRef( layerId, layerName, layerSource, providerName ) );
224 if (
auto *lProject = context.
project() )
226 const QgsVectorLayer *referencedLayer = qobject_cast<QgsVectorLayer *>( lProject->mapLayer( config[QStringLiteral(
"Layer" )].toString() ) );
227 if ( referencedLayer )
229 int fieldIndex = referencedLayer->
fields().
indexOf( config.value( QStringLiteral(
"Key" ) ).toString() );
230 values = qgis::setToList( referencedLayer->
uniqueValues( fieldIndex, countLimit ) );
238 QStringList checkList;
239 if ( value.userType() == QMetaType::Type::QStringList )
241 checkList = value.toStringList();
245 QVariantList valuesList;
246 if ( value.userType() == QMetaType::Type::QString )
249 auto newVal { value };
250 if ( newVal.toString().trimmed().startsWith(
'{' ) )
255 else if ( newVal.toString().trimmed().startsWith(
'[' ) )
260 for (
auto &element : json::parse( newVal.toString().toStdString() ) )
262 if ( element.is_number_integer() )
264 valuesList.push_back( element.get<
int>() );
266 else if ( element.is_number_unsigned() )
268 valuesList.push_back( element.get<
unsigned>() );
270 else if ( element.is_string() )
272 valuesList.push_back( QString::fromStdString( element.get<std::string>() ) );
276 catch ( json::parse_error &ex )
278 QgsMessageLog::logMessage( QObject::tr(
"Cannot parse JSON like string '%1' Error: %2" ).arg( newVal.toString(), ex.what() ) );
282 else if ( value.userType() == QMetaType::Type::QVariantList )
284 valuesList = value.toList( );
287 checkList.reserve( valuesList.size() );
288 for (
const QVariant &listItem : std::as_const( valuesList ) )
290 QString v( listItem.toString( ) );
292 checkList.append( v );
302 QSet< QString > formVariables = qgis::listToSet( scope->variableNames() );
304 formVariables.intersect( usedVariables );
305 return formVariables;
311 QSet< QString > formVariables = qgis::listToSet( scope->variableNames() );
313 formVariables.intersect( usedVariables );
314 return formVariables;
329 QSet<QString> attributes;
333 const QSet<QString> formFunctions( qgis::listToSet( scope->functionNames() )
337 for (
const auto &f : expFunctions )
340 if ( formFunctions.contains( fd->
name( ) ) )
342 const QList<QgsExpressionNode *> cExpressionNodes { f->args( )->list() };
343 for (
const auto ¶m : std::as_const( cExpressionNodes ) )
345 attributes.insert( param->eval( &exp, &context ).toString() );
354 QSet<QString> attributes;
358 const QSet<QString> formFunctions( qgis::listToSet( scope->functionNames() )
362 for (
const auto &f : expFunctions )
365 if ( formFunctions.contains( fd->
name( ) ) )
367 const QList<QgsExpressionNode *> cExpressionNodes { f->args( )->list() };
368 for (
const auto ¶m : std::as_const( cExpressionNodes ) )
370 attributes.insert( param->eval( &exp, &context ).toString() );
382 for (
auto it = attrs.constBegin() ; it != attrs.constEnd(); it++ )
394 for (
auto it = parentAttrs.constBegin() ; it != parentAttrs.constEnd(); it++ )
396 if ( ! parentFeature.
attribute( *it ).isValid() )
408 config.value( QStringLiteral(
"LayerName" ) ).toString(),
409 config.value( QStringLiteral(
"LayerSource" ) ).toString(),
410 config.value( QStringLiteral(
"LayerProviderName" ) ).toString() };
@ NoGeometry
Geometry is not required. It may still be returned if e.g. required for a filter condition.
static QString nullRepresentation()
Returns the string 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)
Fetch next feature and stores in f, returns true on success.
This class wraps a request for features to a vector layer (or directly its vector data provider).
QgsFeatureRequest & setFlags(Qgis::FeatureRequestFlags 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.
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...
int fieldNameIndex(const QString &fieldName) const
Utility method to get attribute index from name.
bool isValid() const
Returns the validity of this feature.
Q_INVOKABLE QVariant attribute(const QString &name) const
Lookup attribute value by attribute name.
A context for field formatter containing information like the project.
QgsProject * project() const
Returns the project used in field formatter.
Container of fields for a vector layer.
Q_INVOKABLE int indexOf(const QString &fieldName) const
Gets the field index from the field name.
QgsField at(int i) const
Returns the field at particular index (must be in range 0..N-1).
Q_INVOKABLE int lookupField(const QString &fieldName) const
Looks up field's index from the field name.
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,...
static QgsProject * instance()
Returns the QgsProject singleton instance.
static bool isNull(const QVariant &variant, bool silenceNullWarnings=false)
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.
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.
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.