How to validate multiple inputs in Laravel? - php

one email is required. and one checkbox should be checked in the first row.
if the second email input is filled in the second row then there is also one checkbox should be checked and so on.
#for ($i = 0; $i < 4; $i++)
<input type="email" id="email" name="email[]">
<input type="checkbox" name="task[{{ $i }}][]" value="sign">
<input type="checkbox" name="task[{{ $i }}][]" value="initial">
<input type="checkbox" name="task[{{ $i }}][]" value="date">
<input type="checkbox" name="task[{{ $i }}][]" value="cc"
#endfor
this is the code in my controller its not catch the task field if it's null.
$validatedData = $request->validate([
'email.0' => 'required_without_all:email.*|email',
'email.1' => 'nullable|email',
'email.2' => 'nullable|email',
'email.3' => 'nullable|email',
'task.*' => 'required_if:email.*,filled',
]);

I have searched a lot everywhere but the following code worked for me:
$request->validate([
'email.*' => 'nullable|email',
'email.0' => 'required|email',
'task.0' => 'required_with:email.0',
'task.1' => 'required_with:email.1',
'task.2' => 'required_with:email.2',
'task.3' => 'required_with:email.3',
]);

You can try this
First, change the field name like below
Here I used data as an array index in order to map the email, sign, date, and initial fields under the same index
#for ($i = 1; $i <= 4; $i++)
<input type="email" id="email" name="data[{{ $i }}][email]">
<input type="checkbox" name="data[{{ $i }}][sign]" value="sign">
<input type="checkbox" name="data[{{ $i }}][initial]" value="initial">
<input type="checkbox" name="data[{{ $i }}][date]" value="date">
<input type="checkbox" name="data[{{ $i }}][cc]" value="cc"
#endfor
Once you pass email in the first box and select the initial option and keep the rest unchanged and add dd($request->all()) in the controller you will output as given below.
array:2 [▼
"data" => array:4 [▼
1 => array:2 [▼
"email" => "someemail#gmail.com"
"initial" => "initial"
]
2 => array:1 [▼
"email" => null
]
3 => array:1 [▼
"email" => null
]
4 => array:1 [▼
"email" => null
]
]
]
Now add Laravel validation with the given below
$request->validate([
'data' => 'required|array',
'data.*.sign' => 'sometimes|required_with:data.*.email',
'data.*.date' => 'sometimes|required_with:data.*.email',
'data.*.cc' => 'sometimes|required_with:data.*.email',
'data.*.initial' => 'required_with:data.*.email',
'data.*.email' => 'required_with:data.*.sign|required_with:data.*.cc|required_with:data.*.date|required_with:data.*.initial',
]);
This will validate the form data both ways around.
NOTE: You must add some custom validation to check if non of the values are selected.
I hope you find this helpful.

<?php
class CourseLevelsRequest
{
private array $rules = [
'course_levels' => 'required|array',
];
public function __construct()
{
$this->makeValidationRules();
request()->validate($this->rules);
// your custom logic
}
private function makeValidationRules(): void
{
collect(request('course_levels'))->each(function ($courseLevelRequest, $index) {
$this->rules['course_levels.'.$index.'.course_id'] = 'required';
$this->rules['course_levels.'.$index.'.level'] = 'required|string|max:255';
$this->rules['course_levels.'.$index.'.programmatic_course_level_name']
= 'required|string|max:255|unique:course_levels,programmatic_course_level_name,'.$courseLevelRequest['id'];
$this->rules['course_levels.'.$index.'.fee'] = 'required|numeric';
});
}
}
Here, I have full control of validation rules

Related

Laravel merge arrays into one array

I am sending 4 arrays to my controller that they need to combine before I can store them to database, here is how they're look like:
array:4 [▼
"from" => array:7 [▼
0 => "8:00"
1 => null
2 => null
3 => null
4 => null
5 => null
6 => null
]
"to" => array:7 [▼
0 => "21:00"
1 => null
2 => null
3 => null
4 => null
5 => null
6 => null
]
"closed" => array:6 [▼
0 => "on"
1 => "on"
2 => "on"
3 => "on"
4 => "on"
5 => "on"
]
"day_id" => array:7 [▼
0 => "a0275acb-c6e5-428f-8589-da0644c1f42e"
1 => "9a8d2dc5-fbe5-4a93-a279-2c6a90781777"
2 => "84d74f04-3728-4314-a6e7-8710cecaa911"
3 => "79ef140a-5de5-4b27-a286-9893cbac820e"
4 => "6d0b2858-ff96-46ce-ae1b-665c3ee353aa"
5 => "38225fe6-3bce-4ee9-bad8-c7f6cacc4854"
6 => "28cef2be-1ff6-4e80-b322-a208f4838391"
]
]
As you might notice closed array is less by 1 value as the checkbox was unchecked, so this one is vary between no value (if none are check) to 7 values (if all of them are checked)
Anyway, I need to make this arrays to something like this:
array:7 [▼
"finaldata" => array:4 [▼
from => "8:00"
to => "21:00"
closed => off
day_id => "a0275acb-c6e5-428f-8589-da0644c1f42e"
],
"finaldata" => array:4 [▼
from => null
to => null
closed => on
day_id => "9a8d2dc5-fbe5-4a93-a279-2c6a90781777"
],
// and so on...
]
If I can get such result then I'll be able to loop and store this data into my database.
Code
$schedules = [];
$schedules['from'] = $request->input('from');
$schedules['to'] = $request->input('to');
$schedules['closed'] = $request->input('closed');
$schedules['day_id'] = $request->input('day_id');
dd($schedules); // returning my results above (on top)
foreach($schedules as $schedule) {
$days = new WorkDays;
//...
$days->save();
}
Question
How can I get such result as I shared to store my data?
Update
blade
<div class="mt-4">
<div x-data="handler()">
<x-jet-label value="Schedule" />
<table class="itable align-middle w-full">
<thead class="thead-light">
<tr>
<th>Day</th>
<th>From</th>
<th>To</th>
<th>Closed</th>
</tr>
</thead>
<tbody>
<template x-for="(field, index) in {{$days}}" :key="index">
<tr>
<td x-text="field.name"></td>
<td>
<x-jet-input x-model="field.from" type="text" name="from[]" />
<x-jet-input x-model="field.id" type="hidden" value="field" name="day_id[]"/>
</td>
<td><x-jet-input x-model="field.to" type="text" name="to[]" /></td>
<td><input x-model="field.closed" class="form-checkbox" type="checkbox" name="closed[]" /></td>
</tr>
</template>
</tbody>
</table>
</div>
<script>
function handler() {
return {
fields: []
}
}
</script>
</div>
Update 2
based on iCoders answer this is what i get, which is good but the ones with unchecked checkbox will not have closed variable array 0 and 6.
"data" => array:7 [▼
0 => array:3 [▼
"from" => "54"
"day_id" => "a0275acb-c6e5-428f-8589-da0644c1f42e"
"to" => "474"
]
1 => array:4 [▼
"from" => null
"day_id" => "9a8d2dc5-fbe5-4a93-a279-2c6a90781777"
"to" => null
"closed" => "on"
]
2 => array:4 [▼
"from" => null
"day_id" => "84d74f04-3728-4314-a6e7-8710cecaa911"
"to" => null
"closed" => "on"
]
3 => array:4 [▼
"from" => null
"day_id" => "79ef140a-5de5-4b27-a286-9893cbac820e"
"to" => null
"closed" => "on"
]
4 => array:4 [▼
"from" => null
"day_id" => "6d0b2858-ff96-46ce-ae1b-665c3ee353aa"
"to" => null
"closed" => "on"
]
5 => array:4 [▼
"from" => null
"day_id" => "38225fe6-3bce-4ee9-bad8-c7f6cacc4854"
"to" => null
"closed" => "on"
]
6 => array:3 [▼
"from" => "67565"
"day_id" => "28cef2be-1ff6-4e80-b322-a208f4838391"
"to" => "6567"
]
I dont know much usage about new component in laravel 8 but usually common idea is
#foreach($days as $key=>$value)
<tr>
<td x-text="field.name"></td>
<td>
<x-jet-input x-model="field.from" type="text" name="data[{{$key}}][from]" />
<x-jet-input x-model="field.id" type="hidden" value="field" name="data[{{$key}}][day_id]"/>
</td>
<td><x-jet-input x-model="field.to" type="text" name="data[{{$key}}][to]" /></td>
<td><input x-model="field.closed" class="form-checkbox" type="checkbox" name="data[{{$key}}][closed]" /></td>
</tr>
#endforeach
Then in controller if you dd($request->data) you get merged data
Updated
As per another question answer Dynamically set name attribute of input field in loop with AlpineJS
You need to use x-bind:name with a template string:
<template x-for="(field, index) in {{$days}}" :key="index">
<tr>
<td x-text="field.name"></td>
<td>
<x-jet-input x-model="field.from" type="text" x-bind:name="`data[${index}][from]`/>
<x-jet-input x-model="field.id" type="hidden" value="field" x-bind:name="`data[${index}][day_id]`"/>
</td>
<td><x-jet-input x-model="field.to" type="text" x-bind:name="`data[${index}][to]` /></td>
<td><input x-model="field.closed" class="form-checkbox" type="checkbox" x-bind:name="`data[${index}][closed]` /></td>
</tr>
</template>
Update2:
<input x-model="field.closed" class="form-checkbox" type="checkbox" name="data[{{$key}}][closed]" #click="$event.target.value = $event.target.checked ? '1' : '2'"/>
Change your blade to something like this.
<template x-for="(field, index) in {{$days}}" :key="index">
<tr>
<td x-text="field.name"></td>
<td>
<x-jet-input x-model="field.from" type="text" name="finaldata[{{$loop->iteration}}]['from']" />
<x-jet-input x-model="field.id" type="hidden" value="field" name="finaldata[{{$loop->iteration}}]['day_id']"/>
</td>
<td><x-jet-input x-model="field.to" type="text" name="finaldata[{{$loop->iteration}}]['to']" /></td>
<td><input x-model="field.closed" class="form-checkbox" type="checkbox" name="finaldata[{{$loop->iteration}}]['closed']" /></td>
</tr>
</template>

How do I merge an array with PHP Laravel?

I have cloned HTML prepared with input group. Some checkbox and radio are not selected. I want to push into the selected email.
I've tried many methods.
array_merge()
array_combine()
array_push()
array_merge_recursive()
But none of these worked. Or I don't know how to get them to work.
HTML
<div class="form-group">
<label for="name">E-posta</label>
<div class="input-group">
<input type="email" class="form-control email-address" name="email[]" placeholder="E-Posta giriniz">
<div class="btn-group">
<label class="btn btn-default">
<input class="primary-radio" type="radio" name="primary[]" checked autocomplete="off"> <span
class="fas fa-star"></span>
</label>
<label class="btn btn-default">
<input class="ban-checkbox" type="checkbox" name="ban[]" autocomplete="off"> <span
class="fas fa-ban"></span>
</label>
<label class="btn btn-default">
<input class="invalid-checkbox" type="checkbox" name="invalid[]" autocomplete="off"> <span
class="fas fa-exclamation-circle"></span>
</label>
</div>
</div>
</div>
PHP
public function add(Request $request)
{
$emails = $request->input('email');
$primary = $request->input('primary');
$ban = $request->input('ban');
$invalid = $request->input('invalid');
$emailAddresses = array();
foreach ($emails as $emailKey => $emailValue) {
$emailAddresses[$emailKey] = [
'emailAddress' => $emailValue,
'invalid' => $invalid,
'lower' => $emailAddresses,
'ban' => $ban,
'primary' => $primary
];
}
dd($emailAddresses);
}
Output
array:3 [▼
0 => array:5 [▼
"emailAddress" => "dodis#live.com"
"invalid" => null
"lower" => "dodis#live.com"
"ban" => array:2 [▼
0 => "on"
1 => "on"
]
"primary" => array:1 [▼
0 => "on"
]
]
1 => array:5 [▼
"emailAddress" => "test#live.com"
"invalid" => null
"lower" => "test#live.com"
"ban" => array:2 [▼
0 => "on"
1 => "on"
]
"primary" => array:1 [▼
0 => "on"
]
]
2 => array:5 [▼
"emailAddress" => "bundayok#live.com"
"invalid" => null
"lower" => "bundayok#live.com"
"ban" => array:2 [▼
0 => "on"
1 => "on"
]
"primary" => array:1 [▼
0 => "on"
]
]
]
Such an output comes. It shouldn't be like that. Here's the example I want it to be.
0: {
emailAddress: "bilgi#ekinciler.com.tr"
invalid: false
lower: "bilgi#ekinciler.com.tr"
optOut: false
primary: true
}
1: {
emailAddress: "muhasebe#ekinciler.com"
invalid: false
lower: "muhasebe#ekinciler.com"
optOut: false
primary: false
}
I am sorry for my English. I hope I can. I would be glad if you help.
Try below code,
What I have done is added array index to each loop to get correct value of that index, here your
"ban" => array:2 [▼
0 => "on"
1 => "on"
]
is array itself so you need 0 index for the first array data. and same applies for all the array.
public function add(Request $request)
{
$emails = $request->input('email');
$primary = $request->input('primary');
$ban = $request->input('ban');
$invalid = $request->input('invalid');
$emailAddresses = array();
$i = 0;
foreach ($emails as $emailKey => $emailValue) {
$emailAddresses[$emailKey] = [
'emailAddress' => $emailValue,
'invalid' => $invalid[$i]?$invalid[$i]:'',
'lower' => $emailAddresses,
'ban' => $ban[$i]?$ban[$i]:'',
'primary' => $primary[$i]?$primary[$i]:''
];
$i++;
}
dd($emailAddresses);
}

How to restructure the array so is possible to store each answer and question_id in the answers table?

If the user is doing a registration in a conference and selects quantity “1” for registration type general and “1” for registration type plus and click “Next” and goes to the registration form.
In the form, the user needs to introduce the name and surname for each participant this two fields are always mandatory for each participant being registered. Then, the registration type general has 3 custom questions associated with it, so for the registration type general the user also need to answer to that 3 custom questions. The questions and the answers answered by the user in the registration form were this:
Question Answer
input text custom question text answer
long text custom question: long answer
checkbox custom question: check1answer
With the registration form below, and with the answers above, the participant array in the $request->all() shows like below. The name, surname, rtypes is stored properly but the answers and question_id are not be stored very properly in the array:
"participant" => array:2 [▼
1 => array:15 [▼
"name" => "John"
"surname" => "W"
0 => array:1 [▼
"answer" => "text answer"
]
1 => array:1 [▼
"question_id" => "1"
]
2 => array:1 [▼
"answer" => "long answer"
]
3 => array:1 [▼
"question_id" => "2"
]
4 => array:1 [▼
"answer" => "check1answer"
]
5 => array:1 [▼
"question_id" => "3"
]
"rtypes" => "1"
]
2 => array:3 [▼
"name" => "Jake"
"surname" => "K"
"rtypes" => "4"
]
]
With the data stored like that using this foreach to insert the participants and the answers in the database shows "Undefined index: answer" in $participant['answer']:
foreach ($participants_list as $participant) {
$name = $participant['name'];
$surname = $participant['surname'];
$participant_result = Participant::create([
'name' => $name,
'surname' => $surname,
'registration_type_id' => $participant['rtypes']
]);
Answer::create([
'participant_id' => $participant_result->id,
'answer' => $participant['answer'],
'question_id' => $participant['question_id']
]);
}
Do you know to strucutre the participant array so solve the issue? So is possible to store correctly the answers of each participant and the question_id in the answers table?
The $participant[0]['answer'] shows "text answer".
The $participant[1]['answer'] shows "undefined index answer".
The $participant[2]['answer'] shows "long answer".
The $participant[3]['answer'] shows "undefined index answer".
Im a beginner but maybe a structure like this allow to use the foreach to store in the answers table. Each index of the array stores all info associated with each participant (name, surname, registration type where the participant is being registered and if there are custom questions associated with the registration type is also necessary to store the answers:
"participant" => array:2 [▼
1 => array:15 [▼
"name" => "John"
"surname" => "W"
"answer" => [
0 => "text answer"
1 => "long answer"
2 => "check1"
]
"question_id" => [
0 => "1"
1 => "2"
2 => "3"
]
"rtypes" => "1"
]
2 => array:3 [▼
"name" => "Jake"
"surname" => "K"
"rtypes" => "4"
]
]
The participant in index 2 is being registered in the registration type "plus" that has id 4 and this registration type dont have any custom question associated. So is only necessary to collect the name, surname and the registration type id. So this is ok for the participant 2 because dont have custom questions.
Registration Form:
<form method="post" action="https://proj.test/conf/1/conf-test/registration/store">
<h6>Participant - 1 - general</h6>
<div class="form-group">
<label for="namegeneral_1">Name</label>
<input type="text" required id="namegeneral_1" name="participant[1][name]" class="form-control" value="">
</div>
<div class="form-group">
<label for="surnamegeneral_1">Surname</label>
<input type="text" required id="surnamegeneral_1" class="form-control" name="participant[1][surname]" value="">
</div>
<div class="form-group">
<label for="participant_question">input text custom question</label>
<input type='text' name='participant[1][][answer]' class='form-control' required>
<input type="hidden" name="participant_question_required[]" value="1">
<input type="hidden" value="1" name="participant[1][][question_id]"/>
</div>
<div class="form-group">
<label for="participant_question">long text custom question</label>
<textarea name='participant[1][][answer]' class='form-control' rows='3' required></textarea>
<input type="hidden" name="participant_question_required[]" value="1">
<input type="hidden" value="2" name="participant[1][][question_id]"/>
</div>
<div class="form-group">
<label for="participant_question">checkbox custom question</label>
<div class='checkbox-group required'>
<div class='form-check'>
<input type='checkbox' name='participant[1][][answer]' value='select1' class='form-check-input' >
<label class='form-check-label' for='exampleCheck1'>check1</label>
</div>
<div class='form-check'>
<input type='checkbox' name='participant[1][][answer]' value='select2' class='form-check-input' >
<label class='form-check-label' for='exampleCheck1'>check2</label>
</div>
</div>
<input type="hidden" name="participant_question_required[]" value="1">
<input type="hidden" value="3" name="participant[1][][question_id]"/>
</div>
<input type="hidden" name="participant[1][rtypes]" value="1"/>
<h6>Participant - 2 - plus</h6>
<div class="form-group">
<label for="nameplus_2">Name</label>
<input type="text" required id="nameplus_2" name="participant[2][name]" class="form-control" value="">
</div>
<div class="form-group font-size-sm">
<label for="surnameplus_2">Surname</label>
<input type="text" required id="surnameplus_2" class="form-control" name="participant[2][surname]" value="">
</div>
<input type="hidden" name="participant[2][rtypes]" value="4"/>
<input type="submit" class="btn btn-primary" value="Register"/>
</form>
You need to manipulate your original code in such a way that you will get the desired format via that code only.
But if you don't have control on that code, then try to manipulate your current array structure to make it in desired format using below code:-
$final = array();
foreach($array['participant'] as $key=>$val){
$final['participant'][$key]['name'] = $val['name'];
$final['participant'][$key]['surname'] = $val['surname'];
$answer_array = array_column($val,'answer');
$question_id_array = array_column($val,'question_id');
if(is_array($answer_array) && count($answer_array) >0){
$final['participant'][$key]['answer'] = $answer_array;
}
if(is_array($question_id_array) && count($question_id_array) >0){
$final['participant'][$key]['question_id'] = $question_id_array;
}
$final['participant'][$key]['rtypes'] = $val['rtypes'];
}
print_r($final);
Output:-https://eval.in/1048496

How to get each question_id and answer from the array?

If the user is doing a registration in a conference, and is registering 1 participants in the registration type with id "1" (Jake K), and 1 participant in the regitration type with id "4" (John W), the request with the form data has this 3 arrays:
"name" => array:2 [▼
1 => array:1 [▼
1 => "Jake"
]
4 => array:1 [▼
1 => "John"
]
]
"surname" => array:2 [▼
1 => array:1 [▼
1 => "K"
]
4 => array:1 [▼
1 => "W"
]
]
"answer" => array:1 [▼
1 => array:1 [▼
1 => array:2 [▼ // answers answered for the registration_type_id 1
1 => "answer1"
2 => "answer2"
]
]
]
Is necessary to use the info of this array to insert in the participants and answers table. Its inserting correctly in the participants table but for the answers table is not working:
foreach ($request->all()['name'] as $key => $nameArray) {
foreach ($nameArray as $nameKey => $name) {
// this is working
$participant_result = Participant::create([
'name' => $name,
'surname' => $request['surname'][$key][$nameKey],
'registration_id' => $registration->id,
'registration_type_id' => $key
]);
// save answer to Database if exist
// this is not working
$answer = Answer::create([
'question_id' => $request['answer'][$key], // the issue is here
'participant_id' => $participant_result->id,
'answer' => $request['answer'][$key][$nameKey], // and here
]);
}
}
The issue is because is necessary to insert in the question_id and answer columns of the answers table. But this values are not returned correctly from the array with "$request['answer'][$key]" and "$request['answer'][$key][$nameKey]".
Do you know how to properly get the question id and answer from the array?
In this above array example, the question id of the "answer1" is 1 and the id of the "answer2" is 2.
"answer" => array:1 [▼
1 => array:1 [▼
1 => array:2 [▼
1 => "answer1"
2 => "answer2"
]
]
Form:
<form method="post"
action="https://proj.test/conference/1/conf-test/registration/storeRegistration">
<h6> Participant - 1 - general</h6>
<div class="form-group">
<label for="namegeneral_1">Name</label>
<input type="text" required id="namegeneral_1" name="name[1][1]" class="form-control" value="">
</div>
<div class="form-group">
<label for="surnamegeneral_1">Surname</label>
<input type="text" id="surnamegeneral_1" class="form-control" name=" surname[1][1]" value="">
</div>
<div class="form-group">
<label for="participant_question">Question 1</label>
<input type='text' name='answer[1][1][1]' class='form-control' required>
<input type="hidden" name="question_required[1][1]" value="1">
</div>
<div class="form-group">
<label for="participant_question">Question 2</label>
<textarea name='answer[1][1][2]' class='form-control' rows='3' required></textarea>
<input type="hidden" name="question_required[1][2]" value="1">
</div>
<h6> Participant - 1 - plus</h6>
<div class="form-group">
<label for="nameplus_1">Name</label>
<input type="text" required id="rnameplus_1" name="rname[4][1]" class="form-control" value="">
</div>
<div class="form-group">
<label for="surnameplus_1">Surname</label>
<input type="text" id="rsurnameplus_1" class="form-control" name=" rsurname[4][1]" value="">
</div>
<input type="submit" class="btn btn-primary" value="Register"/>
</form>
Firstly: in loop you have more than one name, but answer has one key (1). On second run you have $key == 4, but not have this in $request['answer']. Maybe inside first loop you shoud have two loops? One for registering participants and one for registering answers? If answers are registered for both, build array with $participantResult and for every answer register count($participantResult) answers :O If not, remember ID only for first registered participant and save answer.
Please tell me how $request['answer'] works? What is $request['answer'][1] and what $request['answer'][1][1]?
Secondly $request['answer'][$key][$nameKey] in this case is array of two elements. If Answer::create knows about it - it's no problem ;)
EDIT
Is this right solution?
<?php
$aPID = [];
foreach ($request->all()['name'] as $key => $nameArray) {
foreach ($nameArray as $nameKey => $name) {
$aPID[$key] = Participant::create([
'name' => $name,
'surname' => $request['surname'][$key][$nameKey],
'registration_id' => $registration->id,
'registration_type_id' => $key
]);
}
}
foreach($request['answer'] as $pid => $answersArray) {
foreach($answersArray as $questionId => $answer) {
$answer = Answer::create([
'question_id' => $questionId,
'participant_id' => $aPID[$pid],
'answer' => $answer,
]);
}
}

Silex render form - ChoiceType

(and sorry for my English)
I am working on a Silex project and I start using the form.
Without form, i have something like this :
And using the form I would like to have the same thing (for the select)
End with the form i have this :
As you can see the rendering is not great.
I would like to get a few things like:
<option value="1">Méthode</option>
<option value="2">Marketing</option>
<option value="3">Production</option>
At the code level, I have something very simple (
I start on the forms, be indulgent haha) :
Controller :
public function add(Application $app, Request $request) {
if (! $app['security.authorization_checker']->isGranted('ROLE_ADMIN')) {
return new Response('Access Denied!', 403);
}
$repo = new DepartementRepository($app);
$departements = $repo->getAllDepartements();
$data = [];
$erreurs = [];
$form = $app['form.factory']->createBuilder(FormType::class, $data)
->add('nom',null,array('label' => 'Nom :'))
->add('prenom',null,array('label' => 'Prenom :'))
->add('departement_id',ChoiceType::class,array('choices' => $departements,'label' => 'Departement :'))
->add('ville',null,array('label' => 'Ville :'))
->add('salaire',null,array('label' => 'Salaire :'))
->add('date_embauche',null,array('label' => 'Date d\'embauche :'))
->getForm();
$form->handleRequest($request);
if ($form->isValid())
{
$data = $form->getData();
}
return $app['twig']->render('employe/new.html.twig', array('form' => $form->createView(),'erreurs'=> $erreurs));
}
if i dump my $departements variable, i have this :
array:4 [▼
0 => array:2 [▼
"id" => "2"
"nom_dep" => "Marketing"
]
1 => array:2 [▼
"id" => "3"
"nom_dep" => "Méthode"
]
2 => array:2 [▼
"id" => "1"
"nom_dep" => "Production"
]
3 => array:2 [▼
"id" => "4"
"nom_dep" => "Recherche et developpement"
]
]
And my view :
<form action="#" method="post">
{{ form_widget(form) }}
<input type="submit" name="submit" />
</form>
Before I did that:
{% for departement in departements %}
<option value="{{ departement.id }}"
{% if donnees.departement_id is defined and departement.id == donnees.departement_id %}selected{% endif %}>
{{ departement.nom_dep }}
</option>
{% endfor %}
But I do not know how to do this with the form.
Any help is welcome.
Thanks !!
ChoiceType takes an array as parameter:
Array style (like your current repo)
$departements = $repo->getAllDepartements();
$departementChoices = [];
foreach( $departements as $departement) {
$departementChoices[$departement["id"]] = $departement["nom_dep"]
}
Object style
$departements = $repo->getAllDepartements();
$departementChoices = [];
foreach( $departements as $departement) {
$departementChoices[$departement->getId()] = $departement->getLabel()
}

Categories