class FileExampleReadWriteForm

File test form class.

Hierarchy

Expanded class hierarchy of FileExampleReadWriteForm

1 string reference to 'FileExampleReadWriteForm'
file_example.routing.yml in modules/file_example/file_example.routing.yml
modules/file_example/file_example.routing.yml

File

modules/file_example/src/Form/FileExampleReadWriteForm.php, line 17

Namespace

Drupal\file_example\Form
View source
class FileExampleReadWriteForm extends FormBase {
    
    /**
     * Constructs a new FileExampleReadWriteForm object.
     *
     * @param \Drupal\file_example\FileExampleStateHelper $stateHelper
     *   The file example state helper.
     * @param \Drupal\file_example\FileExampleSubmitHandlerHelper $submitHandlerHelper
     *   The file example submit handler helper.
     * @param \Drupal\Core\File\FileSystemInterface $fileSystem
     *   The file system.
     *
     * @see https://php.watch/versions/8.0/constructor-property-promotion
     */
    public function __construct(FileExampleStateHelper $stateHelper, FileExampleSubmitHandlerHelper $submitHandlerHelper, FileSystemInterface $fileSystem) {
    }
    
    /**
     * {@inheritdoc}
     */
    public static function create(ContainerInterface $container) {
        $instance = new static($container->get('file_example.state_helper'), $container->get('file_example.submit_handler_helper'), $container->get('file_system'));
        return $instance;
    }
    
    /**
     * Returns a unique string identifying the form.
     *
     * @return string
     *   The unique string identifying the form.
     */
    public function getFormId() {
        return 'file_example_read_write';
    }
    
    /**
     * {@inheritdoc}
     */
    public function buildForm(array $form, FormStateInterface $form_state) {
        $default_file = $this->stateHelper
            ->getDefaultFile();
        $default_directory = $this->stateHelper
            ->getDefaultDirectory();
        $form['description'] = [
            '#markup' => $this->t('This form demonstrates the Drupal file API. Experiment with the form, and then look at the submit handlers in the code to understand the file API.'),
        ];
        $form['write_file'] = [
            '#type' => 'fieldset',
            '#title' => $this->t('Write to a file'),
        ];
        $form['write_file']['write_contents'] = [
            '#type' => 'textfield',
            '#title' => $this->t('Enter something you would like to write to a file'),
            '#default_value' => $this->t('Put some text here or just use this text'),
        ];
        $form['write_file']['destination'] = [
            '#type' => 'textfield',
            '#default_value' => $default_file,
            '#title' => $this->t('Optional: Enter the streamwrapper saying where it should be written'),
            '#description' => $this->t('This may be public://some_dir/test_file.txt or private://another_dir/some_file.txt, for example. If you include a directory, it must already exist. The default is "public://". Since this example supports session://, you can also use something like session://somefile.txt.'),
        ];
        $form['write_file']['managed_submit'] = [
            '#type' => 'submit',
            '#value' => $this->t('Write managed file'),
            '#submit' => [
                [
                    $this->submitHandlerHelper,
                    'handleManagedFile',
                ],
            ],
        ];
        $form['write_file']['unmanaged_submit'] = [
            '#type' => 'submit',
            '#value' => $this->t('Write unmanaged file'),
            '#submit' => [
                [
                    $this->submitHandlerHelper,
                    'handleUnmanagedFile',
                ],
            ],
        ];
        $form['write_file']['unmanaged_php'] = [
            '#type' => 'submit',
            '#value' => $this->t('Unmanaged using PHP'),
            '#submit' => [
                [
                    $this->submitHandlerHelper,
                    'handleUnmanagedPhp',
                ],
            ],
        ];
        $form['fileops'] = [
            '#type' => 'fieldset',
            '#title' => $this->t('Read from a file'),
        ];
        $form['fileops']['fileops_file'] = [
            '#type' => 'textfield',
            '#default_value' => $default_file,
            '#title' => $this->t('Enter the URI of a file'),
            '#description' => $this->t('This must be a stream-type description like public://some_file.txt or http://drupal.org or private://another_file.txt or (for this example) session://yet_another_file.txt.'),
        ];
        $form['fileops']['read_submit'] = [
            '#type' => 'submit',
            '#value' => $this->t('Read the file and store it locally'),
            '#submit' => [
                [
                    $this->submitHandlerHelper,
                    'handleFileRead',
                ],
            ],
        ];
        $form['fileops']['delete_submit'] = [
            '#type' => 'submit',
            '#value' => $this->t('Delete file'),
            '#submit' => [
                [
                    $this->submitHandlerHelper,
                    'handleFileDelete',
                ],
            ],
        ];
        $form['fileops']['check_submit'] = [
            '#type' => 'submit',
            '#value' => $this->t('Check to see if file exists'),
            '#submit' => [
                [
                    $this->submitHandlerHelper,
                    'handleFileExists',
                ],
            ],
        ];
        $form['directory'] = [
            '#type' => 'fieldset',
            '#title' => $this->t('Create or prepare a directory'),
        ];
        $form['directory']['directory_name'] = [
            '#type' => 'textfield',
            '#title' => $this->t('Directory to create/prepare/delete'),
            '#default_value' => $default_directory,
            '#description' => $this->t('This is a directory as in public://some/directory or private://another/dir.'),
        ];
        $form['directory']['create_directory'] = [
            '#type' => 'submit',
            '#value' => $this->t('Create directory'),
            '#submit' => [
                [
                    $this->submitHandlerHelper,
                    'handleDirectoryCreate',
                ],
            ],
        ];
        $form['directory']['delete_directory'] = [
            '#type' => 'submit',
            '#value' => $this->t('Delete directory'),
            '#submit' => [
                [
                    $this->submitHandlerHelper,
                    'handleDirectoryDelete',
                ],
            ],
        ];
        $form['directory']['check_directory'] = [
            '#type' => 'submit',
            '#value' => $this->t('Check to see if directory exists'),
            '#submit' => [
                [
                    $this->submitHandlerHelper,
                    'handleDirectoryExists',
                ],
            ],
        ];
        $form['debug'] = [
            '#type' => 'fieldset',
            '#title' => $this->t('Debugging'),
        ];
        $form['debug']['show_raw_session'] = [
            '#type' => 'submit',
            '#value' => $this->t('Show raw $_SESSION contents'),
            '#submit' => [
                [
                    $this->submitHandlerHelper,
                    'handleShowSession',
                ],
            ],
        ];
        $form['debug']['reset_session'] = [
            '#type' => 'submit',
            '#value' => $this->t('Reset the Session'),
            '#submit' => [
                [
                    $this->submitHandlerHelper,
                    'handleResetSession',
                ],
            ],
        ];
        return $form;
    }
    
    /**
     * {@inheritdoc}
     */
    public function validateForm(array &$form, FormStateInterface $form_state) {
        $destination = $form_state->getValue('destination');
        if (!$destination) {
            $form_state->setError($form['write_file']['destination'], $this->t('You must enter a destination.'));
            return;
        }
        $filename = $this->fileSystem
            ->basename($destination);
        if (!$filename) {
            $form_state->setError($form['write_file']['destination'], $this->t('The destination %destination is not valid.', [
                '%destination' => $destination,
            ]));
            return;
        }
        // For security reasons, we only allow writing to the .txt file.
        if (!str_ends_with($destination, '.txt')) {
            $form_state->setError($form['write_file']['destination'], $this->t("The .txt file is only permitted for the purpose of ensuring the security of the example."));
        }
    }
    
    /**
     * {@inheritdoc}
     */
    public function submitForm(array &$form, FormStateInterface $form_state) {
        // Intentionally left empty.
    }

}

Members

Title Sort descending Modifiers Object type Summary Overriden Title Overrides
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FileExampleReadWriteForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
FileExampleReadWriteForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
FileExampleReadWriteForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
FileExampleReadWriteForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
FileExampleReadWriteForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
FileExampleReadWriteForm::__construct public function Constructs a new FileExampleReadWriteForm object.
FormBase::$configFactory protected property The config factory. 3
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 3
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user. 2
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route.
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 16
MessengerTrait::messenger public function Gets the messenger. 16
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 2
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 3
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.