Magento admin form time field - forms

I am trying to add a time field to an admin form but it does not work:
$fieldset->addField('sched_time', 'time', array(
'label' => Mage::helper('servicemanager')->__('Scheduled Time'),
'style' => 'width:45px',
'class' => 'required-entry',
'required' => true,
'name' => 'sched_time',
'value' => '09,00,00',
));
The problems are as follows:
The data isn't getting stored in the database ('sched_time' is a mysql time field)
'value' doesn't do anything. I need the default value to be set to 09:00:00 (9am)
Reference: http://www.excellencemagentoblog.com/magento-admin-form-field

You need to write some code manually in your controller's saveAction() method which might look like:
public function saveAction(){
$id = $this->getRequest()->getParam('id');
$model = Mage::getModel('module/model')->load($id);
$time = $this->getRequest()->getParam('sched_time');
$sched_time = $time[0] . ':' . $time[1] . ':' . $time[2]; //HH:MM:SS
$model->setData('sched_time', $sched_time);
$model->save();
}
Hope this will help future visitors!

You need to make an observer, after hours trying to find this myself I came across this link magento weight attribute without decimal points
Hope this helps as it helped me

Related

zf2 Form Validator DateTime dateInvalidDate

Trying to use a DateTime Form element in ZF2 and cannot valid the form.
$inputFilter->add(array(
'name' => 'event_datetime',
'required' => true,
'filters' => array(
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 0,
'max' => 20,
),
),
),
));
Using this on the .phtml file.
<?php $formElement = $form->get('event_datetime');?>
<dt><?php echo $this->formLabel($formElement);?></dt>
<dd><?php echo $this->formDateTimeLocal($formElement);?>
<?php echo $this->formElementErrors($formElement);?>
NOTE: using formDateTimeLocal instead of formDateTime as the latter does not show the HTML5 elements.
Using Chrome the HTML5 DateTimeLocal field appears with a calendar and Time section.
When running $form->isValid() I receive: (var_dump($form->getMessages()))
array (size=1) 'event_datetime' => array (size=1) 'dateInvalidDate' => string 'The input does not appear to be a valid date' (length=44)
The getRequest->getPost() = public 'event_datetime' => string '2015-08-10T03:00' (length=16)
I've tried to split this field into 2: a Date and a Time field as separate variables. This works correctly for the Date BUT not for the Time element.
Reading around I've noticed this: ZF2 validating date and time format PT_BR always The input does not appear to be a valid date which does not help as I need the time component. (obviously I have looked at more than just 1 link but my rep on SO allows only 1 url in post.)
I've also read that Chrome and Opera cut off the 'seconds' part of the time field....
How to I validate either a \Zend\Form\Element\DateTime field or just the \Zend\Form\Element\Time for field...
I've tried to manually glue these together, add the :00 seconds part of the string to Time but to no effect.
If I set the input filter to 'required' => false I still receive the dateInvalidDate validator for for attempts: DateTime and Time...
So, the question is:
How do I validate a DateTime or Time field using Zf2 form elements and inputFilters. Following the Docs and example don't seem to work for me and manually creating the Time string also has the same issue.
Try this:
$inputFilter->add(array(
'type' => 'Zend\Form\Element\DateTimeLocal',
'name' => 'event_datetime',
'required' => true,
'options' => array(
'label' => 'Appointment Date',
'format' => 'Y-m-d\TH:i'
),
'filters' => array(
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 0,
'max' => 20,
),
),
),
));
You get the error, because the datetime string/format you pass is different than the expected datetime format by default. Try playing with 'format' => 'Y-m-d\TH:i' to get the result.
Taken directly from Zend documentation. It's all the same, but with a different element.
use Zend\Form\Element;
use Zend\Form\Form;
$time = new Element\Time('time');
$time
->setLabel('Time')
->setAttributes(array(
'min' => '00:00:00',
'max' => '23:59:59',
'step' => '60', // seconds; default step interval is 60 seconds
))
->setOptions(array(
'format' => 'H:i:s'
));
$form = new Form('my-form');
$form->add($time);
My original issue was validation. The suggestion by Stanimir did help and the dateTimeLocal format has great in pointing me in the right direction.
The whole issue was with the 'format' value.
My main problem was that when populating the \Zend\Form\Element\Time field the format was H:i:s but the HTML5 form only submitted H:i. (also due to my 'format' setting which is OK)
So, when populating the form the DB field returned H:i:s which populated the form correctly BUT on submission failed IF I didn't edit the Time field.
THEREFORE: the answer to this questions is basically make sure the format submitted [and $form->bind($object), $form->setData($post) etc] is EXACTLY the same as the form element definition [H:i != H:i:s] and when pulling from database format to correspond to your required setting.
var_dump($form->get('valid_to_time')->getFormat());
var_dump($form->get('valid_to_time')->getValue());
Once this is the same all will be well and you can split DateTime fields into individual Date and Time (or use DateTime as above).
Sounds simple but this was a headache to get right.

Setting a drupal entity date field without EMW

Is it possible to set a date field (capturing a start and end time) on a drupal entity WITHOUT using entity metadatawrapper?
with EWM I could do (with a corresponding ->save() after, of course)
$wrapper->field_custom_date->set(array(
'value' => $date_start_value,
'value2' => $date_end_value,
));
I've tried
$entity->field_custom_date = array(LANGUAGE_NONE => array(0 => array(
'value' => $date_start_value,
'value2' => $date_start_value,
)));
and a few other very similar variations to no avail. I've tried Googling but I can only find solutions and examples using EMW. Is this possible or do I have to use the entity metadata wrapper?
Thanks!
Try this
$entity->field_custom_date[LANGUAGE_NONE][0]['value'] = $date_start_value;
$entity->field_custom_date[LANGUAGE_NONE][0]['value2'] = $date_end_value;

populate id from database in select box option value in zend framework

hi I am new in zend framework Basically I want to populate company name list from the database. Actually I have doen it but i want to also populate its id in option box
example
select
option value='1'> tcs option
select
this is my code
Application_Form_Clientcompanyform extends Zend_Form
$company_list = new Application_Model_Clientcompany;
$showlist = $company_list->companyNameList();
$list=array();
$id=array();
foreach($showlist as $key => $value)
{
$list[]=$value['companyName'];
$id[]=$value['id'];
}
$this->addElement('select', 'companyName', array(
'required' => true,
'filters' => array('StringTrim'),
'style' => array('width:103px'),
'multiOptions' => $list,
'decorators'=>Array(
'ViewHelper','Errors'
but Now i want to set the value in option in select box width $id from database
$companyName = new Zend_Form_Element_Select('companyName');
$companyName->setRequired(true);
$companyName->addFilter('StringTrim');
$company_list = new Application_Model_Clientcompany;
$showlist = $company_list->companyNameList();
//add selections to multioption, assumes object...change notation if using array
foreach($showlist as $company) {
$name = ucfirst($company->name);
$companyName->addMultiOption($company->id, $name);
}
$this->addElement($companyName);
I know I changed the syntax style, I just find it easier to keep things straight this way.
Everything else you may need is in http://framework.zend.com/manual/1.12/en/zend.form.html, get used to using the reference and the the api for the framework, they really help.

adding data to a date field attached to a node in drupal 7

I need to add data to a datetime field in drupal 7. I am tryin to use
$node->field_test_a_updated[0]['value'] = $val;
$node->field_test_a_updated[0]['delta'] = 0;
$node->field_test_a_updated[0]['timezone'] = 'UTC';
$node->field_test_a_updated[0]['timezone_db'] = 'UTC';
$node->field_test_a_updated[0]['date_type'] = 'datetime';
where $val has the value "2010-06-15T00:00:00-00:00".
When i try to import the content, all the other fields attached to the node get migrated properly, except the date field.I have also tried using [LANGUAGE_NONE] option.
I am sure i am missing out something that is related to drupal7 field api.
Please help.
The structure of fields in Drupal 7 (in this context) is:
array(
'language_code' => array(
0 => array(
'value => $val,
'other_column_value' => $other_val
)
)
);
The delta is handled by the key of each of the arrays inside $array['language_code'] so you don't need to include it. In your case you want the code to look like this (assuming of course you're passing the node through node_save() afterwards):
$node->field_test_a_updated[LANGUAGE_NONE] = array(
0 => array(
'value' => $val,
'timezone' => 'UTC',
'timezone_db' => 'UTC',
'date_type' => 'datetime'
)
);
Hope that helps

Zend_Validate_Db_RecordExists against 2 fields

I usualy use Zend_Validate_Db_RecordExists to update or insert a record. This works fine with one field to check against. How to do it if you have two fields to check?
$validator = new Zend_Validate_Db_RecordExists(
array(
'table' => $this->_name,
'field' => 'id_sector,day_of_week'
)
);
if ($validator->isValid($fields_values['id_sector'],$fields_values['day_of_week'])){
//true
}
I tried it with an array and comma separated list, nothing works... Any help is welcome.
Regards
Andrea
To do this you would have to extend the Zend_Validate_Db_RecordExists class.
It doesn't currently know how to check for the existence of more than one field.
You could just use two different validator instances to check the two fields separately. This is the only work around that I can see right now besides extending it.
If you choose to extend it then you'll have to find some way of passing in all the fields to the constructor ( array seems like a good choice ), and then you'll have to dig into the method that creates the sql query. In this method you'll have to loop over the array of fields that were passed in to the constructor.
You should look into using the exclude parameter. Something like this should do what you want:
$validator = new Zend_Validate_Db_RecordExists(
array(
'table' => $this->_name,
'field' => 'id_sector',
'exclude' => array(
'field' => 'day_of_week',
'value' => $fields_values['day_of_week']
)
);
The exclude field will effectively add to the automatically generated WHERE part to create something equivalent to this:
WHERE `id_sector` = $fields_values['id_sector'] AND `day_of_week` = $fields_values['day_of_week']
Its kind of a hack in that we're using it for the opposite of what it was intended, but its working for me similar to this (I'm using it with Db_NoRecordExists).
Source: Zend_Validate_Db_NoRecordExists example
Sorry for the late reply.
The best option that worked for me is this:
// create an instance of the Zend_Validate_Db_RecordExists class
// pass in the database table name and the first field (as usual)...
$validator = new Zend_Validate_Db_RecordExists(array(
'table' => 'tablename',
'field' => 'first_field'
));
// reset the where clause used by Zend_Validate_Db_RecordExists
$validator->getSelect()->reset('where');
// set again the first field and the second field.
// :value is a named parameter that will be substituted
// by the value passed to the isValid method
$validator->getSelect()->where('first_field = ?', $first_field);
$validator->getSelect()->where('second_field = :value', $second_field);
// add your new record exist based on 2 fields validator to your element.
$element = new Zend_Form_Element_Text('element');
$element->addValidator($validator);
// add the validated element to the form.
$form->addElement($element);
I hope that will help someone :)
Although, I would strongly recommend a neater solution which would be to extend the Zend_Validate_Db_RecordExists class with the above code.
Enjoy!!
Rosario
$dbAdapter = Zend_Db_Table::getDefaultAdapter();
'validators' => array('EmailAddress', $obj= new Zend_Validate_Db_NoRecordExists(array('adapter'=>$dbAdapter,
'field'=>'email',
'table'=>'user',
'exclude'=>array('field'=>'email','value'=>$this->_options['email'], 'field'=>'is_deleted', 'value'=>'1')
))),
For those using Zend 2, If you want to check if user with given id and email exists in table users, It is possible this way.
First, you create the select object that will be use as parameter for the Zend\Validator\Db\RecordExists object
$select = new Zend\Db\Sql\Select();
$select->from('users')
->where->equalTo('id', $user_id)
->where->equalTo('email', $email);
Now, create RecordExists object and check the existence this way
$validator = new Zend\Validator\Db\RecordExists($select);
$validator->setAdapter($dbAdapter);
if ($validator->isValid($username)) {
echo 'This user is valid';
} else {
//get and display errors
$messages = $validator->getMessages();
foreach ($messages as $message) {
echo "$message\n";
}
}
This sample is from ZF2 official doc
You can use the 'exclude' in this parameter pass the second clause that you want to filter through.
$clause = 'table.field2 = value';
$validator = new Zend_Validate_Db_RecordExists(
array(
'table' => 'table',
'field' => 'field1',
'exclude' => $clause
)
);
if ($validator->isValid('value') {
true;
}
I am using zend framework v.3 and validation via InputFilter(), it uses same validation rules as zend framework 2.
In my case I need to check, if location exists in db (by 'id' field) and has needed company's id ('company_id' field).
I implemented it in next way:
$clause = new Operator('company_id', Operator::OP_EQ, $companyId);
$inputFilter->add([
'name' => 'location_id',
'required' => false,
'filters' => [
['name' => 'StringTrim'],
['name' => 'ToInt'],
],
'validators' => [
[
'name' => 'Int',
],
[
'name' => 'dbRecordExists',
'options' => [
'adapter' => $dbAdapterCore,
'table' => 'locations',
'field' => 'id',
'exclude' => $clause,
'messages' => [
'noRecordFound' => "Location does not exist.",
],
]
],
],
]);
In this case validation will pass, only if 'locations' table has item with columns id == $value and company_id == $companyId, like next:
select * from location where id = ? AND company_id = ?