{"id":19615439,"url":"https://github.com/droath/console-form","last_synced_at":"2026-05-16T03:05:20.983Z","repository":{"id":56972275,"uuid":"84260021","full_name":"droath/console-form","owner":"droath","description":"Symfony console form helper.","archived":false,"fork":false,"pushed_at":"2019-06-14T17:16:28.000Z","size":34,"stargazers_count":0,"open_issues_count":4,"forks_count":1,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-01-09T10:36:38.987Z","etag":null,"topics":["console","php","symfony"],"latest_commit_sha":null,"homepage":null,"language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/droath.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2017-03-08T00:25:47.000Z","updated_at":"2019-06-14T17:14:00.000Z","dependencies_parsed_at":"2022-08-21T07:10:18.313Z","dependency_job_id":null,"html_url":"https://github.com/droath/console-form","commit_stats":null,"previous_names":[],"tags_count":8,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/droath%2Fconsole-form","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/droath%2Fconsole-form/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/droath%2Fconsole-form/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/droath%2Fconsole-form/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/droath","download_url":"https://codeload.github.com/droath/console-form/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":240907401,"owners_count":19876686,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["console","php","symfony"],"created_at":"2024-11-11T10:56:48.031Z","updated_at":"2026-05-16T03:05:15.939Z","avatar_url":"https://github.com/droath.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Console Form\n\n[![Build Status](https://travis-ci.org/droath/console-form.svg?branch=master)](https://travis-ci.org/droath/console-form)\n\nA simple form solution when using the Symfony console component.\n\nThere are two ways forms can be created, one is using the standalone method which usually takes place in the command ***execute*** method.\n\nOr by taking advantage of the auto discovery feature so you can reuse forms throughout the project, which keeps the form logic decoupled from the command it's executed on.\n\n\n## Getting Started\n\nFirst, you'll need to download the console form library using composer:\n\n```bash\ncomposer require droath/console-form\n```\n\nSet the **\\Droath\\ConsoleForm\\FormHelper** as a helper class within the console application HelperSet:\n\n```php\n\u003c?php\n\n$application = new \\Symfony\\Component\\Console\\Application('Project-Demo', '0.0.1');\n\n$application-\u003egetHelperSet()\n    -\u003eset(new \\Droath\\ConsoleForm\\FormHelper());\n...\n```\n\n### Auto Discovery\n\nIf you decide to use the auto discovery feature you'll need to use the **\\Droath\\ConsoleForm\\FormDiscovery** class:\n\n```php\n\u003c?php\n...\n\n$formDiscovery = (new \\Droath\\ConsoleForm\\FormDiscovery())\n    -\u003ediscover(__DIR__ . '/Form', '\\Droath\\Project\\Form');\n\n$application-\u003egetHelperSet()\n    -\u003eset(new \\Droath\\ConsoleForm\\FormHelper($formDiscovery));\n...\n```\nThe **\\Droath\\ConsoleForm\\FormDiscovery::discover()** method takes two arguments, the first argument is either a single directory or an array or directories. These directories are searched for form classes that have implemented the **\\Droath\\ConsoleForm\\FormInterface** interface. The second argument is the class namespace.\n\nHere is an example of what the form class needs to implement so it's found by the auto discovery feature:\n\n```php\n\u003c?php\n\nnamespace Droath\\Project\\Form;\n\nuse Droath\\ConsoleForm\\Field\\BooleanField;\nuse Droath\\ConsoleForm\\Field\\SelectField;\nuse Droath\\ConsoleForm\\Field\\TextField;\nuse Droath\\ConsoleForm\\Form;\nuse Droath\\ConsoleForm\\FormInterface;\n\n/**\n * Define project setup form.\n */\nclass ProjectSetup implements FormInterface\n{\n    /**\n     * {@inheritdoc}\n     */\n    public function getName()\n    {\n        return 'project.form.setup';\n    }\n\n    /**\n     * {@inheritdoc}\n     */\n    public function buildForm()\n    {\n        return (new Form())\n            -\u003eaddField(new TextField('name', 'What is your name?'))\n            -\u003eaddField((new SelectField('gender', 'What is your gender?'))\n                -\u003esetOptions(['male', 'female', 'other']))\n            -\u003eaddField(new BooleanField('send_newletter', 'Email me the weekly newsletter'));\n    }\n}\n```\n\n### Form Basics\n\nInteracting with the form helper within the command class. Either you can create a form using the standalone method or retrieve the form using the name that was defined **(auto discovery needs to be implemented)**.\n\nFirst, I'll show you the standalone method on which you can create a form:\n\n```php\n\u003c?php\n\nnamespace Droath\\Project\\Command;\n\nuse Droath\\ConsoleForm\\Field\\BooleanField;\nuse Droath\\ConsoleForm\\Field\\SelectField;\nuse Droath\\ConsoleForm\\Field\\TextField;\nuse Droath\\ConsoleForm\\Form;\nuse Symfony\\Component\\Console\\Command\\Command;\nuse Symfony\\Component\\Console\\Input\\InputInterface;\nuse Symfony\\Component\\Console\\Output\\OutputInterface;\n\nclass Initialize extends Command\n{\n    /**\n     * {@inheritdoc}\n     */\n    public function configure()\n    {\n        $this\n            -\u003esetName('init')\n            -\u003esetDescription('Initialize project config.');\n    }\n\n    /**\n     * {@inheritdoc}\n     */\n    public function execute(InputInterface $input, OutputInterface $output)\n    {\n        $form = $this-\u003egetHelper('form')\n            -\u003egetForm($input, $output);\n\n        $form-\u003eaddFields([\n            (new TextField('project', 'Project name'))\n                -\u003esetDefault('Demo Project'),\n            (new SelectField('version', 'Project Version'))\n                -\u003esetOptions(['7.x', '8.x'])\n                -\u003esetDefault('8.x'),\n        ]);\n\n        $results = $form\n            -\u003eprocess()\n            -\u003egetResults();\n\n        var_dump($results)\n    }\n    ...\n```\n\nIf using **auto discovery** you can simply just retrieve the form by name:\n\n```php\n\u003c?php\n\nnamespace Droath\\Project\\Command;\n\nuse Droath\\ConsoleForm\\Field\\BooleanField;\nuse Droath\\ConsoleForm\\Field\\SelectField;\nuse Droath\\ConsoleForm\\Field\\TextField;\nuse Droath\\ConsoleForm\\Form;\nuse Symfony\\Component\\Console\\Command\\Command;\nuse Symfony\\Component\\Console\\Input\\InputInterface;\nuse Symfony\\Component\\Console\\Output\\OutputInterface;\n\nclass Initialize extends Command\n{\n    /**\n     * {@inheritdoc}\n     */\n    public function configure()\n    {\n        $this\n            -\u003esetName('init')\n            -\u003esetDescription('Initialize project config.');\n    }\n\n    /**\n     * {@inheritdoc}\n     */\n    public function execute(InputInterface $input, OutputInterface $output)\n    {\n        $form = $this-\u003egetHelper('form')\n            -\u003egetFormByName('project.form.setup', $input, $output);\n\n        $results = $form\n            -\u003eprocess()\n            -\u003egetResults();\n\n        var_dump($results)\n    }\n\n    ...\n```\n\n### Form Save\n\nMany of times forms need to save their results to a filesystem. The form save() method displays a confirmation message asking the user to save the results (which is configurable). If input is true, then the save callable is invoked; otherwise it's disregarded.\n\n```php\n\u003c?php\n\n...\n    $form\n        -\u003eaddFields([\n            (new TextField('project', 'Project name'))\n                -\u003esetDefault('Demo Project'),\n            (new SelectField('version', 'Project Version'))\n                -\u003esetOptions(['7.x', '8.x'])\n                -\u003esetDefault('8.x'),\n        ])\n        -\u003esave(function($results) {\n            // Save results to filesystem or remote source.\n            // Don't need to call process() as it's done inside the save method.\n        });\n```\n\n## Form Field Groups\n\nThere might come a time when you need to group fields together. One of the advantages would be having the ability to collect multiple inputs for a grouping of fields. As you can see in the example below, the `setLoopUntil()` provides the result array that was last given, these values can help determine if you should stop collecting data. Return `false` to stop field group iteration, otherwise set to `true`.\n\n```php\n\u003c?php\n...\n\n    $form-\u003eaddFields([\n        (new TextField('name', 'Project Name')),\n        (new FieldGroup('environments'))\n            -\u003eaddFields([\n                (new TextField('ssh_label', 'SSH Label'))\n                    -\u003esetRequired(false),\n                (new TextField('ssh_host', 'SSH Host'))\n                    -\u003esetRequired(false),\n                (new Textfield('ssh_uri', 'SSH URI'))\n                    -\u003esetRequired(false)\n            ])\n            -\u003esetLoopUntil(function($result) {\n                if (!isset($result['ssh_label'])) {\n                    return false;\n                }\n                return true;\n            })\n    ]);\n\n    $results = $form\n        -\u003eprocess()\n        -\u003egetResults();\n```\n\n## Form Fields\n\nThere are three basic field types which are:\n\n- Text\n- Select\n- Boolean\n\nAll field types derive from the base field class, so most fields have similar methods and features.\n\nBelow are some examples of the most useful field methods:\n\n### Condition\n\nThe setCondition() method allows a field to be shown based on what value was previously inputted by the user. This method can be set multiple times if you require more conditions to be met for a given field.\n\n```php\n\u003c?php\n...\n    $form\n        -\u003eaddFields([\n            (new TextField('project', 'Project name'))\n                -\u003esetDefault('Demo Project'),\n            (new SelectField('version', 'Project Version'))\n                -\u003esetOptions(['7.x', '8.x'])\n                -\u003esetDefault('8.x'),\n            (new TextField('another_option', 'More options for 7.x version'))\n                -\u003esetCondition('version', '7.x'),\n        ]);\n\n    $results = $form\n        -\u003eprocess()\n        -\u003egetResults();\n```\n\nThe \"More options for 7.x version\" text field will only be shown if the 7.x version was selected in the previous question.\n\n### Field Callback\n\nThe setFieldCallback() method requires a single callback function, which can be any valid PHP callable. The callback will be invoked during the form process lifecycle. The field callback receives two arguments, the first argument is the field instance. The second is an array of results for all previous questions.\n\nNow you can set additional methods for a given field instance based on the results for a previous question(s). As you can see in the example below the select options are added based on the results retrieved from the \"Project Name\" text field.\n\n```php\n\u003c?php\n...\n\n    $form\n        -\u003eaddFields([\n            (new TextField('name', 'Project Name')),\n            (new SelectField('version', 'Project Version'))\n                -\u003esetFieldCallback(function ($field, $results) {\n                    if ($results['name'] === 'My Project') {\n                        $field-\u003esetOptions([\n                            '7' =\u003e '7x',\n                            '8' =\u003e '8x'\n                        ]);\n                    } else {\n                        $field-\u003esetOptions([\n                            '11' =\u003e '11x',\n                            '12' =\u003e '12x'\n                        ]);\n                    }\n                }),\n        ]);\n\n```\n\n\n### Subform\n\nThe setSubform() method requires a callback function to be set, which can be an anonymous function or any valid PHP callable. The subform function is invoked during the original form process lifecycle.\n\nThe subform callable is given two arguments, the first argument is the subform instance and the second is the inputed value. The callable doesn't need to return any data. Also, the original form process takes care of processing the subform.\n\n```php\n\u003c?php\n...\n\n    $form\n        -\u003eaddFields([\n            (new BooleanField('questions', 'Ask questions?'))\n                -\u003esetSubform(function ($subform, $value) {\n                    if ($value === true) {\n                        $subform-\u003eaddFields([\n                            (new TextField('how_old', 'How old are you?')),\n                            (new TextField('location', 'Where do you live?')),\n                        ]);\n                    }\n                }),\n        ]);\n\n        $results = $form\n            -\u003eprocess()\n            -\u003egetResults();\n\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdroath%2Fconsole-form","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdroath%2Fconsole-form","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdroath%2Fconsole-form/lists"}