Cakephp automatically filled form select for two word named belongTo model - forms

What is right naming or what am I missing to get automagic run for two word named Model. Actual model belong to the two words named model.
Exact example:
Tour belongs to Accommodation type.
in database there is table tours and table accommodation_types
foreign key from tours is tours.accommodation_type_id
Snapshots of code below.
ToursController.php
public function add() {
//...
$accommodation_types = $this->Tour->AccommodationType->find('list');
//...
$this->set(compact('accommodation_types', ...));
}
Tour.php
//...
public $belongsTo = array(
//...
'AccommodationType' => array(
'className' => 'AccommodationType',
'foreignKey' => 'accommodation_type_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
//...
);
Tours/add.ctp (inside a form)
echo $this->Form->input('accommodation_type_id', array('label' => 'Accommodation type'));

As per convention the view vars names should be camelBacked. So rename the view var from $accommodation_types to $accommodationTypes. If you don't follow convention you have to explicitly specify the options var to use like this:
echo $this->Form->input('accommodation_type_id', array('options' => $accommodation_types, 'label' => 'Accommodation type'));

Related

How to realize inheritance in Typo3 6.2 Extension?

My goal is being able to:
Create Expertise Entries in the backend (already accomplished)
Create SubExpertise Entries in the backend
(same props as Expertise but
they belong to one or many Expertise)
Create AdditionalInfoTitles Entries in the backend
(they can belong to one or many Expertise OR SubExpertise)
I want to be able to choose Objects from all Expertise AND SubExpertise when creating a new entry
Right now I can only choose between all Expertise-Entries:
That's why I thought about inheritance since then SubExpertise would be of the same type as Expertise and therefore automatically displayed in the Expertise list in a AdditionalInfoTitles entry. But that's just my theory and I'm kinda stuck in reality with typo3 TCA and other knowledge that I'm lacking...
In my extension builder I made following (don't mind the subExpertises property)
Then I added expertise to the Overrides folder, because I'm trying to extend it with subexpertise:
<?php
if (!defined('TYPO3_MODE')) {
die ('Access denied.');
}
$temporaryColumns = array (
'expertise' => array(
'exclude' => 1,
'label' => 'LLL:EXT:appoints/Resources/Private/Language/locallang_db.xlf:tx_appoints_domain_model_subexpertise.expertise',
'config' => array(
'type' => 'select',
'foreign_table' => 'tx_appoints_domain_model_subexpertise',
'MM' => 'tx_appoints_subexpertise_expertise_mm',
'size' => 10,
'autoSizeMax' => 30,
'maxitems' => 9999,
'multiple' => 0,
'wizards' => array(
'_PADDING' => 1,
'_VERTICAL' => 1,
'edit' => array(
'module' => array(
'name' => 'wizard_edit',
),
'type' => 'popup',
'title' => 'Edit',
'icon' => 'edit2.gif',
'popup_onlyOpenIfSelected' => 1,
'JSopenParams' => 'height=350,width=580,status=0,menubar=0,scrollbars=1',
),
'add' => Array(
'module' => array(
'name' => 'wizard_add',
),
'type' => 'script',
'title' => 'Create new',
'icon' => 'add.gif',
'params' => array(
'table' => 'tx_appoints_domain_model_expertise',
'pid' => '###CURRENT_PID###',
'setValue' => 'prepend'
),
),
),
),
),
);
\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addTCAcolumns(
'tx_appoints_domain_model_expertise',
$temporaryColumns
);
\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addToAllTCAtypes(
'tx_appoints_domain_model_expertise',
'expertise'
);
But I don't think I'm going into the right direction with this -
Because I think this way I'm not gonna be able to add a SubExpertise in the backend separately from an Expertise - I already have the same problem with my Objects that extend fe_user because when creating them I usually have to go through a new User and then set the extension type - but this way I don't have separate listings of the different entities that extend fe_user.
I would get rid of the separation between Expertise and SubExpertise for the most part. According to your description a SubExpertise cannot have another SubExpertise as its parent, so you can adapt the select field that it only lists Expertises which have an empty parent field.
By removing the difference the problem of selecting (Sub)Expertise's in AdditionalInfoTitles is removed; it's just one and the same type of objects.
If you need to differentiate in the presentation in the BE forms there are plenty of options to adjust the labels of the listed items, use a function of your own to build the list or even a custom form element.
In Extbase you can simply write a few functions in your repository to fetch Expertise's, SubExpertise's or both.
If the entity SubExpertise does not have a meaning in your domain model, Jigal's answer is perfect for your scenario. If it does have a meaning, you can achieve that using single table inheritance in Extbase.
class Expertise extends \TYPO3\CMS\Extbase\DomainObject\AbstractEntity
{
// all common properties
}
class SubExpertise extends Expertise
{
/**
* #var \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\[YourVendorName]\Appoints\Domain\Model\Expertise>
*/
protected $expertises;
public function __construct()
{
$this->expertises = new \TYPO3\CMS\Extbase\Persistence\ObjectStorage();
}
public function getExpertises() {}
public function setExpertises($expertises) {}
}
Via TypoScript then you have to define mapping rules, since both Expertise and SubExpertise would be stored in the same table tx_appoints_domain_model_subexpertise.
You'll find more details on single table inheritance in the Extbase book.

Creating collection of read-only entities in Symfony2

My question is about creating collection of entities. I know about "How To Embed Collection Forms" and successfully used it. But in this case I have:
Simple class
class Thing
{
/**
* #ORM\ManyToMany(targetEntity="DicStyle", mappedBy="things")
* ....
*/
protected $styles;
public function __construct()
{
$this->styles = new ArrayCollection();
}
}
Dictionary of styles
class DicStyle
{
.....
}
I don't need to create form for DicStyle objects, because this is read only objects = dictionary (unchangeable). So, I want to create a form with something like this:
$builder->add('styles', 'collection', array(
'type' => 'entity', 'options' => array(
'class' => 'MyEntityBundle:DicStyle'
)
))
Of course it's pseudo-code. I can not imagine how to implement it.
The result
Suppose, I have:
Table "Thing" with one row (id = 1).
Table "DicStyle" with 6 rows (id = from 1 to 6).
Table "mtm_thing_dicstyle" (many-to-many table)
In the form, I choose two DicStyle (id=3, id=5) for the Thing. So, the mtm_thing_dicstyle contains:
thing_id dicstyle_id
-------- ------------
1 3
1 5
Try this form:
$builder->add('styles', 'entity', array(
'class' => 'MyEntityBundle:DicStyle'
'property'=>'name' //what property do you want to see when you select,
'multiple" => true //you'll be able to select many DicStyle
'expanded' => false //it'll shown on a multiple choice select tag
)
);
To select one or more objects in a form to relate them to your result you can use the form field type "entity". (See form-types)
$builder->add('styles', 'entity', array(
'class' => 'MyEntityBundle:DicStyle',
'property' => 'name', // property you want to be displayed
'expanded' => true,
'multiple' => true
)
);
This would render checkboxes and therefore the possibility to select multiple entities to be referenced.
Keep in mind, if you use multiple => true there are two options:
expanded => false: renders a multiselect field
expanded => true: renders checkboxes
See form-entity-type-options

Select an related entity manually

I have an entity that can have an image. This is done using a OneToMany relationship. Now I want the user to choose an image. I can of course use a form field like this:
$builder->add('image', 'entity', array(
'label' => 'Image',
'class' => 'VendorNameBundle:Image',
'property' => 'id',
) );
It renders as expected a dropdown with all the ids. But what I actually want is only a single field that is hidden and that stores the id of the selected image.
This would work but it seems not like a good thing …
In the type:
$builder->add('_image', 'text', array(
'data' => $object->getImage()->getId(),
'property_path' => false
));
In the controller:
$_image = $form["_image"]->getData();
if ($_image) {
$image = $this->getDoctrine()->getRepository('VendorNameBundle:Image')->find($_image);
if ($image) {
$object->setImage($image);
}
}
My question is: How can I get a hidden text field that contains the ID of the related object and stores the new selected one?

Example of Zend Form with Collection Element using Forms not Fieldsets in Zend Framework2

I need a straight forward working example how I can include a collection element in Zend Form, I have seen some examples from Zend Framework 2 site and from previous posts in StackOverflow where most of them pointed to this link. But right now I am not using Fieldsets and staying with Forms, so in case if someone can direct me in the right way, how I can include a simple collection element when the user gets a page where the user can choose multiple choices from the shown collection form. Much better would be populating the collection form from database.
I have searched in the internet for quite a sometime now and thought I would post here, so that Zend profis can give their suggestions.
Just For Information:
Normally one can include a static dropdownbox in Zend Form in this fashion
$this->add(
array(
'name' => "countr",
'type' => 'Zend\Form\Element\Select',
'options' => array(
'label' => "Countries",
'options' => array(
'country1' => 'Brazil',
'country2' => 'USA',
'country3' => 'Mexico',
'country4' => 'France',
)
)
)
);
So I am expecting a simple example which could give me a basic idea how this can be done.
To be honest, I don't see your problem here. Since form collections extend Fieldset which extends Element, you can just add it to the form as a regular element. The view helpers will take care of the rendering recursively.
Step 1: Create a form collection (create an instance of Zend\Form\Element\Collection). If the elements have to be added dynamically in some way, I'd create a factory class for this purpose.
Step 2: Add it to the form. (For example using $form->add($myCollectionInstance).)
Step 3: Render it. Zend\Form\View\Helper\Collection is a pretty good view helper to render the whole form without any pain.
You can also create a new class extending Zend\Form\Element\Collection and use the constructor to add the fields you need. Thus, you can add it to the form using the array you've pasted in your question. Also, you could directly use it in annotations.
Hope this helps.
If you just want to fill in a select list with option values you can add the array to the select list in a controller:
$form = new MyForm();
$form->get('countr')->setOptions(array('value_options'=>array(
'country1' => 'Brazil',
'country2' => 'USA',
'country3' => 'Mexico',
'country4' => 'France',
));
the array can be fetched from db.
this is a different example for using form collections in the simplest way.
In this example it creates input text elements in a collection and fills them in. The number of elements depends on the array:
class MyForm extends \Zend\Form\Form
{
$this->add(array(
'type' => '\Zend\Form\Element\Collection',
'name' => 'myCollection',
'options' => array(
'label' => 'My collection',
'allow_add' => true,
)
));
}
class IndexController extends AbstractActionController
{
public function indexAction
{
$form = new MyForm();
$this->addElementsFromArray($form, array(
'country1' => 'Brazil',
'country2' => 'USA',
'country3' => 'Mexico',
'country4' => 'France',
));
//the above line can be replaced if fetching the array from a db table:
//$arrayFromDb = getArrayFromDb();
//$this->addElementsFromArray($form, $arrayFromDb);
return array(
'form' => $form
);
}
private function addElementsFromArray($form, $array)
{
foreach ($array as $key=>$value)
{
$form->get('myCollection')->add(array(
//'type' => '\Zend\Form\Element\SomeElement',
'name' => $key,
'options' => array(
'label' => $key,
),
'attributes' => array(
'value' => $value,
)
));
}
}
}
index.phtml:
$form->setAttribute('action', $this->url('home'))
->prepare();
echo $this->form()->openTag($form);
echo $this->formCollection($form->get('myCollection'));
echo $this->form()->closeTag();

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