Setting a drupal entity date field without EMW - date

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;

Related

Add Entity Reference to Drupal 8 Form Field?

How can users add products to a simple plugin config using an autocomplete field?
I tried to use Config Entity but it looks the same as Form API (and I can't use entity fields there).
I was able to do this in Drupal 8 using the form API and the entity_autocomplete type.
$form['stories'] = [
'#type' => 'entity_autocomplete',
'#target_type' => 'node',
'#title' => $this->t('Stories'),
'#description' => $this->t('Select some stories.'),
'#default_value' => $default_entities,
'#tags' => TRUE,
'#selection_settings' => array(
'target_bundles' => array('page', 'article'),
),
'#weight' => '0',
];
Use webform - there is an entity reference field.
This won't be useable for your purpose .. but you can check the source for sake.

Symfony2 - Functional Testing File uploads with dynamically created fields

I'm fighting with functional testing of files uploading.
I will try to simplify my situation. Let's say I have
a company entity, which has 3 fields.
Company {
protected name;
protected tags;
protected images;
}
Images is array of CompanyImage entities, which serve for
storing image files and tags contains array of Tag entities,
which can be m:n connected with companies.
In the form I use jquery, for adding tags and images dynamically.
(you can create images and add them to the company similar to the
collection type symfony tutorial)
Because images and tag arrays are created with jquery, I cannot
simply use something like the turorial line below in the functional test of the company form.
$form['images'][0]->upload('/path/to/image.jpg');
For the setting
of the form values I use simple a little trick described by sstok here
(https://github.com/symfony/symfony/issues/4124)
public function testCompanyCreation() {
...
//option1
$image = new UploadedFile(
'/path/to/image.jpg',
'image.jpg',
'image/jpeg',
123
);
//or option2
//$image = array('tmp_name' => '/path/to/image.jpg', 'name' => 'image.jpg', 'type' => 'image/jpeg', 'size' => 300, 'error' => UPLOAD_ERR_OK);
$companyFormNode = $companyCrawler->selectButton('Create');
$companyForm = $companyFormNode->form();
$values = array(
'company' => array(
'_token' => $companyForm['company[_token]']->getValue(),
'name' => 'test company',
'tags' => array('1'),
'images' => array('0' => (array('file' =>$image))),
),
);
$companySubmitCrawler = $client->request($companyForm->getMethod(), $companyForm->getUri(), $values, $companyForm->getPhpFiles());
}
this works perfectly until I try to upload the image file.
With the option1 I get following exception
Exception: Serialization of 'Symfony\Component\HttpFoundation\File\UploadedFile' is not allowed
when I use option2 I get this
Argument 1 passed to Acme\myBundle\Entity\CompanyImage::setFile() must be an instance of Symfony\Component\HttpFoundation\File\UploadedFile, array given, called in ...\PropertyAccess\PropertyAccessor.php on line 347 and defined (500 Internal Server Error)
I would also like to point out, that the whole form and uploading of the files works without any problems in the browser. I also tried to make the entities serializable, and it didn't help. Do I have a bug somewhere?
I have figured it out (took couple of hours). Files have to be uploaded in a separate array.
$companyForm = $companyFormNode->form();
$values = array(
'company' => array(
'_token' => $companyForm['company[_token]']->getValue(),
'name' => 'test company',
'tags' => array('1')
),
);
$files = array(
'company' => array('images' => array('0' => (array('file' => $image))))
);
$companySubmitCrawler = $client->request(
$companyForm->getMethod(),
$companyForm->getUri(),
$values,
$files
);

Magento admin form time field

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

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 = ?

zend mapping one to many fetchall

I have 2 tables user and user_comment where user has many user_comments, i laid down the mapping being
User
$_dependentTables = array('User_Comments);
and
User_Comments
$_referenceMap = array(
'User' => array(
'columns' => 'id',
'refTableClass' => 'User',
'refColumns' => 'id'
)
);
Is there a way for me to do user->fetchAll() and get the user_comments without doing loop query (in cakephp it will do one query on user_comments where in (ids) then format it back to an array but i cant use cake). Is this possible in zend with me doing it manually? Thanks
Try this one
$sql=$this->getAdapter()->select()
->from("user_comment")
->join("user", "user.id=user_comment.userid")
->where("user_comment.id=?",$userId);
$result=$this->getAdapter()->query($sql)->fetchAll();
This might help u....