Laravel Livewire javascript code after model is load - laravel

I have one Laravel Livewire model open as bellow code
public function confirmItemAdd()
{
$this->resetValidation();
$this->confirmingItemAdd = true;
}
and my model window code in blade is
<x-jet-dialog-modal wire:model="confirmingItemAdd">
I have one select2 in model and want to set value of select2 on variable name $s2v
After search I findout that
$('.select2').val(s2v).trigger('change');
how can I set value of select2 on load on model?
Thanks

You can trigger a browser event from the livewire component and listen for that event and change the select2 value accordingly (assuming the select2 part is wire:ignored).
public $s2v = 'Test value';
public function confirmItemAdd()
{
$this->resetValidation();
$this->confirmingItemAdd = true;
$this->dispatchBrowserEvent('change-select2', $this->s2v);
}
in your layout file or with the stack in layout file you can listen for this event and trigger the change for the select2 as below,
<script>
$(window).on('change-select2', (e) => {
$('.select2').val(e.detail).trigger('change');
});
</script>
Note e.detail is the $s2v value passed from the livewire component.

And what validation error is giving to you? you are reseting the validation error before the dispatchBrowserEvent...seem that even by JS you are changing the select2 value the property doesn't
EDITED
Ok, first a have a particular issue with select2 rendering after each refresh and find this solution. In the component a have this:
public function hydrate()
{
$this->emit('select2');
}
and in blade parent or script section
<script>
$(document).ready(function() {
window.initSelectCompanyDrop=()=>{
$('#selectCompany').select2({
placeholder: '{{ __('locale.Select a Company') }}',
allowClear: true});
}
initSelectCompanyDrop();
$('#selectCompany').on('change', function (e) {
livewire.emit('selectedCompanyItem', e.target.value)
});
window.livewire.on('select2',()=>{
initSelectCompanyDrop();
});
});
</script>
If your issue with error bag persist, so you have to look into the kind of validation you're doing. In other case, I define global $message for a validation message but only works for $this->validate. Once I need redefine the validation, using Validator::make I have to create a new var $message for that inside the method

Related

laravel passing a variable to js file from a controller

I have a js file located in assets folder (not View). can i pass a varible from a controller?
In view file:
The Js is called like this
<canvas id="chart1" class="chart-canvas"></canvas>
</div>
It is not possible (in my point of view) to put a variable to external JS file. You can use data-... attributes and get values from html elements.
For example you can pass your PHP variable as a json encoded string variable in your controller.
$data['chart_info'] = json_encode($chart_info);
return view('your_view', $data);
Then put it in data-info like this.
<canvas id="chart1" class="chart-canvas" data-info="{{ $chart_info }}"></canvas>
And finally in JS, you can get the variable and decode (parse) it as following.
let canvas = document.getElementById('chart1');
let info = JSON.parse(canvas.dataset.id);
console.log(info);
You can put that part of the Javascript in the view and send the variable to the same view. For example, add a section in view:
#section('footer')
<script type="text/javascript">
</script>
#endsection
Do not forget that you should add #yield('footer') to the end of your layout view.
I don't like to mix javascript and PHP/Blade, it might be hard to read the code in the future... You could use a different approach, loading the chart with a async ajax request.
You will have to create a end-point that returns the data you need for your chart:
Your router:
Route::get('/chart/get-data', [ ControllerName::class, 'getChartData' ]);
Your controller method:
public function getChartData() {
$chartData = [];
// Your logic goes here
return $chardData;
}
In your javascript (using jquery) file there will be something like that:
function loadChartData() {
$.ajax({
'url': '/chart/get-data',
'method': 'GET'
})
.done((data) => {
// Load your chart here!!!
})
.fail(() => {
console.log("Could not load chart data");
});
}
Hope I helped ;)

Call view in Laravel Controller with anchor tag

I need to call a view in a Laravel Controller, with parameters and with Anchor Tag.
I have this code in my controller:
return view('plans/editPlanView',
['plan' => $plan,
'patient' => $patient,
'aliments'=>$aliments, 'menu'=>$menu, 'tabName'=>$tabName]);
But i need to add an Anchor tag to land in a specific section of the page.
I can't use
return Redirect::to(URL::previous() . "#whatever");
proposed in other posts because i need to pass some parameters.
I think there are some base problem, trying with console this:
$('html, body').animate({
scrollTop: $('#whatever').offset().top
}, 1000);
scrolling to the desired section does not work.
it seems the page makes a small snap but always returns to the top.
Update
I have found the cause of the problem. At the bottom of the blade page I have the following code, without it the anchor tag works fine. Adding it the page makes a small scroll to return to the head. I need to use the datepicker, how can I fix the problem and get the anchor tag to work?
#push('scripts')
<script type="text/javascript">
$(document).ready(function () {
$('.date').datepicker({
firstDayOfWeek: 1,
weekDayFormat: 'narrow',
inputFormat: 'd/M/y',
outputFormat: 'd/M/y',
markup: 'bootstrap4',
theme: 'bootstrap',
modal: false
});
});
</script>
#endpush
You can create the method showPage() in your contoller for example TestController
public function showPage(Request $request)
{
$plan = $request->plan;
...
return view('plans/editPlanView', [
'plan' => $plan,
'patient' => $patient,
'aliments'=>$aliments, 'menu'=>$menu, 'tabName'=>$tabName
]);
}
Then create a route for rendering that view
Route::get('/someurl', 'TestController#showPage')->name('show-page');
And then in your methods you can use something like that:
$url = URL::route('show-page', ['#whatever']);
return Redirect::to($url)
I found a workaround, I added the disable attribute to the date input, in doing so, when the datepicker is initialized, the page does not scroll up. Then, as a last javascript statement I re-enabled the fields:
$('.date').prop("disabled", false);

Multiple CheckBox Validation using spring JS?

I am creating dynamic Check Boxes in runtime. my requirement is have to validate atleast one checkbox checked or not. am doing this using springJS. But to validate i have to pass checkBox Id to spring Validation, But this ID array creating in runtime. how can i achieve this? i tried all solutions but it did'nt worked for me. i am doing like this it was working if i hardcode checkbox id.
<script type="text/javascript">
Spring.addDecoration(
new Spring.ElementDecoration({
elementId: '_CheckBox_ids',
widgetType: 'dijit.form.CheckBox',
widgetModule: 'dijit.form.CheckBox',
validate: function () {
if (dojo.query("#roo_apiUser_profile > input[type=checkbox]", 'dijit.form').filter(function (n) {
return n.checked;
}).length > 0) {
return true;
} else {
alert('choose at least one profile');
return false;
}
},
widgetAttrs: {
required: true
}
}));
</script>
You may add the onsubmit attribute in your form tag and call a function that does the validation on checkboxes.
Alternately, you may create your own extension of AbstractElementDecoration (defined in spring.js) using dojo.declare and pass to the validate attribute a function that will do the checkboxes validation for you. For elementId you may pass in the id of a div element that contains all the checkboxes. Spring.ValidateAllDecoration calls Spring.validateAll function. Make sure you do the necessary tweaking in your AbstractElementDecoration extension so that there is no exceptions in Spring.validateAll.

Ember event in one view update another?

I have a small extract from my Ember app here. My page contains a number of views each containing different data each with their own controllers.
I want a search field (in index view) to go in one view which should "talk" to the stationList controller to update the content of the stationList view. This doesn't work. I get an error: TypeError: this.get(...).search is not a function
The logging outputs the name of the contoller I've asked it to use: App.StationListController
I added a second search form inside on the StationList View. This one works just fine. The logging this time outputs a dump of the StationListController object. So I am guessing that the other search form, despite my code (in SearchFormView): controllerBinding : 'App.StationListController', is not correctly setting the controller.
So I guess my question is why not?
How can I route the change on the form field in the one view to call a funciton on another view's controller?
Here's my code:
<script type="text/x-handlebars" data-template-name="application">
{{outlet}}
</script>
<script type="text/x-handlebars" data-template-name="index">
<div id="searchForm">search form view search:
{{#view App.SearchFormView}}
{{view App.StationSearchField}}
{{/view}}
</div>
<div id="stationList">{{render stationList}}</div>
</script>
<script type="text/x-handlebars" data-template-name="stationList">
station list view search: {{view App.StationSearchField}}
<ul>
<li>List</li>
<li>will</li>
<li>go</li>
<li>here</li>
</ul>
{{searchTerm}}
</script>
And
App = Ember.Application.create({})
App.SearchFormView = Ember.View.extend({
init : function()
{
console.log("SearchFormView init", this.get('controller'))
}
})
App.StationSearchField = Ember.TextField.extend({
keyUp: function(event) {
var searchTerm = this.value
console.log("value",searchTerm,this.get('controller'))
this.get('controller').search(searchTerm)
}
})
App.StationListController = Ember.ArrayController.extend({
content : [],
searchTerm : null,
search : function(term)
{
this.set("searchTerm",term)
console.log("searching",term)
}
});
Fiddle: http://jsfiddle.net/ianbale/8QbrK/14/
I think the controllerBinding stuff is from the older version, I don't think that works anymore.
You can use controllerFor on get('controller') in the StationSearchField.
this.get('controller').controllerFor('station_list').search(searchTerm)
But controllerFor is deprecated and may be removed. Depending on your application structure you use needs on the controller.
Another way which I am using, is to send a custom event from the View, which the Route then sends to the corresponding controller.
App.IndexRoute = Ember.Route.extend({
events: {
search: function(term) {
controller = this.controllerFor('station_list')
controller.search(term);
}
}
});
and dispatch a search event from view like so.
this.get('controller').send('search', searchTerm);
The advantage of this method is you dispatch the same event from multiple places and it would get handled in the same way.
Here's the updated jsfiddle.

Joomla - OnMouseover show data from controller in tooltip using Qtip script

I need help to show the data (from controller) in tooltip (using qTip script) on MouseOVer event.
User mouserover on link (Multiple links like in foreach)
id send to a js function like function getData(id){}
Call the PHP function from the controller & using the variable return the data to tooltip.
Show return data into tooltip.
HTML & PHP:
foreach ($rows as $row) {
<a href="#" onmouseover="getData(<?php echo $row->id; ?>)" >Name</a>
}
JS function :
function getData(id)
{
var url='index.php?option=com_test&controller=test&task=getDetails&format=raw';
var data = 'item_id=' + id ;
var request = new Request({
url: url,
method:'post',
data: data,
async: true,
onSuccess: function(responseText)
{
// How i show the "responseText" data here in tooltip using qTip
}
}).send();
}
Controller function:
function getDetails()
{
echo $return = JRequest::getVar('item_id');
}
Would it not be easier to preload the tip in a content item view override (add it to the title= attribute), and adding the call to qTip (one per page) would do the trick.
Also, ajax would make the tooltip not very quick.
Just make sure you properly escape " or ' characters in the title attribute or you will break your markup.
edit: added code. i'm writing this here so there may be typos, but it should give you the idea:
foreach ($rows as $row) {
// let's assume $tip contains the right tip for each row:
Name
}
This first part will show the default browser tooltip.
Now you have to inject the qTip script:
$document = JFactory::getDocument();
$document->addScriptDeclaration('
jQuery("a.tipme").qTip();
');
Now how to put the value in $tip? I see you have a com_test component, you don't need to go through the controller, but can instantiate directly the model that will provide the tooltip; if it's called "tip":
$tipmodel=JModel::getInstance('tip', 'ComtestModel'); // get the model (once!)
$tip = $tipmodel->getTip($row->id);
All the variable, model, controller names in this story are fictional.

Resources