Skip to content

Commit c9af58f

Browse files
committed
Handle subclasses (: operator) in default create() method of SharpForm
1 parent 97d5f10 commit c9af58f

File tree

2 files changed

+36
-6
lines changed

2 files changed

+36
-6
lines changed

src/Form/SharpForm.php

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
namespace Code16\Sharp\Form;
44

55
use Code16\Sharp\Exceptions\Form\SharpFormUpdateException;
6-
use Code16\Sharp\Form\Fields\SharpFormField;
76
use Code16\Sharp\Form\Layout\FormLayoutColumn;
87
use Code16\Sharp\Form\Layout\FormLayoutTab;
98
use Code16\Sharp\Utils\SharpNotification;
@@ -83,10 +82,10 @@ public function newInstance()
8382
public function hasDataLocalizations()
8483
{
8584
return collect($this->fields())
86-
->filter(function($field) {
87-
return $field["localized"] ?? false;
88-
})
89-
->count() > 0;
85+
->filter(function($field) {
86+
return $field["localized"] ?? false;
87+
})
88+
->count() > 0;
9089
}
9190

9291
/**
@@ -224,7 +223,18 @@ public function __construct($attributes)
224223
$this->attributes = $attributes;
225224

226225
foreach($attributes as $name => $value) {
227-
$this->$name = $value;
226+
if(strpos($name, ':')) {
227+
list($subModel, $attr) = explode(':', $name);
228+
229+
if(!isset($this->$subModel)) {
230+
$this->$subModel = new \stdClass();
231+
}
232+
233+
$this->$subModel->$attr = $value;
234+
235+
} else {
236+
$this->$name = $value;
237+
}
228238
}
229239
}
230240
public function toArray()

tests/Unit/Form/SharpFormTest.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,26 @@ function buildFormFields()
3535
], $sharpForm->newInstance());
3636
}
3737

38+
/** @test */
39+
function we_get_formatted_data_in_creation_with_the_default_create_function_with_subclasses()
40+
{
41+
$sharpForm = new class extends BaseSharpForm {
42+
function buildFormFields()
43+
{
44+
$this->addField(
45+
SharpFormTextField::make("name")
46+
)->addField(
47+
SharpFormMarkdownField::make("subclass:company")
48+
);
49+
}
50+
};
51+
52+
$this->assertEquals([
53+
"name" => "",
54+
"subclass:company" => ["text" => null],
55+
], $sharpForm->newInstance());
56+
}
57+
3858
/** @test */
3959
function if_the_field_formatter_needs_it_we_can_delay_its_execution_after_first_save()
4060
{

0 commit comments

Comments
 (0)