I have the following models:
Posts->hasMany('texts');
Texts has a field 'body' that is required (not null)
Posts->hasMany('images);
Images has a field 'imagelink' that is required (not null)
When a user wants to create a post I want a single form to also add at least one text, or at least one image, or both.
My understanding is that because the formhelper
uses the validator in TextsTable.php
and ImagesTable.php
it marks both the images.0.imagelink
and the texts.0.body
fields as required. And they are required if you actually want to create an entity of either type texts or images. But I want the creation of these associated entities optional. A user should be able to make a post with only an image for example.
How do I tell cakephp
or the formhelper
that not every post needs to have a text and an image? Is there something to add to the association definitions, or the validator of PostsTable.php
?
I can create a post without any associated models just fine if I have a form with only the fields that are directly in the posts model, but not when I have one form for both the post and fields for associated models. Then the formhelper
forces me to create an entity of all possible associated models that have a field in the form every time an entity of the base model is created.
In the end I also want to create as many texts and images as the user wants, but I think that's a different problem.
This is the relevant form in the ctp-file:
<?= $this->Form->create($post) ?>
<fieldset>
<?php
echo $this->Form->control('post_title');
echo $this->Form->control('texts.0.body');
echo $this->Form->control('images.0.imagelink');
?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
TextsTable.php (ImagesTable.php is basically the same)
public function validationDefault(Validator $validator)
{
$validator
->integer('id')
->allowEmptyString('id', null, 'create');
$validator
->scalar('body')
->requirePresence('body', 'create')
->notEmptyString('body');
return $validator;
}
Scenarios:
I tried making two fields but then if a user wants to make a post with both an image and a text, the image and text aren't in the same post.