1

I have added datepicker in magento2 backend form using following code.

protected function _prepareForm()
{
$fieldset->addField(
        'date_started',
        'date',
        [
            'name' => 'date_started',
            'label' => __('Start Time'),
            'date_format' => $dateFormat,
            'class' => 'validate-date validate-date-range date-range-task_data-from',
            'class' => 'required-entry',
            'style' => 'width:200px'
        ]
    );
$fieldset->addField(
        'date_completed',
        'date',
        [
            'name' => 'date_completed',
            'label' => __('End Time'),
            'date_format' => $dateFormat,
            'class' => 'validate-date validate-date-range date-range-task_data-from',
            'class' => 'required-entry',
            'style' => 'width:200px',
        ]
    );
}

but this is not validating the date range.

I need to validate: date_started should be minimum today and the date_completed should be greater than date_started.

I have seen follwoing question Start and End Date Validation but it is for Magento 1.

I also have seen the documentation Date and Time Selector, Calendar widget but it is not useful for it.

My Form.php

<?php

namespace Vendor\Module\Block\Adminhtml\Task\Edit;


/**
 * Adminhtml Add New Task Form.
 */
class Form extends \Magento\Backend\Block\Widget\Form\Generic
{
/**
 * @var \Magento\Store\Model\System\Store
 */
protected $_systemStore;

/**
 * @param \Magento\Backend\Block\Template\Context $context
 * @param \Magento\Framework\Registry             $registry
 * @param \Magento\Framework\Data\FormFactory     $formFactory
 * @param array                                   $data
 */
public function __construct(
    \Magento\Backend\Block\Template\Context $context,
    \Magento\Framework\Registry $registry,
    \Magento\Framework\Data\FormFactory $formFactory,
    \Magento\Cms\Model\Wysiwyg\Config $wysiwygConfig,
    \Vendor\Module\Model\Taskstatus $options,
    array $data = []
) 
{
    $this->_options = $options;
    $this->_wysiwygConfig = $wysiwygConfig;
    parent::__construct($context, $registry, $formFactory, $data);
}

/**
 * Prepare form.
 *
 * @return $this
 */
protected function _prepareForm()
{
    $dateFormat = $this->_localeDate->getDateFormat(\IntlDateFormatter::SHORT);
    $model = $this->_coreRegistry->registry('task_data');

    $form = $this->_formFactory->create(
        ['data' => [
                        'id' => 'edit_form', 
                        'enctype' => 'multipart/form-data', 
                        'action' => $this->getData('action'), 
                        'method' => 'post'
                    ]
        ]
    );

    $form->setHtmlIdPrefix('vmtask_');
    if ($model->getTaskId()) {
        $fieldset = $form->addFieldset(
            'base_fieldset',
            ['legend' => __('Edit Task Data'), 'class' => 'fieldset-wide']
        );
        $fieldset->addField('task_id', 'hidden', ['name' => 'task_id']);
    } else {
        $fieldset = $form->addFieldset(
            'base_fieldset',
            ['legend' => __('Add Task Data'), 'class' => 'fieldset-wide']
        );
    }

    $fieldset->addField(
        'task_name',
        'text',
        [
            'name' => 'task_name',
            'label' => __('Task Name'),
            'id' => 'task_name',
            'title' => __('Task Name'),
            'class' => 'required-entry',
            'required' => true,
        ]
    );

    $wysiwygConfig = $this->_wysiwygConfig->getConfig(['tab_id' => $this->getTabId()]);

    $fieldset->addField(
        'task_description',
        'editor',
        [
            'name' => 'task_description',
            'label' => __('Task Description'),
            'style' => 'height:36em;',
            'required' => true,
            'config' => $wysiwygConfig
        ]
    );


    $fieldset->addField(
        'date_started',
        'date',
        [
            'name' => 'date_started',
            'label' => __('Start Time'),
            'date_format' => $dateFormat,
            'class' => 'validate-date validate-date-range date-range-task_data-from',
            'class' => 'required-entry',
            'style' => 'width:200px',
            'datePickerOptions'=> array(
                        'maxDate'=> 'new Date()'
                        )
        ]
    )->setAfterElementHtml("<script type=\"text/javascript\">
    //<![CDATA[
      require([
      'jquery',
      'mage/calendar'
        ], function($){
               $('#date_started').calendar({           
               hideIfNoPrevNext: true,
               minDate: new Date(),
               showOn: 'button',
            });
        });         
    //]]>
    </script>");
    $fieldset->addField(
        'date_completed',
        'date',
        [
            'name' => 'date_completed',
            'label' => __('End Time'),
            'date_format' => $dateFormat,
            'class' => 'validate-date validate-date-range date-range-task_data-from',
            'class' => 'required-entry',
            'style' => 'width:200px',
        ]
    )->setAfterElementHtml("<script type=\"text/javascript\">
    //<![CDATA[
      require([
      'jquery',
      'mage/calendar'
        ], function($){
        $('#date_completed').click(function(event) {
            var maxD = $('#date_started').value();
               $('#date_completed').calendar({           
               hideIfNoPrevNext: true,
               minDate: maxD,
               showOn: 'button'

            });    });
            });
    //]]>
    </script>");

    $form->setValues($model->getData());
    $form->setUseContainer(true);
    $this->setForm($form);

    return parent::_prepareForm();
}

}

Thanks

4
  • Have you got solution? Sep 26, 2018 at 8:37
  • Nope. Instead, I have added server-side validation for the backend. Have you found something?
    – Knight017
    Sep 26, 2018 at 9:15
  • No. it's working fine for me. i don't understand problem :) any way this is for you +1. Sep 26, 2018 at 9:26
  • Thanks, I'll check it in vanilla Magento 2 as I get some time.
    – Knight017
    Sep 26, 2018 at 9:52

2 Answers 2

1

Even if the question is old, today I needed to implement a date range validation in Magento 2 and ended up using the uiComponent xml declaration rule validate-date-range to accomplish the task, so having two date fields you would use it like this:

        <field name="from_time" sortOrder="30" formElement="date">
            <settings>
                <validation>
                    <rule name="validate-datetime" xsi:type="boolean">true</rule>
                </validation>
            </settings>
        </field>

        <field name="to_time" sortOrder="40" formElement="date">
            <settings>
                <validation>
                    <rule name="validate-datetime" xsi:type="boolean">true</rule>
                    <rule name="validate-date-range" xsi:type="string">from_time</rule>
                </validation>
            </settings>
        </field>

Please note that the name passed to the rule is the from_time field name, this settings will display a message to the user before submitting the form, as soon as the to_time field is populated: enter image description here

0

Use ->setAfterElementHtml to fieldset.

$fieldsetDirector->addField(
        'date_started',
        'date',
        [
            'name' => 'date_started',
            'label' => __('Start Time'),
            'date_format' => 'yyyy-MM-dd',                
            'class' => 'required-entry',
            'style' => 'width:200px'
        ]
    )->setAfterElementHtml("<script type=\"text/javascript\">
        //<![CDATA[
          require([
          'jquery',
          'mage/calendar'
            ], function($){
                   $('#date_started').calendar({           
                   hideIfNoPrevNext: true,
                   minDate: new Date(),
                   showOn: 'button',
                   dateFormat: 'yyyy-MM-dd'
                });    });         
        //]]>
        </script>");
    $fieldsetDirector->addField(
        'date_completed',
        'date',
        [
            'name' => 'date_completed',
            'label' => __('End Time'),
            'date_format' => 'yyyy-MM-dd',                
            'class' => 'required-entry',
            'style' => 'width:200px',
        ]
    )->setAfterElementHtml("<script type=\"text/javascript\">
        //<![CDATA[
          require([
          'jquery',
          'mage/calendar'
            ], function($){
            $('#date_completed').click(function(event) {
                var maxD = 'Find Start date field value';
                   $('#date_completed').calendar({           
                   hideIfNoPrevNext: true,
                   minDate: maxD,
                   showOn: 'button',
                   dateFormat: 'yyyy-MM-dd'
                });    });
                });
        //]]>
        </script>");

Note : For date_completed field validation you have to find date_started field value and set value in date_completed field minDate.

7
  • tried but not working, the script is append after datepicker button.
    – Knight017
    Aug 29, 2018 at 14:34
  • Can you share your code so i can check it. Aug 30, 2018 at 4:48
  • @Knight017 have you changed $fieldsetDirector to $fieldset ? Aug 30, 2018 at 5:10
  • You mean to say $fieldset to $fieldsetDirector?, by the way i have updated my code.
    – Knight017
    Aug 30, 2018 at 5:28
  • @Knight017 just copy and past my code, then date_started field hide previous day from today and for date_completed field you need to get the value of date_started field and set that value to var maxD Make sure date format is same as like new Date() Aug 30, 2018 at 5:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.