How update any fields on field_type?
Created 7 years ago by flexnst

My field_type is a map to select the location information contains 3 fields: "{field_name}", "{field_name}_lat", "{field_name}_lng". Main field {field_name} successfully saved, but I can not understand how to save values of the other two ( {field_name}_lat, {field_name}_lng). Can you help me, please? Im search documentation, but i see https://pyrocms.com/documentation/streams-platform/v1.1#addons/field-types-incomplete

ryanthompson  —  7 years ago Best Answer

Good question! This is something that the Geocoder Field Type could do for you (which is included in PRO) but to take from it's example:

Properties are just an array of columns it manages. This class is called an Accessor for the type and is responsible for accessing the data on the object (which in turn get's saved to DB).

<?php namespace Anomaly\GeocoderFieldType;

use Anomaly\Streams\Platform\Addon\FieldType\FieldTypeAccessor;

/**
 * Class GeocoderFieldTypeAccessor
 *
 * @link          http://anomaly.is/streams-platform
 * @author        AnomalyLabs, Inc. <hello@anomaly.is>
 * @author        Ryan Thompson <ryan@anomaly.is>
 * @package       Anomaly\GeocoderFieldType
 */
class GeocoderFieldTypeAccessor extends FieldTypeAccessor
{

    /**
     * Desired data properties.
     *
     * @var array
     */
    protected $properties = [
        'address',
        'formatted',
        'latitude',
        'longitude',
        'formatted_latitude',
        'formatted_longitude'
    ];

    /**
     * Set the value.
     *
     * @param $value
     * @return array
     */
    public function set($value)
    {
        $entry = $this->fieldType->getEntry();

        $attributes = $entry->getAttributes();

        if (is_array($value)) {
            foreach ($this->properties as $property) {
                $attributes[$this->fieldType->getColumnName() . '_' . $property] = array_pull($value, $property);
            }
        }

        if (is_null($value)) {
            foreach ($this->properties as $property) {
                $attributes[$this->fieldType->getColumnName() . '_' . $property] = $value;
            }
        }

        $entry->setRawAttributes($attributes);
    }

    /**
     * Get the value.
     *
     * @return array
     */
    public function get()
    {
        $entry = $this->fieldType->getEntry();

        $attributes = $entry->getAttributes();

        return array_combine(
            $this->properties,
            array_map(
                function ($property) use ($attributes) {
                    return array_get($attributes, $this->fieldType->getColumnName() . '_' . $property);
                },
                $this->properties
            )
        );
    }
}
flexnst  —  7 years ago

ryanthompson - Thank you very mutch!!