How to get double request name to array in laravel? - php

Result from MODAL:
Result from FORM:
DESCRIPTION:
So I wanna make a FORM from MODAL that will send data to actual FORM's table, but at the first IMAGE that not send like the FORM one.
CODE:
This is code from FORM attribute:
public function setLandCertificateIdAttribute($values)
{
// dd($values);
$this->attributes['land_certificate_id'] = implode(',', $values);
}
This is code using MODAL:
public function form(Model $model)
{
$this->multipleSelect('land_certificate_id', 'Nomor Sertifikat')
->options(LandCertificate::where('data_order_id', $model->id)->pluck('number', 'id'));
}
And the MODAL always return : implode(): Invalid arguments passed
I'm using laravel-admin project btw

implode(): Invalid arguments passed: It means that the function is expecting an array of data.
The implode function in PHP is easily remembered as "array to string"
In your modal html set your land_certificate_id name as array.
For example.
<input type="text" name="land_certificate_id[]"></input>

Related

How can I pass input value from view to controller and model to fetch data correctly? Codeigniter

I am trying to fetch a data that has the same id of my input hidden value.
I cannot fetch the id or input hidden value of the data
To start with, this is what I've done to make things clearer for me to debug things I made a hard coded form and a button to bring me to the page
In View - groups/index.php
As you can see I made the posts/index/1 which is a hard coded value but I can change that later easily that is not my problem
<?php echo form_open('posts/index/1') ?>
<input type="hidden" name="txtGroup" value="1" />
<button type="submit" class="btn btn-info"> Submit</button>
</form>
So after I made the form I will make a function in controller to fetch the posts/index
In Controller - Posts.php
public function index(){
$this->load->view('templates/header');
$this->load->view('teachers/posts/index');
$this->load->view('templates/footer');
}
And so I fetched the page. At this point, i can now go through /posts/index/1 and see my page
In my page posts/index.php I have a data and it is fetched through Ajax here it is
So I already fetched this data in posts/showPosts
showAllQuestions();
//Show all data
function showAllQuestions(){
$.ajax({
type: 'ajax',
url: '<?php echo base_url() ?>posts/showPosts',
async: false,
dataType: 'json',
success: function(data){
var html = '';
var i;
var n=1;
for(i=0; i<data.length; i++){
html +='<div class="card">'+
'<div class="card-header" style="color:white; background-color:black">'+
'<h4><span class="iconify" data-icon="ant-design:info-circle-outlined" data-inline="false"></span> Question No. '+ n++ +'</h4>'+
'</div>'+
'<div class="card-body">'+
'<form>'+
'<div class="form-group">'+
'<label for="exampleFormControlTextarea1"><h5> <span class="iconify" data-icon="emojione:check-mark-button" data-inline="false"></span> </h5></label>'+
'<input type="text" value="'+data[i].question+'" class="form-control" disabled />'+
'</div>'+
'<hr>'+
'<span class="iconify" data-icon="el:edit" data-inline="false"></span> '+
'<span class="iconify" data-icon="fa-solid:trash-alt" data-inline="false"></span>'+
// 'Edit '+
'</form>'+
'</div>'+
'</div><br>';
}
$('#showdata').html(html);
},
error: function(){
alert('Could not get Data from Database');
}
});
}
In posts/showPosts - Posts.php, this is the controller
public function showPosts(){
$result = $this->post_model->showPosts();
echo json_encode($result);
}
Finally the Model to Determine if I fetched the correct ID depending on the data id I submit
Problem is the $id is null and I don't have a clue to start with, because I declare a hidden input value on the view page.
public function showPosts(){
// Show questions and answers
$id = $this->input->post('txtGroup');
$this->db->select('*');
$this->db->from('questions');
$this->db->where('group_id', $id);
$query = $this->db->get();
return $result = $query->result_array();
}
I am going to try to understand this question better than your previous one (which is now safe to delete since this is a better description of your issue).
In your groups/index.php view, you want to allow a user to navigate to the posts/index page and pass an integer as a single parameter (which is hard-coded by you, not entered by the user) -- I'll refer to it as $txtGroup for context. Because you are not performing a INSERT|UPDATE|DELETE operation, better practice is to send the data as a $_GET instead of $_POST. Because Codeigniter enables the passing of $_GET parameter as a slash-delimited extension of the url, I don't see any benefit in setting up a <form>.
Style your new hyperlink as a button using your preferred classes.
Link to <?php echo $integer; ?>
This will send your data to the posts/index.php controller. This is where you should be accessing/extracting the $txtGroup value from the url.
Here's where I start to get foggy about what you need. If you want to pass the value to the teachers/posts/index view, then do so by passing an associative array as the second parameter when you load the view.
public function index($txtGroup) {
$this->load->view('templates/header');
// if you want to pass the value to THIS
$this->load->view('teachers/posts/index', ['txtGroup' => $txtGroup]);
$this->load->view('templates/footer');
}
If you are not interested in passing the $txtGroup to the view, then the only other reason to pass the value from groups/index.php to posts/index would be to modify a query and then pass dynamic data to the teachers/posts/index view (which you would need to supply when loading the view anyhow).
public function index($txtGroup) {
$data['posts'] = $this->post_model->showPosts($txtGroup);
$this->load->view('templates/header');
$this->load->view('teachers/posts/index', $data);
$this->load->view('templates/footer');
}
In your model, use the passed argument.
public function showPosts($groupId) {
return $this->db->get_where('questions', ['group_id' => $groupId])->result_array();
}
This way, you don't need to use an ajax call (which looks like you are unconditionally triggering in your view anyhow). Now Codeigniter will work its magic to transfer $data to your view whereby you can access the multidimensional result set as $posts (the variable is named by the first-level key that you assign it). Use a foreach() loop to iterate the rows of results and generate your html content -- all using server-side language.
<?php foreach ($posts as $index => $post) { ?>
<div class="card">
// ... the rest of your content ...
<?php } ?>
As you design the new dynamic content using the above loop:
Use $index as your counter so that you don't have to manually increment.
DO NOT allow INSERT|UPDATE|DELETE operations to be triggered by $_GET events, this is not best practice. Those types of actions should only be initiated by $_POST submissions.

Arguments not working propelry in codeigniter 3

I am trying to pass a string named "publicUsers" in a callback function, but when I display the argument in my console I see the following string... &Z34Sf{;Cr(m
I have included a trait named "VerifyLogin" in my controller which has a function named VerifyAndSetSession
Any help would be really appreciated
below is my code
if(isset($_POST['sign_in']))
{
$this->emailPassValidation("","|callback_VerifyAndSetSession[publicUsers]");
}
This is emailPassValidation method""
function emailPassValidation($new_account_call_back,$sign_in_callback ){
$this->form_validation->set_rules("password","password","required{$sign_in_callback}",
['required' => 'Please enter your %s']);
}
This is where I am debugging the passed arg
trait VeirfyLogIn
{
function VerifyAndSetSession($infoType)
{
fb($infoType, "Infotype");
//This shows in the console.log &Z34Sf{;Cr(m ???
exit;
}
}
Form validation callbacks accept by default one parameter which is the value of the input to check.
It means that :
$this->form_validation->set_rules("field","field","callback_checkField");
Will imply a callback function like this :
public function checkField($field_value){}
If you want to pass extra data to your callback, you can set that value like you did with brackets :
$this->form_validation->set_rules("field","field","callback_checkField['othervalue']");
That new var will not replace the default parameter but add a new one :
public function checkField($field_value, $othervalue){}
So in your case, for :
callback_VerifyAndSetSession[publicUsers]
the function should be :
function VerifyAndSetSession($fieldvalue, $infoType)

Sending ajax request for each element?

I have an app that has rows, each row contains data. The rows are created by the user (just cloning a sample row).
My ajax function looks like this.
save : function(el) {
//Renaming the properties to match the row index and organize
jQuery('#application-builder-layout .builder-row').each(function(row) {
// Iterate over the properties
jQuery(this).find('input, select, textarea').each(function() {
// Save original name attr to element's data
jQuery(this).data('name', jQuery(this).attr('name') );
// Rewrite the name attr
jQuery(this).attr('name', 'application[rows]['+row+'][elements]['+jQuery(this).attr('name')+']');
});
});
//Looping through each row and saving them seperately with new rowkey
setTimeout(function() {
// Iterate over the layers
jQuery('#application-builder-layout .row-box').each(function(row) {
// Reindex layerkey
jQuery(this).find('input[name="rowkey"]').val(row);
// Data to send
$data = jQuery('#application-builder-layout .row-box').eq(row).find('input, textarea, select');
//$data = $data.add( jQuery('#application-builder-layout') );
jQuery.ajax(jQuery('#form').attr('action'), {
type : 'POST',
data : $data.serialize(),
async : false,
success: function( response ) {
//console.log( response );
}
});
});
}, 500);
},
This is the jQuery, it's application style format so this function is inside a var and is called inside a submit function, the problem is not the ajax, looking at it in the console it saves the data fine, just like I have before.
The Problem I cant get all the data into the database (only the last ajax request) take a look below at "Form Data" it shows what my ajax data looks like and how it's inserting into the DB vs how it should insert, I am using json encode and usually this works, but recently I switched to OOP style coding in PHP so I am not sure if that changes anything?
The PHP:
class MyApp {
const Post_Type = 'page';
public function __construct() {
// register actions
add_action('init', array(&$this, 'init'));
}
public function init() {
// Initialize Post Type
add_action('save_post', array(&$this, 'save_post'));
}
//The main save method
public function save_post($post_id) {
// Empty the builder
if($_POST['rowkey'] == 0) {
$builder = array();
}
$builder['rows'][$_POST['rowkey']] = $_POST['application']['rows'][$_POST['rowkey']];
$builder = esc_sql(json_encode($builder));
if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return;
}
if($_POST['post_type'] == self::Post_Type && current_user_can('edit_post', $post_id)) {
// Update the post's meta field
update_post_meta($post_id, 'MY_DATABASE', $builder);
} else {
return;
}
}
}
The above works fine, except its not inserting the data as an array just inserting the last ajax post call, not each. I am sure in my save method I need to reconfig that somehow, but I am just hacking away and cant find info on the web, so I could really use some insight.
I hope I provided enough.
My code summed up: Just to be clear on whats going on here, let me you some basic HTML of my app.
//This gets cloned and the jQuery renames the rowkey to match the index.
<div class="row-box">
<input type="hidden" name="rowkey" value="0">
<div class="builder-row">
<textarea style="display: block;" name="html"></textarea>
<textarea style="display: block;" name="breakingbad"></textarea>
</div>
</div>
So summed up lets say there is 4 rows, the jQuery renames each row, then loops through each and submits an ajax call for each of them. Then the PHP handles the $_POST, in prior applications working with my custom DB I got it to work but working with wp database I am having issues, maybe I am missing something in my method?
Form Data: the ajax form data looks like this (this is the form data inside headers which can be found in the console(firbug) or network(chrome))
//First element
rowkey:0
application[rows][0][elements][html]:A
application[rows][0][elements][breakingbad]:123
Then if there is another row ajax posts again
//Second element
rowkey:1
application[rows][1][elements][html]:B
application[rows][1][elements][breakingbad]:456
So an and so forth, the database looks like this
{"rows":{"2":{"elements":{"html":"B","breakingbad":"456"}}}}
It should be more like this
{"rows":[{"elements":{"html":"A","breakingbad":"123"},{"elements":{"html":"B","breakingbad":"456"}]}
Holy Smokes Batman: I think I got it, It all resides inside how I handle the $_POST ill update soon with an answer..
The database looks good like this
{"rows":[
{"elements":{"html":"A","breakingbad":"123"}},
{"elements":{"html":"B","breakingbad":"456"}}]
}
Now I can continue to build.. whew this was a MASSIVE headache.

Populate form fields from database using Codeigniter

i am trying to populate two form fields from data that is retrieved from a database, in order for the user to update them. The table is called records and it is quite simple:
Record_ID
title
content
My model:
function get_data()
{
$r = $this->uri->segment(3);
$query = $this->db->get_where('records', array('Record_ID' => $r));
return $query->result();
}
My controller:
function set_values()
{
$data = $this->entries_model->get_data();
$this->load->view('update_view', $data);
}
and my update record view:
<?php
echo form_open('site/update',$data);?>
Title:
<?php echo form_input('title',set_value('title'));?>
Content:
<?php echo form_input('content',set_value('content'));
echo form_submit('submit', 'Submit');?>
<?php echo form_close();?>
The problem is that i get the following error:
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: data
Filename: views/update_view.php
Line Number: 10
My question is twofold:
How do i access this data in my view form and
how do i populate the respective fields with it.
I am new to Codeigniter, my questions may look simplistic but any help would be appreciated. Thanks in advance.
There are a few things going on here:
$data is an array or object that is passed to a view. It's ELEMENTS are then available as variables in the view. So, $data['myelement'] = 'somevalue' in the controller would be accessed as $somevalue in the view.
If you pass a 2nd parameter to the form_open() method, it is expected to be a key/value pair of attributes for the tag that will be generated. like, array('class' => 'form_class', 'id' => 'form_id')
If you want to set the values of your form inputs, use the view helper function set_value(). In your case, use the controller to set elements in the $data array you'll pass to the view. $data['form_values'] = array('title' => $title, 'content' => $content);
Then, in the view:
You should pass a array to your view file. So replace:
$data = $this->entries_model->get_data();
with:
$data['entries_data'] = $this->entries_model->get_data();
and on your view file replace:
echo form_open('site/update',$data);?>
with:
echo form_open('site/update',$entries_data);?>
first you need to pass data in proper way
replace
$data = $this->entries_model->get_data();
with:
$data['data'] = $this->entries_model->get_data();
for setting value in set_value you need to do the in-line condition check to check either data is an object or not if object then put value other wise just empty
<?php echo form_input('title',set_value((is_object($data)?$data->title:'')));?>
you have to do the same thing for your all form fields
Jcory has answered your question but let me add a little to it.
In you model instead of return $query->result(); do this return $query->row(); this is because using returning a return object requires that you should loop through the resultset in your view
Instead of $data = $this->entries_model->get_data(); do this $data['entry'] = $this->entries_model->get_data();
In your view do this <?php echo form_input('title',set_value('title',$entry->title));?>
I hope these changes may solve the problem

Insert DB Value into Form Field

The Question: How do I insert values from a database table (#__mytable) into form text fields (motitle and modescription) which have been rendered from an XML file within the Joomla 3.0 platform?
-
I've been trying for days to solve this "easy" Joomla! based undocumented challenge.
I have followed Joomla!'s guide for Developing an MVC, read most of their out-of-date documentation and torn apart the com_content component but have still no idea how to populate my fields.
I've been playing with $this->form->bind($this->item);.
Below I have included some of my code to show the structure I am using. Please feel free to point out any issues you spot along the way.
Models\Forms\item.xml
<?xml version="1.0" encoding="UTF-8"?>
<form>
<fields name="groupOPTIONS">
<fieldset name="Options">
<field
type="text"
name="motitle"
id="motitle"
label="Title"
description="MY TEXT FIELD DESCRIPTION"
maxLength="255" />
<field
type="textarea"
name="modescription"
id="modescription"
label="Description"
description="MY TEXT FIELD DESCRIPTION"
rows="15"
cols="5"
maxLength="255" />
</fieldset>
</fields>
</form>
Models\item.php
jimport('joomla.application.component.modelitem');
class MagicObjectsModelItem extends JModelForm {
public function getForm($data = array(), $loadData = true) {
// Get the form 'items'
$form = $this->loadForm('com_magicobjects.item', 'item',
array('control' => 'jform', 'load_data' => $loadData));
if (empty($form)) {
return false;
}
return $form;
}
protected function loadFormData() {
// Check the session for previously entered form data.
$data = JFactory::getApplication()->getUserState('com_magicobjects.item.edit.data', array());
if (empty($data)) {
$data = $this->getDBItem(1);
}
return $data;
}
public function getDBItem($pk) {
//Obtain JDatabase static connection
$oDb = JFactory::getDbo();
$oQuery = $oDb->getQuery(true);
$sValueToMatch = $pk;
$oQuery
->select(array('mid', 'name', 'keyword', 'description'))
->from('#__mytable')
->where('mid = "' . $sValueToMatch . '"')
->order('mid ASC');
$oDb->setQuery($oQuery);
return $oDb->loadObjectList();
}
views\item\view.html.php
jimport('joomla.application.component.view');
function display($tpl = null) {
// Initialise variables.
$this->form = $this->get('Form');
$this->item = $this->get('Item');
//Display the view
parent::display($tpl);
}
Views\item\tmpl\default.php
foreach ($this->form->getFieldset('Options') as $field) {
echo $field->label;
echo $field->input;
}
By performing a print_r() on item I can see I have the data, but I need to insert the data into the fields shown.
In case this it's still a problem because the form definition is defining a <fields /> group.
This mean that the form fields will be output as follows:
input type="text" name="[groupOPTIONS][motitle]"
based on the example you give above. If you remove the fields grouping it will probably work. It's annoying though as certain JForm methods only work on groups...
You would probably need to change the way in which the data was being passed into the form if you wanted to keep the fields grouping (e.g. by overloading getItem).
Hope that makes sense...
In Joomla 3, the JForm::bind() method appears to accept either an object or associative array as a parameter. All of the object/array fields are then stored in a protected JRegistry type data member called JForm::$data.
When you're trying to display a form field (by calling JForm::getInput()), the call stack is as follows
JForm::getInput() -> JForm::getField() -> JForm::loadField() -> JForm::getValue()
JForm::getValue() returns a value from the (aforementioned JRegistry) JForm::$data data member. The JForm::loadField() method also passes the default value (defined by the form) to the JForm::getValue() method in case a value in the JForm::$data variable doesn't exist.
In terms of doing this inside a model, you might want to generate a object or assoc array from a database query or table (ensuring that the field names correspond with the field names defined in the form xml) and then pass it to JForm::bind() as a parameter. However, if you are using JModelForm, I think you should only override JModelForm::loadFormData() to pass the object/assoc array to the loaded form.
See : libraries/joomla/form/form.php
Hope that helps :)
Instead of $oDb->loadObjectList(); use $oDb->loadAssoc(); in your getDBItem() function.
Check this - http://docs.joomla.org/Accessing_the_database_using_JDatabase/1.5
Check this also - joomla loadformdata
Hope this will work.

Categories