CakePHP 3.3 - Formbuilder first value to be 1 - php

I got a problem with CakePHP formbuilder. The first value of the options have to be 1 instead of 0.
View:
<div class="form-group">
<label class="col-md-3 control-label" for="competentie">Competenties</label>
<div class="col-md-6">
<?php echo $this->Form->input('competence._ids',['class'=>'form-control ','options'=> $competence,'div'=>false,'label'=>false]); ?>
</div>
</div>
Controller:
$category = $this->Cv->Category->find('list', ['keyField' => 'category_id', 'valueField' => 'category']);
$this->set(compact('cv', 'category'));
$this->set('_serialize', ['cv']);
Any idea how i can make it start at value 1? Instead of 0.
Screenshot of it: https://i.gyazo.com/5ebeeeccc11ee08762efd9a84ba357ba.png

Does categories table have category_id field ?
If not you may trying to do:
$category = $this->Cv->Category->find('list',
['keyField' => 'id', 'valueField' => 'category']);
Otherwise look at the debug value one more time and confirm if data are coming correctly.

Related

Posting arrays Laravel 8 - values returning as NULL

I am trying to post an array from my form to database
The form fields are showing up as NULL
HTML form excerpt:
#foreach (range(0,9) as $x)
<div class="row m-3 credit-card-details">
<div class="col-lg-4">
<div class="form-group">
<label for="financeCompany-{{ $x }}">Finance Company name #{{ $x }}</label>
<input type="text" class="form-control" id="financeCompany-{{ $x }}" name="creditCards[{{ $x }}][financeCompany]" value="" placeholder="Finance Company Name" />
</div>
</div>
<div class="col-lg-4">
<div class="form-group">
<label for="creditLimit-{{ $x }}">Credit limit</label>
<input type="text" class="form-control" id="creditLimit-{{ $x }}" name="creditCards[{{ $x }}][creditLimit]" value="" placeholder="$" />
</div>
</div>
<div class="col-lg-4">
<div class="form-group">
<label for="consolidate-{{ $x }}">Consolidate this card?</label>
<input type="text" class="form-control" name="creditCards[{{ $x }}][consolidate]" id="consolidate-{{ $x }}" value="" />
</div>
</div>
</div>
#endforeach
My Controller:
public function store(CreateApplicationRequest $request, Applicant $applicant, CreditCard $creditCard)
{
$applicant = Applicant::create([
...
]);
$application = $applicant->application()->create([
...
]);
$creditCards = $request->input('creditCards');
foreach ($creditCards as $creditCard)
{
$application->creditCards()->create([
'financeCompany' => $request->input('financeCompany'),
'creditLimit' => $request->input('creditLimit'),
'consolidate' => $request->input('consolidate')
]);
}
...
}
My dd results are showing up like this:
The right amount of records are being created in my credit_cards table and the application_id, created_at and updated_at fields are being correctly recorded, however the financeCompany, creditLimit and consolidate fields (from the form) are all showing up as NULL.
Database:
CreditCard model:
protected $fillable = [
'application_id',
'financeCompany',
'creditLimit',
'consolidate'
];
Only the application_id is being collected by the database.
Still quite new at this, any help would be greatly appreciated.
so your request() has $creditCards by the look of it. The values you are interested in seems to be within $creditCards
you need to do something like this
collect($creditCards)
->each(fn ($creditCard) => $application->creditCards()
->create([
'financeCompany' => creditCard['financeCompany'],
'creditLimit' => creditCard['creditLimit'],
'consolidate' => creditCard['consolidate']
])
);
or if you want to use foreach
foreach ($creditCards as $creditCard) {
$application->creditCards()->create([
'financeCompany' => creditCard('financeCompany'),
'creditLimit' => creditCard('creditLimit'),
'consolidate' => creditCard('consolidate')
]);
}
Make sure you have them declared in the $fillable in your model otherwise the ORM will not pick them up.
Example:
protected $fillable = [
'financeCompany',
'creditLimit',
'consolidate',
];

I have this Select form from Laravel collectives and everything I try always returns null on the controller

I want to return the value on controller but it always returns null and I can't find the issue here.
Laravel View
<div class="form-group">
<label> {{ trans('content.Keep it private')}} </label>
{!! Form::select('is_private', array('0' => trans("content.yes"), '1' => trans("content.no")), '0'); !!}
</div>
Laravel Controller
dd(Input::get('is_private'))

Laravel 5.7 validate fields with asterisk, required_if

I have a Vue form that let users add work experience for there profile.
Users can add extra experience by clicking on a button. Clicking on that will add an new item with new input fields. I can't add the whole script because it's quit big. But here is an example to give you an idea:
<div class="item">
<div class="row">
<div class="form-group col-md-6">
<label class="form-label">Title</label>
<input type="text" name="experiences[0][title]" class="form-control">
</div>
<div class="form-group col-md-6">
<label class="form-label">Institution</label>
<input type="text" name="experiences[0][institution]" class="form-control">
</div>
</div>
<div class="row">
<div class="col-md-12">
<textarea name="experiences[0][comments]" class="form-control"></textarea>
</div>
</div>
</div>
<div class="item">
<div class="row">
<div class="form-group col-md-6">
<label class="form-label">Title </label>
<input type="text" name="experiences[1][title]" class="form-control">
</div>
<div class="form-group col-md-6">
<label class="form-label">institution </label>
<input type="text" name="experiences[1][institution]" class="form-control">
</div>
</div>
<div class="row">
<div class="col-md-12">
<textarea name="experiences[1][comments]" class="form-control"></textarea>
</div>
</div>
</div>
After each element there is a button to add a new row. This works fine but I have some validation issues.
I only want to validate the fields if one of the fields has a value. For example:
If experiences[0][institution] has a value, experiences[0][title] and experiences[0][comments] are required.
This has to work in every order. If title has a value, the other fields are required.
I can't really find out a way how to validate this. This is my validation rule:
$this->validate(request(), [
'experiences.*.title' => 'required_if:experiences.*.institution,null',
'experiences.*.institution' => 'required_if:experiences.*.title,null',
]);
Problem here is that it simply doesn't validate. I can't figure out how to make a rule that says, if field X has a value, Y and Z are required.
Hope anyone here can help me finding a solution! :)
Like Azeame said, make a custom validation rule and check if all values are filled or all are empty. Something in de lines of:
public function passes($attribute, $value)
{
$required = ['title','institution','comments'];
$experience = collect($value)->reject(function ($item, $key) {
return empty($item);
});
if (count($experience) == 0) {
return true;
}
foreach ($required as $field) {
if ( !$experience->has($field)) {
return false;
}
}
return true;
}
Maybe there is a beter way, but this should work.
required_if doesn't work with null as it will treat it as a string ("null"), it will work with boolean values though.
Instead you can use the required_without rule:
$this->validate(request(), [
"experiences.*.title" => "required_without:experiences.*.institution",
"experiences.*.institution" => "required_without:experiences.*.title",
]);
Example
$experiences = [
[
"title" => "My title",
"institution" => "",
"comments" => "<p>My first description</p>", //passes
],
[
"title" => "",
"institution" => "My title",
"comments" => "<p>My second description</p>", //passes
],
[
"title" => "My title",
"institution" => "My title",
"comments" => "<p>My third description</p>", //passes
],
[
"title" => "",
"institution" => null,
"comments" => "<p>My forth description</p>", //fails
],
];
$rules = [
"experiences.*.title" => "required_without:experiences.*.institution",
"experiences.*.institution" => "required_without:experiences.*.title",
];
$validator = Validator::make(compact('experiences'), $rules);
dd($validator->fails());
Write a custom rule with php artisan make:rule and in the passes() function write a check to ensure that all of the array keys are present and also that at least 2 of the array values are not null. I'm thinking something like this:
function passes($attribute, $value){
if(array_keys($value) !== ['title','institution','comments']){
return false;
}
if(empty($value['title']) && empty($value['institution'])){
return false;
}
return true;
}
and in your $this->validate pass the rule as ['experiences.*' =>['array', new CustomRule()] instead of required_if...
I haven't checked this so feel free to edit if it's broken.

How to Customizing/add a class to the ActiveForm items with Material Bootstrap design classes on Yii2

I'm trying to add a class for a TextField like this one:
<div class="form-group-lg">
<?= $form->field($model, 'email'); ?>
</div>
Output:
And that would be something like this?(the label will be inside the TextField).i mean, can we use it like below codes?
Example:
I need something like this:
<div class="form-group label-floating">
<label class="control-label" for="focusedInput1">Write something to make the label float</label>
<input class="form-control" id="focusedInput1" type="text">
</div>
http://fezvrasta.github.io/bootstrap-material-design/bootstrap-elements.html
Forms section-first one.
So, the question is,
How can i add a class to this item with above codes on Yii2 ActiveForm?
You need to use fieldConfig Propertie in ActiveForm.
Like as
<?php $form = ActiveForm::begin([
'id' => 'active-form',
'fieldConfig' => [
'template' => "<div class=\"form-group label-floating\">{label}{input}{error}</div>",
],
]); ?>
For more info read Docs

inserting array value to database laravel

I have a form attributes called, name, description and features where features is a multiple checkboxes which is like
feature 1
feature 2
feature 2
feature 4
User can select multiple checkbox at once. I have a database table called product like
-----------------------------------------
id name description features
-----------------------------------------
When user selects the multiple checkbox, i need to insert all checkbox value in the features column. Right now I can echo the selected checkbox value like
$feat = Input::get('features');
foreach ($feat as $key => $n){
echo $feat[$n];
}
but I need those features to insert into the database, for normal insertion, we would do like:
$product = new Product;
$product->name = Input::get('name');
$product->description = Input::get('description');
$product->features = Input::get('features');
$product->save();
but how should i modify the above code in order to save the array value to the database? I am trying to insert the value to same column because i won't be querying it on the basis of features.
It's quite simple. If you know that you won't query the features, it's perfectly fine to store them as Json or a serialized array. But if you will need to query them and they are a key aspect of your application, you should put them in their own table.
I prefer to store arrays in Json-format because it's easier to read and is not specific to PHP. Laravel gives you pretty sweet options to make this work.
At first, declare the features-field of you products-table as json in your migration:
Schema::create('products', function (Blueprint $table) {
// ...
$table->json('features');
});
Then tell your Product-model to automatically cast it to an array when you access it by simply setting a $casts-attribute:
class Product extends Model
{
// ...
protected $casts = [
'features' => 'json'
];
}
That's it. Now the array will be stored as Json, but when you access it with $product->features you'll get an array back.
To make everything even more simple, you should set up a fillable attribute on your Product model:
class Product extends Model
{
// ...
protected $fillable = ['name', 'description', 'features'];
}
This allows for doing something like this in your controller (or wherever you create the product):
$product = Product::create(Input::all());
...instead of newing it up and setting the attributes one by one.
And as mentioned above, be sure you don't need the features to be query-able, meaning you won't encounter situation where you're trying to get certain products only having specific features or something. But if you do need to look up features, you should put them in their own table. Otherwise this approach is just fine because it's more convenient.
Please look to database normalization for information how to store Data which is in a 1:N relationship. You have to create an extra table like "product_feature" with the attributes: ['id', 'product_id', 'function_name'].
Then your Insert function looks like this:
$product = new Product;
$product->name = Input::get('name');
$product->description = Input::get('description');
$product->save();
$feat = Input::get('features');
foreach ($feat as $key => $n){
$product_function = new ProductFunction;
$product_function->product_id = $product->id;
$product_function->function_name = $feat[$n];
$product_function->save();
}
Hope it helps!
You could use the json_encode function to save the array as a json string.
$product->features = json_encode(Input::get('features'));
But I will also agree with #AdrianBR it is a bad idea to saving the array value to the database in a single column.
I had something similar to this although i used ajax to send the values
<div class="row mb-3" id="insert_new_item">
<div class="col-lg-6">
<p>Item Description</p>
<input value="" type="text" name="order[description]" class="form-control product " id="" placeholder="Your Item Description">
</div>
<div class="col-lg-1 col-sm-6 col-12 mt-lg-0 mt-3">
<p>Qty</p>
<input placeholder="0" type="text" name="order[quantity]" min="1" class="text-right form-control qty" id="" min="1">
</div>
<div class="col-lg-2 col-sm-6 col-12 mt-lg-0 mt-3">
<p>Rate/Unit (₦ )</p>
<input placeholder="0.00" type="text" name="order[rate]" class="text-right form-control rate" id="">
</div>
<div class="col-lg-2 mt-lg-0 mt-3">
<p>Amount (₦ )</p>
<input type="text" name="order[amount]" id="" class="text-right form-control amount" readonly value="0" >
</div>
<div class="col-lg-1">
<span><i class="fa fa-times text-danger removeItem" style="font-size: 22px"></i></span>
</div>
So when i console.log(any value) i get this:
["0" : "value 1", "1" : "value 2"]
from my controller i can do this
foreach ($request->description as $key => $description) {
$order = Order::create([
'description' => $description,
'amount' => $request->rate[$key],
'quantity' => $request->quantity[$key],
'invoice_id' => 7
]);
}
You can insert like this,
$candidate_data = array(
'mobile' => $request->get('mobile'),
'password' => $request->get('password')
);
DB::('tablename')->insert($candidate_data);

Categories