My model (table with 2 primary keys and are foreign key on the same time) :
class FormationPersonnel extends Model
{
protected $fillable = ['cin', 'id_form'];
public $incrementing = false;
}
I create checkboxes with JQuery, Ajax like so :
var grabData = "";
for (let i = 0; i < data.length; i++) {
grabData +=
`<div class="col-lg-4 col-sm-6">
<div class="custom-control custom-checkbox">
<input type="checkbox" name="cin[]" id="`+data[i]["cin"]+`" class="custom-control-input" value="`+data[i]["cin"]+`">
<label for="`+data[i]["cin"]+`" class="custom-control-label">`+data[i]["cin"]+' '+data[i]["nom"]+' '+data[i]["prenom"]+`</label>
</div>
</div>`;
}
personnelsInput.html("");
personnelsInput.append(grabData);
which I give the checkboxes the same name as :
name="cin[]"
In My controller I use this code, but is not storing any data from checkboxes :
$cins = $request->cin; //I get inputs like this
foreach ($cins as $cin) {
$form_pers = new FormationPersonnel; //create new record
if ($request->has($cin)) {
$form_pers->id_form = $request->input('id_form');
$form_pers->cin = $request->input($cin);
$form_pers->save(); //save data
}
}
What is the correct way ?
The correct way to check whether the Model has cin or not is
Edited
based on the comment we put, I think I know what you're trying to do, so do it like below code to get what you need.
note
you don't know what $cins values so that's why you use if(). No need to check whether the user check (checkbox) or not. because the checked value only send by form. please try to know what data you have in your variable before coding.
I recommended you to use dd() or print_r() or others https://laraveldaily.com/echoing-dd-vs-var_dump-vs-print_r/ to check the data you got in your variable.
$cins = $request->cin; //getting all checked (from checkbox) data
foreach ($cins as $cin) {
$form_pers = new FormationPersonnel; //new model
$form_pers->id_form = $request->id_form; //get name="id_form" from form
$form_pers->cin = $cin; //put cin value (loop)
$form_pers->save(); //save
}
Related
I'm using Laravel for my application.
I have made a PRINT button on my HTML page which is simply calling a route, to be able to send it throught DOMPDF to print it to PDF.
Print
Now, in my Controller, I would like to get the value of a radio button which has been created in the HTML this way
<div class="col-lg-7 selectie">
<input type="radio" name="factuur_selectie" id="factuur_selectie" value="1" checked> Alle facturen 
<input type="radio" name="factuur_selectie" id="factuur_selectie" value="2"> Betaalde facturen
<input type="radio" name="factuur_selectie" id="factuur_selectie" value="3"> Onbetaalde facturen
</div>
In my controller I can not find the way to get the value of the checkbox, I suppose because I'm not doing a submit ?
How would I be able to get the value of the radio button please?
public function printFacturen(Request $request){
}
I already tried three following ways, but it is not working :
$fields = Input::get('factuur_selectie');
$value = $request->get('factuur_selectie');
$request->input('factuur_selectie');
Bestregards,
Davy
You need to grab the value of factuur_selectie using JavaScript and add it to the generated URL, something like:
var val = document.querySelector('#factuur_selectie:checked').value;
var btn = document.querySelector('.btn.btn-default');
var url = btn.getAttribute('href');
btn.setAttribute('href', url + '?factuur_selectie=' + val);
Then you should be able to retrieve factuur_selectie from your controller.
Probably you are going to need to update the value everytime an option is selected. In that case you can retrieve the value from then event itself:
var btn = document.querySelector('.btn.btn-default');
document.querySelector('.selectie').addEventListener('change', function(event) {
var val = event.target.value;
var url = btn.getAttribute('href');
var pos = url.indexOf('?');
// If URL already contains parameters
if(pos >= 0) {
// Remove them
url = url.substring(0, pos);
}
btn.setAttribute('href', url + '?factuur_selectie=' + val);
});
Here you have a working example.
In my ng-repeat, scored/not scored are there. I want to display <div> class if at least one item in the ng-repeat has "Not Scored"
You should be determining whether or not you are displaying that div inside your controller. Doing it within the ng-repeat would mean you would have logic in your view and that's just not good practice. Here is a simple example on how to accomplish what you're wanting.
In your controller:
$scope.showDiv = false;
$scope.getItems = function () {
// fetch items via ajax...
for (var i = 0; i < data.items.length; i++) {
if (data.items[i].foo == 'Not Scored') {
showDiv = true;
}
}
}
And on your view:
<div ng-show="showDiv">
// do your ng-repeat here
</div>
So I am trying to validate the input of one item inside of an ng-repeat. For examples sake lets say that I have 5 items (1,2,3,4,5) and I only want to validate the form if the 4th item is selected.
I have used ng-pattern before to validate forms, but not one that had a dropdown menu to select item.name
I have included the regex I would like the 4th item to be validated with inside the ng-pattern.
<div>
<select name="name" ng-model="item.name" ng-options="item for item in items" required></select>
</div>
<div>
<input name="results" type="text" ng-model="item.results" ng-pattern="/^\d\d\d\/\d\d\d/" required>
</div>
Any suggestions as to the correct way to validate this situation would be greatly appreciated. I have thought about creating a directive to validate this, but that feels like is an overly complicated solution to this since I would not use the directive more than once in this app.
//////////////////////////////////////////////////
It wouldn't let me answer my own question so here is the answer I figured out.
What I ended up having to do was use ng-pattern and pass it a function.
<input name="results" type="text" ng-model="vital.results" ng-pattern="vitalRegEx()" required>
Here is the controller code
$scope.item4RegEx = /^\d{2,3}\/\d{2,3}$/;
$scope.itemRegEx = function() {
if($scope.item && $scope.item.name === "fourth item")
return $scope.item4RegEx;
else return (/^$/);
};
or else...
add ng-change directive on the select dropdown which calls a Controller method and that controller method sets a flag whether to validate form or not.
eg.
<select ng-change="checkIfFormShouldbeValidated()" ng-model="item.name"></select>
// Inside controller
$scope.checkIfFromShouldBeValidated = function(){
if( $scope.item.name == 4th Item ) $scope.shouldValidate = true;
else $scope.shouldValidate = false;
};
$scope.formSubmit = function(){
if(($scope.shouldValidate && form.$valid) || (!$scope.shouldValidate)){
// Submit Form
}
};
See if it helps.
I wrote this recursive function inside my controller to check the validity of all child scopes.
function allValid(scope) {
var valid = true;
if (scope.$$childHead) {
valid = valid && allValid(scope.$$childHead);
}
if (scope.$$nextSibling) {
valid = valid && allValid(scope.$$nextSibling);
}
if (scope.scorePlannerForm) {
valid = valid && scope.myForm.$valid;
}
return valid;
}
Then in my controller I check this with the controller scope.
function formSubmit() {
if (allValid($scope)) {
// perform save
}
}
I am working with a registered_member_data_edit page?
My controller function is
function edit_profile()
{
$data['title']= 'Edit Profile';
$member_id = $this->session->userdata('member_id');
$this->load->model('user_model','',TRUE);
$data['row'] = $this->user_model->edit_user($member_id)->result();
$this->load->view('edit_profile.php', $this->data);
}
My model function is
public function edit_user($member_id)
{
$this->db->select('fullname','country','district','address','nominee_name','nominee_relation','mobile_no','password','bank_acc_no','bank_acc_name','bank_name','branch_name');
return $this->db->get_where('user', array('member_id'=> $member_id));
}
My view page is like
<p><label>User Name</label>
<input type="text" class="input-short" value="" /></p>
What should I put in the value to show the db data in edit page?
public function edit_user($member_id)
{
$this->db->select('fullname','country','district','address','nominee_name','nominee_relation','mobile_no','password','bank_acc_no','bank_acc_name','bank_name','branch_name');
return $this->db->get_where('user', array('member_id'=> $member_id));
}
this will return the object, which you have in $data['row'] and that variable you are sending to view file.
So in view file, you can access the all data of the object using $row.
So from here you have 2 options
Even that function returning only 1 row, you have to access using foreach($row->result() as $_data) and after that you can access each and every column as $_data->fullname like that.
You can convert that object to array using $row = $row->result_array() and you can access the database column using $row[0]['fullname'] like that.
Best luck.
If this was a problem with MVC3, there would be posts out there about this, but I can't find any. I must be doing something wrong. I have a simple view (Index.cshtml) that iterates through a list using a for loop. In each iteration, I output two text inputs with values from one of the list items.
#{Html.BeginForm();}
#Html.Encode("\n")
#for (int i = 0; i < Model.SortOptions.Count; i++ )
{
#Html.TextBoxFor(m => m.SortOptions[i].ColumnName);
#Html.Encode("\n");
#Html.TextBoxFor(m => m.SortOptions[i].Direction);
#Html.Encode("\n");
}
<input type="submit" value="Submit" />
#{Html.EndForm();}
I have two controllers for the view, one for GET requests and one for POST. The POST version adds different items to the list than the GET version. This is where the problem comes in. After the page has re-loaded, the text boxes have the same value as when the page loaded on the GET.
At first I thought it must be a caching issue, but if I modify the code (as seen below), to manually add the text inputs and inject the values into the html, the new values are sent to the browser.
#{Html.BeginForm();}
#Html.Encode("\n")
#for (int i = 0; i < Model.SortOptions.Count; i++ )
{
var columnNameName = string.Format("SortOptions[{0}].ColumnName", i);
var columnNameID = string.Format("SortOptions_{0}__ColumnName", i);
var directionName = string.Format("SortOptions[{0}].Direction", i);
var directionID = string.Format("SortOptions_{0}__Direction", i);
<input type="hidden" name="#columnNameName" id="#columnNameID" value="#Model.SortOptions[i].ColumnName" />
<input type="hidden" name="#directionName" id="#directionID" value="#Model.SortOptions[i].Direction" />
}
<input type="submit" value="Submit" />
#{Html.EndForm();}
I've stepped through the code to ensure that the model contains the expected values at the time they are sent to the view. I even inspected the values of the list by stepping through the code in the view. It appears to have the correct values, but when I view it in the browser, it has the values that should correspond to when the page responded to the GET request. Is this a problem with the editor templates? I just started using mvc3 and the razor engine, so there is a lot I don't know. Any help would be appreciated.
----- UPDATE: ADDED CONTROLLER CODE ----
[HttpGet]
public ActionResult Index()
{
var inv = new InventoryEntities();
var model = new IndexModel(inv);
model.SortOptions = new List<SortOption>();
model.SortOptions.Add(new SortOption { ColumnName = "Model", Direction = SortDirection.Ascending });
model.SortOptions.Add(new SortOption { ColumnName = "Make", Direction = SortDirection.Ascending });
//Load data
model.LoadEquipmentList();
return View(model);
}
[HttpPost]
[OutputCache(Duration = 1)]
public ActionResult Index(List<SortOption> sortOptions, SortOption sort)
{
var inv = new InventoryEntities();
var model = new IndexModel(inv);
ModelState.Remove("SortOptions");
model.SortOptions = new List<SortOption>();
model.SortOptions.Add(new SortOption { ColumnName = "Type", Direction = SortDirection.Descending });
model.SortOptions.Add(new SortOption { ColumnName = "SubType", Direction = SortDirection.Descending });
model.EquipmentList = new List<EquipmentListItem>();
model.EquipmentList.Add(new EquipmentListItem { ID = 3, AssignedTo = "Mike", Location = "Home", Make = "Ford", Model = "Pinto", Selected = false, SubType = "Car", Type = "Vehicle" });
return View(model);
}
Remember that Html helpers such as TextBoxFor first use the model state when binding their values and after that the model. Let's consider a very simple example in order to illustrate what this means:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyViewModel { Name = "foo" });
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
model.Name = "bar";
return View(model);
}
}
and the view:
#model MyViewModel
#using (Html.BeginForm())
{
#Html.TextBoxFor(x => x.Name)
<input type="submit" value="OK" />
}
Now when you submit the form you will expect that the value in the textbox changes to "bar" as that's what you've put in your POST action but the value doesn't change. That's because there is already a value with the key Name in the model state which contains what the user entered. So if you want this to work you need to remove the original value from the model state:
[HttpPost]
public ActionResult Index(MyViewModel model)
{
// remove the original value if you intend to modify it here
ModelState.Remove("Name");
model.Name = "bar";
return View(model);
}
The same thing happens in your scenario as well. So you might need to remove the values you are modifying from the model state in your POST action.
A couple things pop out at me - without seeing a bit more it's hard to say but...both of these could be rewritten as such. The extra # symbols are not necessary.
#using(Html.BeginForm()) {
Html.Encode("\n")
for (int i = 0; i < Model.SortOptions.Count; i++ ) {
Html.TextBoxFor(m => m.SortOptions[i].ColumnName);
Html.Encode("\n");
Html.TextBoxFor(m => m.SortOptions[i].Direction);
Html.Encode("\n");
}
<input type="submit" value="Submit" />
}
#using (Html.BeginForm()) {
Html.Encode("\n");
for (int i = 0; i < Model.SortOptions.Count; i++ ) {
var columnNameName = string.Format("SortOptions[{0}].ColumnName", i);
var columnNameID = string.Format("SortOptions_{0}__ColumnName", i);
var directionName = string.Format("SortOptions[{0}].Direction", i);
var directionID = string.Format("SortOptions_{0}__Direction", i);
<input type="hidden" name="#columnNameName" id="#columnNameID" value="#Model.SortOptions[i].ColumnName" />
<input type="hidden" name="#directionName" id="#directionID" value="#Model.SortOptions[i].Direction" />
}
<input type="submit" value="Submit" />
}
Otherwise your stuff looks right and I can't see anything wrong off the top of my head.