Drupal 8 custom form image field
To create a custom form with an image field in Drupal 8, you can follow these steps:
Define a custom form class by creating a new file, for example,
CustomForm.php
, in your custom module'ssrc/Form
directory.In the
CustomForm.php
file, define the form class and extend the Drupal\Core\Form\FormBase class. This will allow you to build the form using Drupal's form API. Here's an example:
<?php
namespace Drupal\your_module\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
class CustomForm extends FormBase {
public function getFormId() {
return 'custom_form';
}
public function buildForm(array $form, FormStateInterface $form_state) {
$form['image'] = [
'#type' => 'managed_file',
'#title' => $this->t('Image'),
'#upload_location' => 'public://images/',
'#upload_validators' => [
'file_validate_extensions' => ['png jpg jpeg'],
],
];
// Add other form elements as needed.
$form['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Submit'),
];
return $form;
}
public function submitForm(array &$form, FormStateInterface $form_state) {
// Handle form submission here.
}
}
- In your custom module's
.module
file, implementhook_menu()
to define a menu route for your form. Here's an example:
<?php
function your_module_menu() {
$items['your-module/form'] = [
'title' => 'Custom Form',
'page callback' => 'Drupal\your_module\Form\CustomForm::build',
'access callback' => TRUE, // or use a permission for access control
];
return $items;
}
Clear the Drupal cache to ensure the new route is recognized.
Access your custom form by visiting the defined route, such as
/your-module/form
, in your Drupal site. You should see the form with an image field.
That's it! Now you have a custom form with an image field in Drupal 8. You can customize the form and add more fields as needed. Remember to handle the form submission in the submitForm()
method of your form class.