I need to post an array of data with the index number of the line. (If I send without the index in brackets, only the last item is being picked up by the server)
Problem is that js doesn't allow me to use brackets in the key name...
I tried to build a string with all the array data as key[0] : 'value' and than passed it in as one of the param, but that didn't work either.
Meteor.methods({
submit_order: function(){
var test = HTTP.call("POST", "https://example.com/api/",
{
headers:
{
"Content-Type": "application/x-www-form-urlencoded"
}
,
data : {ApiLogin:'login',
ApiKey:'key',
OrderNumber:'ReactTest1',
Items[0][ProductQty] : '1', <--- problem is here
Items[1][ProductQty] : '2'
},
},
function (error, result) {
if (!error) {
console.log(result);
} else{
console.log("http post error");
};
});
}
});
In PHP its written as follows:
'Items' => array(
1 => array(
'ProductQty' => 2,
),
2 => array(
'ProductQty' => 1,
),
3 => array(
'ProductQty' => 1,
)
),
You are close, you just need to set up the array in the following way:
{
ApiLogin:'login',
ApiKey:'key',
OrderNumber:'ReactTest1',
Items:[{ProductQty : '1'},{ProductQty : '2'}]
}
Related
I have an array that makes in front end with js and pass that to my controller with ajax.
Ajax:
var values = [{FirstName: "fff"},{LastName: null}]
$.ajax({
method: "POST",
url: "/api/store-step",
data: { values: values, step: activePanelNum }
}).fail(function (jqXHR, textStatus, error,result) {
console.log(jqXHR.responseJSON.errors);
}).done(function( result ) {
console.log(result);
});
structure of array is this:
[{FirstName: "fff"},{LastName: null}]
Controller:
public function storeSteps(Request $request)
{
$validator = Validator::make($request->values, [
'FirstName' => 'required',
'LastName' => 'required',
]);
if ($validator->fails()) {
return response()->json(['success'=>false, 'errors' => $validator->getMessageBag()->toArray()],422);
}
}
I can't validate this array with request validation Laravel. Now I'm going to turn this array into a Larval request to apply the rules to it.
Can any one helps?
you can validate array element like this
$validator = Validator::make($request->all(), [
'values' => 'required',
'values.*.FirstName' => 'required',
'values.*.lastName' => 'required','
]);
by using . you can access an index in a array and * apples all indexes in the array.
I have a form with a ChoiceType. Values are set with a Ajax request (this choice depends of an other choice).
But there is many choices (13200), And when I submit the the form whith a correct choice, I have this error "This value is not valid.".
I have tried whith 100 choices, and it's work well.
This form is build whith EventsListener (simplified version) :
$ff = $builder->getFormFactory();
// function to add 'template' choice field dynamically
$func = function ( \Symfony\Component\Form\FormEvent $e) use ($ff, $curlRequest, $builder, $rapport) {
$data = $e->getData();
$form = $e->getForm();
if ($form->has('idsSouscripteur') )
{
$form->remove('idsSouscripteur');
}
$idClient = $data->getIdClient() > 0 ? $data->getIdClient() : null;
$idsSouscripteur = count($data->getIdsSouscripteur()) > 0 ? $data->getIdsSouscripteur() : null;
$souscripteursArray = [];
if (!is_null($idClient)) {
$souscripteurs = /* Request to get 'souscripteurs' objects */;
foreach ($souscripteurs as $souscripteur) {
$souscripteursArray[$souscripteur->nomSouscripteur] = $souscripteur->numInterne;
}
}
$form
->add('idsSouscripteur', ChoiceType::class, [
'label' => 'rapports.block_2.souscripteur',
'mapped' => false,
'multiple' => true,
'choices' => $souscripteursArray,
'constraints' => array(
new NotBlank()
),
'attr' => [
'placeholder' => 'rapports.block_2.souscripteur_placeholder'
]
]);
if (!is_null($idsSouscripteur)) {
$rapport->setIdsSouscripteur($idsSouscripteur);
}
};
// Register the function above as EventListener on PreSet and PreBind
$builder->addEventListener(FormEvents::PRE_SET_DATA, $func);
$builder->addEventListener(FormEvents::PRE_SUBMIT, $func);
Anyone lnow why symfony is not working with big array ?
I have created a form in Codeigniter with a phone number field that dynamically is duplicated using javascript. So basically I can have one or more fields like this.
<input name="phone[]" value=""type="text">
<input name="phone[]" value=""type="text">
Then in my controller I have
$form_data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'phone' => $this->input->post('phone[]')
);
Then I am saving this to my dabase like so
function SaveForm($form_data)
{
$this->db->insert('customers', $form_data);
if ($this->db->affected_rows() == '1')
{
return TRUE;
}
return FALSE;
}
but obviously the code for 'phone' is wrong, I just cant figure out how to properly do this.
you can't save array in to database. You can convert it in to string using implode() and whenever you needed then convert it back in array using explode(). Like below
$phone=implode(',',$this->input->post('phone'));
$form_data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'phone' => $phone
);
OR
You can convert it to json string and when you needed convert back to Array Like below:
$phone = json_encode($this->input->post('phone'));
Convert back to array
$phone = json_decode($phone, TRUE);
Modify your function as below and it will works like charm,
function SaveForm($form_data)
{
foreach ($form_data as $contact)
{
$data[] = array(
'first_name' => $contact['first_name'],
'last_name' => $contact['last_name'],
'phone' => $contact['phone']
);
}
$this->db->insert_batch('customers', $data);
if ($this->db->affected_rows() > 0)
{
return TRUE;
}
return FALSE;
}
Modified:
Oh, yes you have to edit para array that you passed to SaveForm function.
Please use following code, ignore above code:
foreach($_POST['first_name'] as $key=>$fname)
{
$form_data[] = array(
'first_name' => $_POST['first_name'][$key],
'last_name' => $_POST['last_name'][$key],
'phone' => $_POST['phone'][$key],
);
}
function SaveForm($form_data)
{
$this->db->insert_batch('customers', $data);
if ($this->db->affected_rows() > 0)
{
return TRUE;
}
return FALSE;
}
In controller
$phone = $_POST['phone'];//this will store data as array. Check image 02
$form_data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'phone' => $phone,//some times it works with '$phone'
);
In Model
function SaveForm($form_data)
{
$this->db->insert('customers', $form_data);
if ($this->db->affected_rows() == '1')
{
return TRUE;
}
else
{
return FALSE;
}
}
Tested
Image 01 (My form)
Image 02 (After Submitted)
mysql doesn’t has any array data type. So we can not store array directly into mysql database.
To do this we have to first convert array into string using php serialize() function then save it into mysql database.
for eg:php code to store array in database
$array = array("foo", "bar", "hello", "world");
$conn=mysql_connect('localhost', 'mysql_user', 'mysql_password');
mysql_select_db("mysql_db",$conn);
$array_string=mysql_escape_string(serialize($array));
To retrieve array from database
$conn=mysql_connect('localhost', 'mysql_user', 'mysql_password');
mysql_select_db("mysql_db",$conn);
$q=mysql_query("select column from table",$conn);
while($rs=mysql_fetch_assoc($q))
{
$array= unserialize($rs['column']);
print_r($array);
}
for array insertion to database use this programme in codeigniter controller=>
$inputdata=$this->input->post();
$phone=array($inputdata['phone']);
foreach($phone as $arr)
{
$phoneNo=$arr;
$f=count($phoneNo);
for($i=0;$i<$f;$i++)
{
$arre=[
'phone'=>$phoneNo[$i],
];
$insertB= $this->user_model->userdata($arre);
}
}
public function add_theme_pages(){
$page_name = $this->input->post('page');
$page_img = $this->input->post('page_img');
for($i=0; $i < count($page_name); $i++){
$pages_data = array(
'theme_id' => $this->input->post('theme_id'),
'theme_page_name' => $page_name[$i],
'theme_page_img' => $page_img[$i]
);
if($this->backendM->add_theme_pages($pages_data)){
$this->session->set_flashdata('message', 'Theme Added Successfully !');
$this->session->set_flashdata('message_class', 'green');
$this->create_template();
}else{
$this->create_template();
}
}
}
Ok, what i have is a PHP array that looks like this:
Array
(
[0] => Array
(
[label] => 1
[value] => Value example
)
[1] => Array
(
[label] => 10
[value] => Value example 2
)
[...]
)
Now, if i json_encode() this array, what i get is:
[
Object { label="1", value="Value example" },
Object { label="10", value="Value example 2" },
...
]
But to use it in jQuery Autocomplete i need the array to be like this:
[
{ label="1", value="Value example" },
{ label="10", value="Value example 2" },
...
]
I've read tons of pages without finding a solution...can someone help?
UPDATE FOR PETER:
Here's my code:
$results = array();
foreach ($temp as $tmp) {
$results[] = array(
'label' => $tmp['id'],
'value' => $tmp['it']
);
};
echo json_encode($results);
If it may be useful, $temp array is generated from the following Wordpress function:
$wpdb->get_results($query, ARRAY_A);
UPDATE FOR PETER 2
SCRIPT:
jQuery(document).ready(function($){
var temp_array = function(request, response) {
$.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'POST',
dataType: 'json',
data: {
'action': 'autocomplete_finder',
'data' : request.term,
},
success: function(data) {
//response(data);
console.log(data);
}
});
};
$('#containing').autocomplete({
source: temp_array,
minLength: 3,
select: function(event, ui) {
console.log('test')
}
});
});
HTML:
<input id="containing" style="width: 98%">
I just realized what simple mistake you did
Switch label with value:
$results = array();
foreach ($temp as $tmp) {
$results[] = array(
'label' => $tmp['it'],
'value' => $tmp['id']
);
};
echo json_encode($results);
and it will works
your array should look like this:
Array
(
[0] => Array
(
[label] => Value example
[value] => 1
)
[1] => Array
(
[label] => Value example 2
[value] => 10
)
[...]
)
Im am trying to create a controller that uploads a file for me but I always get the same result. The file isn't valid so he doesn't upload.
The function in my controller is:
$upload = new \Zend\File\Transfer\Transfer();
$upload->setDestination('./data/images/uploads/');
$rtn = array('success' => null);
if ($this->getRequest()->isPost()) {
$files = $upload->getFileInfo();
foreach ($files as $file => $info) {
if (!$upload->isUploaded($file)) {
print "<h3>Not Uploaded</h3>";
\Zend\Debug\Debug::dump($file);
continue;
}
if (!$upload->isValid($file)) {
print "<h4>Not Valid</h4>";
\Zend\Debug\Debug::dump($file);
continue;
}
}
$rtn['success'] = $upload->receive();
}
return new \Zend\View\Model\JsonModel($rtn);
The result is:
<h4>Not Valid</h4><pre>string(8) "files_0_"
</pre>{"success":false}
When I look at $files (print_r()) I get:
Array
(
[files_0_] => Array
(
[name] => logo_welcome.gif
[type] => image/gif
[tmp_name] => /private/var/tmp/phpiufvIc
[error] => 0
[size] => 62935
[options] => Array
(
[ignoreNoFile] =>
[useByteString] => 1
[magicFile] =>
[detectInfos] => 1
)
[validated] =>
[received] =>
[filtered] =>
[validators] => Array
(
[0] => Zend\Validator\File\Upload
)
[destination] => ./data/images/uploads
)
)
As you can see in ZF2 docs, file uploading with Zend\File\Transfer has been deprecated in favor of using the standard ZF2 Zend\Form and Zend\InputFilter features.
Having said that, you should use Zend\Filter\File\RenameUpload to move the uploaded file. You just need to attach the Zend\Filter\File\RenameUpload filter to your InputFilter specification, like that:
$this->add([
'name' => 'file',
'type' => 'Zend\InputFilter\FileInput',
'filters' => [
[
'name' => 'FileRenameUpload',
'options' => [
'target' => realpath('./data/uploads/'),
'randomize' => true,
'use_upload_extension' => true,
],
],
],
]);
And in your controller action:
if ($this->request->isPost()) {
$post = array_merge_recursive(
$this->request->getPost()->toArray(),
$this->request->getFiles()->toArray()
);
$form->setData($post);
if ($form->isValid()) {
// File uploaded and moved to data/uploads folder
}
}
Take a look in official documentation for a complete example.