How to create a new workflow in Symfony?

by aniya.jaskolski , in category: PHP Frameworks , 2 years ago

How to create a new workflow in Symfony?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by darion , 2 years ago

@aniya.jaskolski 

To create a new workflow in Symfony, you can follow these steps:

  1. Install the Workflow component:
1
composer require symfony/workflow


  1. Define the workflow in a YAML file. For example, create a file named my_workflow.yaml in the config/packages directory with the following content:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
framework:
    workflows:
        my_workflow:
            type: workflow
            marking_store:
                type: single_state
                arguments: ['current_place']
            supports:
                - AppEntityMyEntity
            places:
                - draft
                - review
                - published
            transitions:
                submit:
                    from: draft
                    to: review
                approve:
                    from: review
                    to: published


In this example, we define a workflow named my_workflow that can be applied to instances of the AppEntityMyEntity class. The workflow has three places: draft, review, and published. The marking_store configuration defines that the workflow has a single current state, stored in the current_place property of the entity. The transitions configuration defines two possible transitions: submit, which moves the entity from draft to review, and approve, which moves the entity from review to published.

  1. Load the workflow configuration in your application by importing the my_workflow.yaml file in your config/routes.yaml file:
1
2
workflows:
    - { resource: '../config/packages/my_workflow.yaml' }


  1. Use the workflow in your code. For example, to apply the submit transition to a MyEntity instance:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
use SymfonyComponentWorkflowRegistry;

class MyController
{
    public function submitAction($id, Registry $workflowRegistry)
    {
        $myEntity = $entityManager->getRepository(MyEntity::class)->find($id);
        $workflow = $workflowRegistry->get($myEntity);
        $workflow->apply($myEntity, 'submit');
        $entityManager->flush();

        // ...
    }
}


In this example, we retrieve the MyEntity instance with the specified ID from the database, get the workflow associated with the entity using the Registry service, and apply the submit transition to the entity. Finally, we persist the changes to the database using the entity manager.