Nice use case for Layer Actions.
Just configure a new layer action like this:
Code for the layer action:
from qgis.core import QgsProject
from qgis.utils import iface
field_name = "etiqueta" # CHANGE THIS TO YOUR OWN FIELD NAME
layer = QgsProject.instance().mapLayer("[% @layer_id %]")
idx = layer.fields().indexOf(field_name)
if layer.selectedFeatureCount():
params = QgsAggregateCalculator.AggregateParameters()
params.delimiter = ','
value = layer.aggregate(
QgsAggregateCalculator.StringConcatenateUnique,
field_name, params, fids=layer.selectedFeatureIds())[0]
for fid in layer.selectedFeatureIds():
layer.changeAttributeValue(fid, idx, value)
iface.messageBar().pushSuccess("Concatenate unique", "Done!")
else:
iface.messageBar().pushInfo("Concatenate unique", "First select some features...")
Notes:
- You just need to change the
field_name
variable to match your field name and you're done.
- The layer action will be available in editing mode. It won't be saved until you click on
Save Layer Edits
.
Below the code for concatenating several fields at once:
from qgis.core import QgsProject
from qgis.utils import iface
field_names = ["my_field_1", "my_field_2"] # CHANGE THIS TO YOUR OWN FIELD NAMES
layer = QgsProject.instance().mapLayer("[% @layer_id %]")
field_dict = {layer.fields().indexOf(fn): fn for fn in field_names}
if layer.selectedFeatureCount():
params = QgsAggregateCalculator.AggregateParameters()
params.delimiter = ','
attr_map = dict()
for idx, field_name in field_dict.items():
value = layer.aggregate(
QgsAggregateCalculator.StringConcatenateUnique,
field_name, params, fids=layer.selectedFeatureIds())[0]
attr_map[idx] = value
for fid in layer.selectedFeatureIds():
layer.changeAttributeValues(fid, attr_map)
iface.messageBar().pushSuccess("Concatenate unique", "Done!")
else:
iface.messageBar().pushInfo("Concatenate unique", "First select some features...")
Aggregate
could help, see: gis.stackexchange.com/a/395730/88814