Changing field type
Created 8 years ago by kiltedup

Evening,

I have a field in a stream that was added as a text field type. Can anyone point me to the correct way to change the field type to be a textarea while preserving the entries that have already been added.

Ta,

Dave

ryanthompson  —  8 years ago

Right now there is no good way to do it. I have an open issue on Github and will be implementing it into the next version.

If it's a simple enough move you can do this manually.

  1. Find the field in your streams_fields table and update the type.
  2. Update the column type as needed.
  3. Run php artisan streams:compile to update your generated entry models.

Hope this helps!

kiltedup  —  8 years ago

Thanks Ryan,

Job for next week so will try what you suggested.

kiltedup  —  8 years ago

Boom!

That worked - cheers.

squatto  —  5 years ago

For those that come across this in the future, I was able to accomplish this by doing the following migration:

<?php

use Anomaly\Streams\Platform\Database\Migration\Migration;
use ProjectName\DataModule\Producer\Form\Options\ProducerRelationshipOptions;
use ProjectName\DataModule\Producer\ProducerModel;

class ProjectNameModuleDataChangeProducerIdFieldType extends Migration
{
    public function up()
    {
        // delete the existing (unused) "producer" field in the "data" namespace
        if ($field = $this->fields()->findBySlugAndNamespace('producer', 'data')) {
            $field->delete();
        }

        // change the slug and type of the existing "producer_id" field in the "data" namespace
        $this->fields()->findBySlugAndNamespace('producer_id', 'data')
             ->setAttribute('slug', 'producer')
             ->setAttribute('type', 'anomaly.field_type.relationship')
             ->setAttribute('config', [
                 'related' => ProducerModel::class,
                 'handler' => ProducerRelationshipOptions::class,
             ])
             ->save();
    }
}

I had to rename the field from producer_id to producer because using the field type anomaly.field_type.relationship causes the database field name to be the field slug plus _id. Had I not changed the slug to producer, Pyro would have renamed the underlying database field to producer_id_id (the slug producer_id plus _id).

The field originally had a type of anomaly.field_type.select which meant that the database field type was varchar(255). Changing the field type to anomaly.field_type.relationship thankfully coerced all of the string values into integer values in the database table, maintaining the relationships.

I should note that because I was changing the field's slug from producer_id to producer, I had to go through my entire codebase and change all field references. That was the only difficult part of this entire process!