Get repeatable json data in Request select_from_ajax - laravel-backpack

I have a repeatable field --and others-- with an ajax select inside. It has an endpoint route. In the controller of the route i do this
$inputs = $request->input('form');
dd($inputs);
It show all form fields that were completed except the repeatable field. Like this
6 => array:2 [
"name" => "payment_method"
"value" => 1
]
7 => array:2 [
"name" => "date"
"value" => "2020-12-17"
]
8 => array:2 [
"name" => "expiration"
"value" => "2020-12-31"
]
9 => array:2 [
"name" => "invoice_lines_data" <------- repeatable field
"value" => null <---- HERE THE JSON DATA
]
I want the actual json value of the repeatable field. Any help? Thanks

Update $(element).select2 function of select2_from_ajax.blade.php with the following code.
var formSerializeArray = form.serializeArray();
let rowNumber = element.attr('data-row-number');
let selector = element.attr('data-custom-selector');
// if any dependencies have been declared inside repeatable field
// then send those dependencies value with ajax fetch request
for (var i=0; i < $dependencies.length; i++) {
var $dependency = $dependencies[i];
//if element does not have a custom-selector attribute we use the name attribute
if(typeof element.attr('data-custom-selector') != 'undefined') {
// we get the row number and custom selector from where element is called
let rowNumber = element.attr('data-row-number');
let selector = element.attr('data-custom-selector');
// replace in the custom selector string the corresponding row and dependency name to match
selector = selector
.replaceAll('%DEPENDENCY%', $dependency)
.replaceAll('%ROW%', rowNumber);
console.log(selector)
dependency_val = $(selector).val();
if(dependency_val){
formSerializeArray.push({name: $dependency, value: dependency_val});
}
}
}
return {
q: params.term, // search term
page: params.page, // pagination
form: formSerializeArray
//form: form.serializeArray() // all other form inputs
};

Related

Doctrine Entity values are all null except for id

I'm trying to fetch an Object from the database with the repository method findOneBy (id).
Basically, the line looks like this:
public function findAssignedTickets(User $user)
{
$userId = $user->getId();
$ticketMapping = new ResultSetMapping;
$ticketMapping->addEntityResult(Ticket::class, 't');
$ticketMapping->addFieldResult('t', 'id', 'id');
// Postgresql Native query, select all tickets where participants array includes the userId
$query = "SELECT *
FROM (
SELECT id, array_agg(e::text::int) arr
FROM ticket, json_array_elements(participants) e
GROUP BY 1
) s
WHERE
$userId = ANY(arr);
";
$results = $this->getEntityManager()->createNativeQuery($query, $ticketMapping)->getResult();
$results = array_map(function($item) {
return $item->getId();
}, $results); // Transform to array in integers
dump($results); // array:2 [0 => 83, 1 => 84] -> It's correct
$tickets = [];
foreach ($results as $ticketId) {
dump($this->findOneById($ticketId));
// $ticket = $this->findOneById($ticketId);
// $tickets[] = [
// 'identifier' => $ticket->getIdentifier(),
// 'title' => $ticket->getTitle(),
// 'author' => $ticket->getAuthor()->getUsername(),
// 'status' => $ticket->getStatus(),
// 'created' => $ticket->getCreatedAt()->format('c'),
// 'updated' => $ticket->getUpdatedAt()->format('c'),
// ]; // Ticket formatting to send in json
}
return $tickets;
}
which will output :
And I'm sure that the received id matches a row in the database, and that the database contains data, and all fields belong directly to the entity, except for author which represents a ManyToOne and I heard about the lazy displaying of Doctrine, but it shouldn't happen on other fields.
Why can't I retrieve data from the Object even with getters, and why are all the values set to null Except for id ?
EDIT : I was wondering if that had a connexion to the ResultSetMapping I used to fetch the tickets IDs in a totally separate request earlier, and when I added a addFieldResult('t', 'title', 'title'); it did the work, but not on the other fields, another mystery.

MongoDB Raw query to select documents which are in given datetime period

I want to select documents which are in user given date time period like between :
$from_date : "2017-01-07 09:08:59" To `$to_date : "2017-08-09 09:08:59"`
I'm using laravel framework and jenssegers/laravel-mongodb mongodb driver to run my query, And this is my Raw query :
$normal_banners = BannerView::raw(function ($collection) use ($id, $from_date, $to_date) {
$conditions = [
["camp_id" => ['$eq' => $id]],
['$or' => [
['seat_target_status' => ['$eq' => true]],
['seat_target_status' => ['$eq' => false]]
]],
['camp_target_status' => ['$eq' => false]],
];
if ($from_date) {
$conditions[] = ['created_at' => ['$gte' => $from_date]];
}
return $collection->aggregate([
['$match' => ['$and' => $conditions]],
]);
})->count();
But my problem is that it returns 0 as result; while there are 16 documents in this time period.
I've tried this method to get the count of them but still 0 result :
$normal_banners = BannerView::Where('camp_id', $id)
->where(function ($query) {$query->where('seat_target_status', true)->orWhere('seat_target_status', false);
})
->where('camp_target_status', false)
->where("created_at", ">=", $from_date)
->count();
FYI : I've converted datetime of input to ISODate Which is the mongodb datatype for created_at field.
$Fromdatetime = $request->input('from_date');
$from_date = new DateTime($Fromdatetime);
$from_date = $from_date->format(DateTime::ISO8601);
mongodb field data type is :
"updated_at": ISODate("2017-04-10T09:35:58.641Z"),
"created_at": ISODate("2017-04-10T09:35:58.641Z")
My input data type is : "2017-01-07T09:08:59+0000"
Any suggestion ?
You have to "put in braces" orWhere function and in your raw query you are testing $to_date with updated_at column, but in Eloquent code you are making between with created_at column
$targeted_banners = BannerView::Where('camp_id', $id)
->where(function($query){$query->where('seat_target_status', true)->orWhere('seat_target_status', false);})
->where('camp_target_status', false)
->where("created_at", ">=" $from_date)
->where("updated_at", "<=", $to_date)
->count();
I've solved this problem using Carbon::createDateFrom method, it create a UTC date time base on my input :
Inputs :
{
"from_date": "2017-03-10",
"to_date": "2017-04-09"
}
Converting input dates :
$from_date_arr = explode("-",$request->input('from_date'));
$from_date = Carbon::createFromDate($from_date_arr[0],$from_date_arr[1],$from_date_arr[2]);
$to_date_arr = explode("-",$request->input('to_date'));
$to_date = Carbon::createFromDate($to_date_arr[0],$to_date_arr[1],$to_date_arr[2]);
And This is the query I run which worked :
$normal_banners = BannerView::Where('camp_id', $id)
->where(function ($query) {$query->where('seat_target_status', true)->orWhere('seat_target_status', false);
})
->where('camp_target_status', false)
->where("created_at", ">=",$from_date)
->where("created_at", "<=",$to_date)
->count();
There is a strange problem still with jessenger driver which whereBetween is not working and we should use two where clause to make it work.
Hope solves others problem.

HTML-Template - Array of Hash

I have two Array of Hashes: The first contains values for a current time interval and the second contains values for a previous time interval.
#AoHcurrent=
( { node => "ABC",
link => "DEF",
time => "10:00",
value => "100",
},
{
node => "FGH",
link => "IJK",
time => "10:00",
value => "200",
},
);
#AoHprevious=
( { node => "ABC",
link => "DEF",
time => "09:45",
value => "10",
},
{ node => "FGH",
link => "IJK",
time => "09:45",
value => "50",
},
);
I want to now use HTML-Template to present this data. Something like :
NODE LINK VALUE
---------------------
ABC DEF 100(10)
FGH IJK 200 (50)
the values in brackets represent the previous value.
my %html_template_parameters =
( AOHCURRENT => \#AoHcurrent,
AOHPREVIOUS => \#AoHprevious, );
my $html_template=qq{Report.tmpl};
my $html_output=qq{Report.html};
htmlReport($html_template,$html_output,\%html_template_parameters);
where htmlReport is a function that generates the report
I require guidance on defining the Report.tmpl file.
Thanks you in advance
see also http://www.perlmonks.org/?node_id=972954
I gave an example there how this can be solved with HTML::Template::Compiled.
Basically you would navigate through the parameter stash like this:
[%= expr=".AOHPREVIOUS[__index__]{'value'}" %]
or with the classic syntax:
<TMPL_VAR expr=".AOHPREVIOUS[__index__]{'value'}" >
You can't do that with 2 separate lists just with HTML::Template. And trying to do it with HTML::Template::Expr would be a nightmare to maintain. Try collapsing them into a single list where the hash data is merged.

How to do a select with Zend Framework from a form?

im trying make a form with zend, and i do know how to do a select from a form
public function init()
{
$this->addElement("text","titulo",array(
"label" => "Titulo"
));
$this->setAttrib("id", "enviarNoticia");
$this->setAttrib("class", "FormEnviarNoticia");
$this->setMethod("post");
$this->addElement("textarea","noticia",array());
$this->addElement("submit","Enviar",array());
$this->addElement("multiselect", "categories",array(
"label" => "Categories",
"required" => false,
));
}
How to add options and item selected?
Instead of trying to get the data from the form itself, you should get the data from the model/database in your controller and assign the values to the form from the controller.
// In a controller
// get the options from your model or database into an array
$options = array('name' => 'value', 'name2' => 'value2', 'name3' => 'value3');
$form = new Application_Form_Form();
$form->getElement('categories')->setMultiOptions($options); // set the $options as the options for the categories multiselect
if ($this->getRequest()->isPost()) {
if ($this->form->isValid($this->getRequest()->getPost())) {
// form passed validation
}
} else { // form was not submitted
// to set default value(s) for the select
$form->getElement('categories')->setValue(array('name2', 'name3'));
}

Why am I getting a "Odd number of elements in anonymous hash" warning in Perl?

Help, I'm trying to create a new post in my wordpress blog with custom fields using the following perl script using metaweblogAPI over XMLRPC, but there seems to be an issue with the custom fields. Only the second custom field (width) ever seems to get posted. Can't get the "height" to publish properly. When I add another field, I get the "Odd number of elements in anonymous hash" error. This has got to be something simple - would someone kindly sanity check my syntax? Thanks.
#!/usr/bin/perl -w
use strict;
use RPC::XML::Client;
use Data::Dumper;
my $cli=RPC::XML::Client->new('http://www.sitename.com/wp/xmlrpc.php');
my $appkey="perl"; # doesn't matter
my $blogid=1; # doesn't matter (except blogfarm)
my $username="Jim";
my $passwd='_____';
my $text=<<'END';
This is the post content...
You can also include html tags...
See you!
END
my $publish=0; # set to 1 to publish, 0 to put post in drafts
my $resp=$cli->send_request('metaWeblog.newPost',
$blogid,
$username,
$passwd,
{
'title' => "this is doodoo",
'description' => $text,
'custom_fields' => {
{ "key" => "height", "value" => 500 },
{ "key" => "width", "value" => 750 }
},
},
$publish);
exit 0;
While techically valid syntax, it's not doing what you think.
'custom_fields' => {
{ "key" => "height", "value" => 500 },
{ "key" => "width", "value" => 750 }
},
is roughly equivalent to something like:
'custom_fields' => {
'HASH(0x881a168)' => { "key" => "width", "value" => 750 }
},
which is certainly not what you want. (The 0x881a168 part will vary; it's actually the address where the hashref is stored.)
I'm not sure what the correct syntax for custom fields is. You can try
'custom_fields' => [
{ "key" => "height", "value" => 500 },
{ "key" => "width", "value" => 750 }
],
which will set custom_fields to an array of hashes. But that may not be right. It depends on what send_request expects.