I want to list out all invoice email templates in my custom module. I want to add one dropdown in my custom admin form.
List assume, you have form field like:
$fieldset->addField(
'invoice_template_id', 'select', [
'label' => __('Select Email Template'),
'title' => __('Select Email Template'),
'name' => 'invoice_template_id',
'required' => true,
'class' => 'selectopt',
/* 'css_class' => 'hidden', */
'values' => $this->getEmailTemplate()
]
);
and write function who can get collection of invoice custom email templates:
/**
Email Template List
* */
public function getEmailTemplate() {
$emailList = array();
$collection = $this->emailTemplateCollectionFactory->create();
foreach ($collection as $list) {
if (($list->getOrigTemplateCode() == "sales_email_invoice_template")) {
$emailList[$list->getTemplateId()] = $list->getTemplateCode();
} elseif (($list->getOrigTemplateCode() == "sales_email_invoice_comment_guest_template")) {
$emailList[$list->getTemplateId()] = $list->getTemplateCode();
} elseif ($list->getOrigTemplateCode() == "sales_email_invoice_comment_template") {
$emailList[$list->getTemplateId()] = $list->getTemplateCode();
}elseif ($list->getOrigTemplateCode() == "sales_email_invoice_guest_template") {
$emailList[$list->getTemplateId()] = $list->getTemplateCode();
}
}
return $emailList;
}
It will only return Invoice related custom template list.
Related
I have this form: https://greektoenglish.com/translation
After I complete the form, provide it with a file, and finally submit it, I get this error: "field is required". That the file field is required. But I already completed the field.
If I remove "'#required' => TRUE," from the code where the file upload field is declared, fill the form out, and submit it, then the form is submitted correctly.
How can I solve this?
This is my code:
<?php
namespace Drupal\submit_translation\Form;
use Drupal\Component\Utility\EmailValidatorInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Mail\MailManagerInterface;
use Drupal\mimemail\Utility\MimeMailFormatHelper;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* The example email contact form.
*/
class SubmitTranslation extends FormBase {
/**
* The email.validator service.
*
* #var \Drupal\Component\Utility\EmailValidatorInterface
*/
protected $emailValidator;
/**
* The language manager service.
*
* #var \Drupal\Core\Language\LanguageManagerInterface
*/
protected $languageManager;
/**
* The mail manager service.
*
* #var \Drupal\Core\Mail\MailManagerInterface
*/
protected $mailManager;
/**
* Constructs a new ExampleForm.
*
* #param \Drupal\Component\Utility\EmailValidatorInterface $email_validator
* The email validator service.
* #param \Drupal\Core\Language\LanguageManagerInterface $language_manager
* The language manager service.
* #param \Drupal\Core\Mail\MailManagerInterface $mail_manager
* The mail manager service.
*/
public function __construct(EmailValidatorInterface $email_validator, LanguageManagerInterface $language_manager, MailManagerInterface $mail_manager) {
$this->emailValidator = $email_validator;
$this->languageManager = $language_manager;
$this->mailManager = $mail_manager;
}
/**
* {#inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('email.validator'),
$container->get('language_manager'),
$container->get('plugin.manager.mail')
);
}
/**
* {#inheritdoc}
*/
public function getFormId() {
return 'submit_translation_form';
}
/**
* {#inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, $dir = NULL, $img = NULL) {
$form['intro'] = [
'#markup' => $this->t('Use this form to send us the document that we\'ll translate!'),
];
$form['from'] = [
'#type' => 'textfield',
'#title' => $this->t('Name'),
'#description' => $this->t("Your full name."),
'#required' => TRUE,
];
$form['from_mail'] = [
'#type' => 'textfield',
'#title' => $this->t('Email address'),
'#description' => $this->t("Your email address."),
'#required' => TRUE,
];
$form['params'] = [
'#tree' => TRUE,
'subject' => [
'#type' => 'textfield',
'#title' => $this->t('Title'),
'#description' => $this->t("The title of the document."),
'#required' => TRUE,
],
'count' => [
'#type' => 'textfield',
'#title' => $this->t('Word Count'),
'#description' => $this->t("The word count of the document."),
'#required' => TRUE,
],
'body' => [
'#type' => 'textarea',
'#title' => $this->t('Comments'),
'#description' => $this->t("Tell us if you have any special requirements."),
'#required' => TRUE,
],
// This form element forces plaintext-only email when there is no HTML
// content (that is, when the 'body' form element is empty).
'plain' => [
'#type' => 'hidden',
'#states' => [
'value' => [
':input[name="body"]' => ['value' => ''],
],
],
],
'attachments' => [
'#name' => 'files[attachment]',
'#type' => 'file',
'#title' => $this->t('Choose a file to send for translation.'),
'#required' => TRUE,
],
];
$form['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Send message'),
];
return $form;
}
/**
* {#inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
// Extract the address part of the entered email before trying to validate.
// The email.validator service does not work on RFC2822 formatted addresses
// so we need to extract the RFC822 part out first. This is not as good as
// actually validating the full RFC2822 address, but it is better than
// either just validating RFC822 or not validating at all.
$pattern = '/<(.*?)>/';
$address = $form_state->getValue('from_mail');
preg_match_all($pattern, $address, $matches);
$address = isset($matches[1][0]) ? $matches[1][0] : $address;
if (!$this->emailValidator->isValid($address)) {
$form_state->setErrorByName('from_mail', $this->t('That email address is not valid.'));
}
$file = file_save_upload('attachment', [ 'file_validate_extensions' => array('doc docx pdf')], 'temporary://', 0);
if ($file) {
$form_state->setValue(['params', 'attachments'], [['filepath' => $file->getFileUri()]]);
}
}
/**
* {#inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
// First, assemble arguments for MailManager::mail().
$module = 'submit_translation';
$key = "solon_key";
$to = "info#gexl.eu";
$langcode = $this->languageManager->getDefaultLanguage()->getId();
$params = $form_state->getValue('params');
$reply = "";
$send = TRUE;
$params['body'] .= " Count: " . $params['count'];
// Second, add values to $params and/or modify submitted values.
// Set From header.
if (!empty($form_state->getValue('from_mail'))) {
$params['headers']['From'] = MimeMailFormatHelper::mimeMailAddress([
'name' => $form_state->getValue('from'),
'mail' => $form_state->getValue('from_mail')
]);
}
elseif (!empty($form_state->getValue('from'))) {
$params['headers']['From'] = $from = $form_state->getValue('from');
}
else {
// Empty 'from' will result in the default site email being used.
}
// Handle empty attachments - we require this to be an array.
if (empty($params['attachments'])) {
$params['attachments'] = [];
}
// Remove empty values from $param['headers'] - this will force the
// the formatting mailsystem and the sending mailsystem to use the
// default values for these elements.
foreach ($params['headers'] as $header => $value) {
if (empty($value)) {
unset($params['headers'][$header]);
}
}
// Finally, call MailManager::mail() to send the mail.
$result = $this->mailManager->mail($module, $key, $to, $langcode, $params, $reply, $send);
if ($result['result'] == TRUE) {
$this->messenger()->addMessage($this->t('Your message has been sent.'));
}
else {
// This condition is also logged to the 'mail' logger channel by the
// default PhpMail mailsystem.
$this->messenger()->addError($this->t('There was a problem sending your message and it was not sent.'));
}
}
}
This happens because the form element '#type' => 'file' has no #value to validate. #required fields must have a #value set otherwise validation fails.
This is (now considered) a very old issue that has been fixed in Drupal 9.5.x, but this was assumed in the good old days of Drupal 7, as mentioned in the Form API reference :
#required: Indicates whether or not the element is required. This
automatically validates for empty fields, and flags inputs as
required. File fields are NOT allowed to be required.
So I guess the best solution is to upgrade to 9.5.x or above, if feasible, but as sometimes upgrading makes things complicated, you might prefer to review and apply the patch manually to your current code base.
[EDIT]: If still having issues after upgrade to >= 9.5.2,
Looking at the patch, a default valueCallback is now used to provide a #value to file form elements, but.. well there is another issue :
public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
if ($input === FALSE) {
return NULL;
}
$parents = $element['#parents'];
$element_name = array_shift($parents); # <- problem here :/
$uploaded_files = \Drupal::request()->files->get('files', []);
$uploaded_file = $uploaded_files[$element_name] ?? NULL;
if ($uploaded_file) {
// Cast this to an array so that the structure is consistent regardless of
// whether #value is set or not.
return (array) $uploaded_file;
}
return NULL;
}
See how it doesn't care about whether or not the element has a #name explicitly defined ? and whether or not #parents is a tree ? Now because of those wrong assumptions on the element's name and its parents, you are somehow forced to either :
Leave the #name property unset and refer to the file later on validation/submit as 'params' (the parents root) instead of 'attachment'. Or,
Stick with #tree => FALSE. Or,
Provide your own #value_callback (deprecated ...?)
I am using Drupal 9. I want to give the ability to the admin to place a block and select from the block a taxonomy term in which will filter a content type.
I did the above by creating a custom block with the taxonomy "Sponsor Type" as you can see the screenshot bellow.
Also I use views_embed_view to pass the taxonomy as an argument and filter the data using Contextual filters
Custom block code:
<?php
namespace Drupal\aek\Plugin\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Provides a 'SponsorsBlock' block.
*
* #Block(
* id = "sponsors_block",
* admin_label = #Translation("Sponsors"),
* )
*/
class SponsorsBlock extends BlockBase {
/**
* {#inheritdoc}
*/
public function defaultConfiguration() {
return [
"max_items" => 5,
] + parent::defaultConfiguration();
}
public function blockForm($form, FormStateInterface $form_state) {
$sponsors = \Drupal::entityTypeManager()
->getStorage('taxonomy_term')
->loadTree("horigoi");
$sponsorsOptions = [];
foreach ($sponsors as $sponsor) {
$sponsorsOptions[$sponsor->tid] = $sponsor->name;
}
$form['sponsor_types'] = [
'#type' => 'checkboxes',
'#title' => $this->t('Sponsor Type'),
'#description' => $this->t('Select from which sponsor type you want to get'),
'#options' => $sponsorsOptions,
'#default_value' => $this->configuration['sponsor_types'],
'#weight' => '0',
];
$form['max_items'] = [
'#type' => 'number',
'#title' => $this->t('Max items to display'),
'#description' => $this->t('Max Items'),
'#default_value' => $this->configuration['max_items'],
'#weight' => '0',
];
return $form;
}
/**
* {#inheritdoc}
*/
public function blockSubmit($form, FormStateInterface $form_state) {
$this->configuration['sponsor_types'] = $form_state->getValue('sponsor_types');
$this->configuration['max_items'] = $form_state->getValue('max_items');
}
/**
* {#inheritdoc}
*/
public function build() {
$selectedSponsorTypes = $this->configuration['sponsor_types'];
$cnxFilter = '';
foreach ($selectedSponsorTypes as $type) {
if ($type !== 0) {
$cnxFilter .= $type . ",";
}
}
return views_embed_view('embed_sponsors', 'default', $cnxFilter);
}
}
My issue now is how to limit the results. If you look above I have added an option "Max items to display" but using the Contextual filters I can't find any way to pass that argument to handle this.
If you use views_embed_view(), you will not be able to access the view object.
Load your view manually then you can set any properties before executing it:
use Drupal\views\Views;
public function build() {
$selectedSponsorTypes = $this->configuration['sponsor_types'];
$cnxFilter = '';
foreach ($selectedSponsorTypes as $type) {
if ($type !== 0) {
$cnxFilter .= $type . ",";
}
}
$view = Views::getView('embed_sponsors');
$display_id = 'default';
$view->setDisplay($display_id);
$view->setArguments([$cnxFilter]);
$view->setItemsPerPage($this->configuration['max_items']);
$view->execute();
return $view->buildRenderable($display_id);
}
In Sonata Admin is it possible to set or precompile a value in a form taking it from the query string?
I have a custom page with a calendar and when I click a date on the calendar I would like to be redirected to the create page of an event where the date is already set from the query string. Something like:
http://localhost:8000/admin/app/event/create?date=2017-07-11
I solved it by using the request service and a field marked as 'mapped' => false on my form builder:
protected function configureFormFields(FormMapper $formMapper)
{
$request = $this->getRequest();
$dateParameter = $request->query->get('date');
$date = null;
if ($dateParameter) {
$date = \DateTime::createFromFormat('!Y-m-d', $dateParameter);
}
if (!$date) {
$formMapper
->add('date', DatePickerType::class)
->add('calendarDate', HiddenType::class, array(
'data' => null,
'mapped' => false,
))
;
} else {
$formMapper
->add('date', DatePickerType::class, array(
'data' => $date,
'disabled' => true,
))
->add('calendarDate', HiddenType::class, array(
'data' => $date->format('Y-m-d'),
'mapped' => false,
))
;
}
$formMapper
// other fields
->add('other_field', ModelType::class)
;
}
Then, on the following method I am updating the entity field:
public function prePersist($myEntity)
{
$this->preUpdate($myEntity);
}
public function preUpdate($myEntity)
{
$dateString = $this->getForm()->get('calendarDate')->getData();
if ($dateString) {
$date = \DateTime::createFromFormat('!Y-m-d', $dateString);
if ($date) {
$myEntity->setDate($date);
}
}
}
In this way I can use my form with or without the query string parameter date:
http://localhost:8000/admin/app/event/24/edit?date=2017-07-01
And in the HTML I have this:
<input type="hidden" id="s59664a9ea44ce_calendarDate" name="s59664a9ea44ce[calendarDate]" class=" form-control" value="2017-07-01" />
P.S. when someone gives a -1 it should be nice to explain why...
I wrote a custom views handler, that mark message private to 0 or 1 or 2; any is value of hers label [MARK_READ,ARK_NEW,...] :
function mydevel_views_data() {
$data['mydevel']['table']['group'] = t('mydevel');
$data['mydevel']['table']['join'] = array(
// Exist in all views.
'#global' => array(),
);
$data['mydevel']['mydevel_isnewmessage'] = array(
'title' => t('is new message field'),
'help' => t('is new message field.'),
'field' => array(
'handler' => 'mydevel_handler_field_isnewmessage',
'click sortable' => TRUE,
),
'filter' => array(
'handler' => 'mydevel_handler_filter_isnewmessage',
),
);
and wrote a filed handler that work properly; message_mark function is wrote on mydevel module file and work currectly; if the message is new that filed label row by "now":
class mydevel_handler_field_isnewmessage extends views_handler_field_numeric {
var $field_alias = 'mydevel_field_isnewmessage';
function query() {
}
function option_definition() {
$options = parent::option_definition();
//dsm($this);
return $options;
}
function options_form(&$form, &$form_state) {
parent::options_form($form, $form_state);
}
function get_value($values, $field = NULL) {
return intval(message_mark($values->mid, $values->message_timestamp));
}
function render($values) {
$value = $this->get_value($values);
$value_theme = theme('mark', array('type' => $value));
return $value_theme;
}
}
Now, i want to write a views filter handler that filter on that filed on numeric mode [0 or 1 or 2] or on check list mode [all, read, new, updated]. but I don't want to overwite query function on filter handler and want to use from value that returned by this common handler filed (mydevel_handler_filter_isnewmessage) that added to views filed. can wrote this idea by extend the standard views handler? what i do my dears? I wrote this but not work: this is return error
class mydevel_handler_filter_isnewmessage extends views_handler_filter_numeric {
var $always_multiple = TRUE;
function option_definition() {
$options = parent::option_definition();
return $options;
}
function operators() {
$operators = parent::operators();
return $operators;
}
function query() {
}
}
tank you a lot.
How to limit the number of embedded form with the type "sonata_type_collection" ?
$formMapper->add('phones', 'sonata_type_collection',
array(
'required' => true,
'by_reference' => false,
'label' => 'Phones',
),
array(
'edit' => 'inline',
'inline' => 'table'
)
I would like limit to last five phones, I found only this solution for now, limit the display in the template twig "edit_orm_one_to_many", but i don't like that.
I found a solution by rewriting the edit action in the controller,
such in the documentation sonataAdminBundle I created my admin controller class:
class ContactAdminController extends Controller
{
public function editAction($id = null)
{
// the key used to lookup the template
$templateKey = 'edit';
$em = $this->getDoctrine()->getEntityManager();
$id = $this->get('request')->get($this->admin->getIdParameter());
// $object = $this->admin->getObject($id);
// My custom method to reduce the queries number
$object = $em->getRepository('GestionBundle:Contact')->findOneAllJoin($id);
if (!$object)
{
throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
}
if (false === $this->admin->isGranted('EDIT', $object))
{
throw new AccessDeniedException();
}
$this->admin->setSubject($object);
/** #var $form \Symfony\Component\Form\Form */
$form = $this->admin->getForm();
$form->setData($object);
// Trick is here ###############################################
// Method to find the X last phones for this Contact (x = limit)
// And set the data in form
$phones = $em->getRepository('GestionBundle:Phone')->findLastByContact($object, 5);
$form['phones']->setData($phones);
// #############################################################
if ($this->get('request')->getMethod() == 'POST')
{
$form->bindRequest($this->get('request'));
$isFormValid = $form->isValid();
// persist if the form was valid and if in preview mode the preview was approved
if ($isFormValid && (!$this->isInPreviewMode() || $this->isPreviewApproved()))
{
$this->admin->update($object);
$this->get('session')->setFlash('sonata_flash_success', 'flash_edit_success');
if ($this->isXmlHttpRequest())
{
return $this->renderJson(array(
'result' => 'ok',
'objectId' => $this->admin->getNormalizedIdentifier($object)
));
}
// redirect to edit mode
return $this->redirectTo($object);
}
// show an error message if the form failed validation
if (!$isFormValid)
{
$this->get('session')->setFlash('sonata_flash_error', 'flash_edit_error');
}
elseif ($this->isPreviewRequested())
{
// enable the preview template if the form was valid and preview was requested
$templateKey = 'preview';
}
}
$view = $form->createView();
// set the theme for the current Admin Form
$this->get('twig')->getExtension('form')->renderer->setTheme($view, $this->admin->getFormTheme());
return $this->render($this->admin->getTemplate($templateKey), array(
'action' => 'edit',
'form' => $view,
'object' => $object,
));
}
}