Using livewire defer, if input value has text the value is sent when pagination link is clicked- how to stop this? - laravel-7

I'm using livewire with pagination. I set the input to defer so that the search is not carried out until the search button is clicked. However, I have also noticed that if I have any text in the search box that value is sent whenever a pagination button is clicked. I've tried setting the value to "" in jquery $(document).on("click", ".page-link", () => $( "#inlineFormInput" ).val("")); when a pagination buttton is click but that has not solved the problem. And actually clearing the value could cause other problems.
The desired result is that, if for some reason a user leaves text in the searchbox that value is not passed if the user changes their mind and just clicks a pagination link. The input value should only be passed when the search button is clicked. Any help would be greatly appreciated.
livewire component html:
<div id="searchBoxRow">
<input wire:model.defer="search" wire:keydown.enter="updateFaculty" id="inlineFormInput" class="form-control" val="" type="search" autocomplete="off" placeholder="Seach for Name or Country" aria-label="Search">
<button wire:click="updateFaculty" class="btn btn-primary" id="facultyCardsSearchButton" type="submit">
<i class="bi bi-search button-icon"></i>
<span class="button-text">Search</span>
</button>
</div>
livewire php file:
<?php
namespace App\Http\Livewire;
use App\Models\Tag;
use App\Models\Faculty;
use Livewire\Component;
use Livewire\WithPagination;
class FacultyData extends Component
{
use WithPagination;
protected $paginationTheme = 'bootstrap';
public $search = null;
public $tagId = null;
public function updateFaculty(){
$search = $this->search;
$tagId = $this->tagId;
$this->emit('closeAutocomplete');
}
public function updatingSearch()
{
$this->resetPage();
}
public function render()
{
$tags = Tag::all();
$allFaculty = Faculty::searchFilter([$this->search, $this->tagId])->with('country', 'tags')->paginate(10);
return view('livewire.faculty-data', [
'allFaculty' => $allFaculty,
'tags' => $tags
]);
}
}

Here is an idea. You can use the updatingPage() of the $page property hook. When performing the page switch clean the search property. But, somehow you need to check if this is a result of a searched data before or just the client has had his way...well, my idea is get a flagged property to tell livewire what to do. For example
public $searchFlag = false;
public function updateFaculty(){
if ($this->search) // only of search has any value
$this->searchFlag = true;
// do
}
public function updatingPage()
{
if (! $this->searchFlag) {
$this->reset(['search']);
}
if (! $this->search) {
$this->reset(['searchFlag']);
}
}

Related

Laravel Livewire wire:click() deleting component property?

Hi fellow stackoverflowers,
I am running repeatedly into following issue while digging myself into Laravel8 Livewire capabilities. In my Livewire component called Ticker I am reading a series of dates data from a calendar table into a component property $days.
In my view I am displaying a div element for each element of $days with a wire:click, which should wire to the component's tick() method.
The view renders and mounts fine, but each time an element is clicked, a "Trying to get property 'id' of non-object $day->id" error appears - as if the $days property had been deleted or emptied by the method call. Can anyone help me in understanding this behaviour?
Component Ticker.php:
class Counter extends Component
{
public $days;
public function mount()
{
$this->days = \DB::table("caldays")->WhereBetween("id", [320, 326])->get();
}
public function render()
{
return view('livewire.ticker');
}
public function tick($id)
{
/* do stuff with selected $id */
}
}
View ticker.blade.php:
...
#foreach($days as $day)
<div class="border border-light-blue-500 border-opacity-75 p-6 text-center"
wire:click="tick({{ $day->id }})"
>
#endforeach
...
Many thx in advance & happy year & stay healthy!
You have to notice that. After delete your respective day this will not update your collection anyway. So after deletion you have to re query the days.Or Simply remove the respective day from your collection.
Try This:
#forelse($days as $day)
<div class="border border-light-blue-500 border-opacity-75 p-6 text-center"
wire:click="tick({{ $day->id }})"
>
#empty
<p>No day found</p>
#endforelse
Another solution is:
#if(count($days>0)
#foreach($days as $day)
<div class="border border-light-blue-500 border-opacity-75 p-6 text-center"
wire:click="tick({{ $day->id }})"
>
#endforeach
#endif
In php file:
public function tick($dayId){
$day = \DB::table("caldays")->Where("id", $dayId)->get();
$day->delete();
if(in_array($dayId,$this->days)) {
$key = array_search($dayId, $this->days);
array_splice($this->days, $key, 1);
}
}

Update #Html.Partial() View only

I am not looking for a javascript/jquery answer. I can do that, but I feel like it breaks the purpose. This seems like something that should be possible without javascript.
I'm trying to get a simple listbox selection to update an #Html.Partial section, and I'm not exactly sure what to do. Everything loads initially just fine. After I submit, however, I am not quite sure how to 'attach' to my partial view to update it.
The purpose here is to only load the listbox one time, and let them view or request as many new reports as they want without reloading. If it's not possible, that's fine, I can use one page, reload the listboxes, and it will work. I just don't see why I would need to go to the database to reload the listbox items every time they view or request a report.
"master" html page:
#using TCTReports.Models
#model ReportViewModel
<h2>My Reports</h2>
<div class="row">
<div class="col-md-6">
<h3>Select Report</h3>
#using (Html.BeginForm("GetReport", "Report"))
{
#Html.DropDownListFor(m => m.SelectedMyID, Model.myLB)
<input type="submit" value="View" />
}
</div>
<div class="col-md-6">
<h3>All Reports</h3>
#using (Html.BeginForm("ReqReport", "Report"))
{
#Html.DropDownListFor(m => m.SelectedAllID, Model.allLB)
<input type="submit" value="View" />
}
</div>
</div>
#Html.Partial("_Msg")
_Msg is super simple atm. It would eventually be a report viewer, for now, it looks at #Viewbag...
<h2>#ViewBag.Message</h2>
Controller submit actions (I get my selected value just fine. currently on void but was ActionResult with Views - but I don't feel like that is correct either, as it completely overwrites the page (even with PartialView) and I lose my listboxes and _layout...):
public void GetReport(ReportViewModel model)
{
var myID = model.SelectedMyID;
ViewBag.Message = "Report: " + myID.ToString() + " Selected.";
//return PartialView("_Msg","Test");
}
public void ReqReport(ReportViewModel model)
{
var allID = model.SelectedAllID;
ViewBag.Message = "Report: " + allID.ToString() + " Requested.";
//return PartialView("_Msg", "Test");
}
Ok, so how would I go about updating _Msg and refreshing only the #Html.PartialView() section of my master html page? I played with #sections briefly but didn't make much progress.

Is it possible to add a message in the listing of items in Prestashop?

I've built my module and made an AdminController that list items from my table, with creation/update/delete/view.
In the listing page, I'd like to add a message after the breadcrumb, but before the table.
I saw there is a hook available : "displayAdminListBefore" and a block to extend "override_header", but I don't know how to make it work!
Can someone could point me in the right direction please?
You can simply add your module to the displayAdminListBefore hook.
First hook the module to this hook with the install function:
public function install()
{
if (!parent::install() || !$this->registerHook('displayAdminListBefore'))
return false;
return true;
}
Then create the hook function like that:
public function hookDisplayAdminListBefore($params)
{
return '
<div class="bootstrap">
<div class="alert alert-success">
<button data-dismiss="alert" class="close" type="button">×</button>
Add your text here
</div>
</div>
';
}
Or, you can also use a .tpl:
public function hookDisplayAdminListBefore($params)
{
$this->smarty->assign(array(
'first_var' => $first_var,
'second_var' => $second_var',
));
return $this->display(__FILE__, 'views/templates/admin/listbefore.tpl');
}
The best way for you will be to override list_header.tpl and use the override_header hook.
To do so, create a new file list_header.tpl in modules/your_module/views/templates/admin/your_module/helpers/list/list_header.tpl
In this file copy the following code:
{extends file="helpers/list/list_header.tpl"}
{block name="override_header"}
Your text
{$your_var}
{/block}
$your_var must be defined in your controller in the function renderList():
$this->context->smarty->assign(
array(
'your_var' => 'your_var_value'
)
);

Orchard cms Extending Menu Item part

What's the best way to extent the Menu part in orchard ?
I want to use the normal menu part for most content types.
But I also want a Custom MainNavigationMenuPart. that has all the things the menu part has but adds a media picker field and a text field to it. - These items that will display on menu rollover.
Option 1
I think this is the best way to go ...
I've looked at writing a custom Menu part - but it seem like a lot of functionality for how the menu part currently work is there, I'm not sure how best to tap into this in a DRY way.
I can add a MenuPartItem to my customPart, so main menu part model would look like this
public class MainMenuPart : ContentPart<MainMenuRecord>
{
public MenuPart MenuPart { get; set; }
public string ShortDescription
{
get { return Record.ShortDescription; }
set { Record.ShortDescription = value; }
}
}
But ...
how do I render this on in the editor view for the part ?
I want to use the exiting MenuPartItemEditor.
how do I save this information in the record for the part?
Option 2
I've looked also at adding fields to the menu part (via cms).
My menu part now looks like this on the back end
Here I have customise the admin view for the menu depending on the content type.
Buy creating a Parts.Navigation.Menu.Edit.cshtml in Views/EditorTemplates, in my custom them I have access to the menu part, but I can seem to control the display of the fileds I have added to the part. (menu image, highlight, and short description)
Here is the custom Parts.Navigation.Menu.Edit.cshtml (original found in Orchard.Core/Navigation/Views/EditorTemplates/Parts.Navigation.Menu.Edit.cshtml)
#model Orchard.Core.Navigation.ViewModels.MenuPartViewModel
#using Orchard.ContentManagement
#using Orchard.Core.Navigation.Models;
#if (!Model.ContentItem.TypeDefinition.Settings.ContainsKey("Stereotype") || Model.ContentItem.TypeDefinition.Settings["Stereotype"] != "MenuItem")
{
if (Model.ContentItem.ContentType == "StandardIndexPage" ||
Model.ContentItem.ContentType == "AlternateIndexPage" ||
Model.ContentItem.ContentType == "MapIndexPage")
{
var sd = ((dynamic)Model.ContentItem).MenuPart.ShortDescription;
#sd
<fieldset>
#Html.HiddenFor(m => m.OnMenu, true)
#Html.HiddenFor(m => m.CurrentMenuId, Model.CurrentMenuId)
<div>
<label for="MenuText">#T("Menu text (will appear on main menu)")</label>
#Html.TextBoxFor(m => m.MenuText, new { #class = "text-box single-line" })
<span class="hint">#T("The text that should appear in the menu.")</span>
</div>
</fieldset>
}
else
{
<fieldset>
#Html.EditorFor(m => m.OnMenu)
<label for="#Html.FieldIdFor(m => m.OnMenu)" class="forcheckbox">#T("Show on menu")</label>
<div data-controllerid="#Html.FieldIdFor(m => m.OnMenu)" class="">
<select id="#Html.FieldIdFor(m => m.CurrentMenuId)" name="#Html.FieldNameFor(m => m.CurrentMenuId)">
#foreach (ContentItem menu in Model.Menus)
{
#Html.SelectOption(Model.CurrentMenuId, menu.Id, Html.ItemDisplayText(menu).ToString())
}
</select>
<span class="hint">#T("Select which menu you want the content item to be displayed on.")</span>
<label for="MenuText">#T("Menu text")</label>
#Html.TextBoxFor(m => m.MenuText, new { #class = "text-box single-line" })
<span class="hint">#T("The text that should appear in the menu.")</span>
</div>
</fieldset>
}
}
else
{
<fieldset>
<label for="MenuText">#T("Menu text")</label>
#Html.TextBoxFor(m => m.MenuText, new { #class = "textMedium", autofocus = "autofocus" })
<span class="hint">#T("The text that should appear in the menu.")</span>
#Html.HiddenFor(m => m.OnMenu, true)
#Html.HiddenFor(m => m.CurrentMenuId, Request["menuId"])
</fieldset>
}
I've also tried to control the display of fields using the placement.info in the theme
<Match ContentType="StandardIndexPage">
<Place Fields_Boolean_Edit-Highlight="-"/>
</Match>
with no success.

Drupal - Search box not working - custom theme template

I am using a customised version of search-theme-form.tpl
When I use the search box, I do get transferred to the search page. But the search does not actually take place. The search box on the search results page does work though. This is my search-them-form.tpl.php file (demo :
<input type="text" name="search_theme_form_keys" id="edit-search-theme-form-keys" value="Search" title="Enter the terms you wish to search for" class="logininput" height="24px" onblur="restoreSearch(this)" onfocus="clearInput(this)" />
<input type="submit" name="op" id="edit-submit" value="" class="form-submit" style="display: none;" />
<input type="hidden" name="form_token" id="edit-search-theme-form-form-token" value="<?php print drupal_get_token('search_theme_form'); ?>" />
<input type="hidden" name="form_id" id="edit-search-theme-form" value="search_theme_form" />
There is also a javascript file involved. I guess it's use is pretty clear from the code:
function trim(str) {
return str.replace(/^\s+|\s+$/g, '');
}
function clearInput(e) {
e.value=""; // clear default text when clicked
e.className="longininput_onfocus"; //change class
}
function restoreSearch(e) {
if (trim(e.value) == '') {
{
e.value="Search"; // reset default text onBlur
e.className="logininput"; //reset class
}
}
}
What can be the problem and how can I fix it?
Apparently, you cannot directly modify the HTML in search-theme-form.tpl.php since thats not the right way to do it. So my adding the class and onFocus and onBlur attributes was the problem.
The correct way to do it is to modify the themes template.php file. Basically we will be using form_alter() to modify the form elements. Since using the HTML way is wrong. Take a look at the code below (taken from : here )
<?php
/**
* Override or insert PHPTemplate variables into the search_theme_form template.
*
* #param $vars
* A sequential array of variables to pass to the theme template.
* #param $hook
* The name of the theme function being called (not used in this case.)
*/
function yourthemename_preprocess_search_theme_form(&$vars, $hook) {
// Note that in order to theme a search block you should rename this function
// to yourthemename_preprocess_search_block_form and use
// 'search_block_form' instead of 'search_theme_form' in the customizations
// bellow.
// Modify elements of the search form
$vars['form']['search_theme_form']['#title'] = t('');
// Set a default value for the search box
$vars['form']['search_theme_form']['#value'] = t('Search this Site');
// Add a custom class and placeholder text to the search box
$vars['form']['search_theme_form']['#attributes'] = array('class' => 'NormalTextBox txtSearch',
'onfocus' => "if (this.value == 'Search this Site') {this.value = '';}",
'onblur' => "if (this.value == '') {this.value = 'Search this Site';}");
// Change the text on the submit button
//$vars['form']['submit']['#value'] = t('Go');
// Rebuild the rendered version (search form only, rest remains unchanged)
unset($vars['form']['search_theme_form']['#printed']);
$vars['search']['search_theme_form'] = drupal_render($vars['form']['search_theme_form']);
$vars['form']['submit']['#type'] = 'image_button';
$vars['form']['submit']['#src'] = path_to_theme() . '/images/search.jpg';
// Rebuild the rendered version (submit button, rest remains unchanged)
unset($vars['form']['submit']['#printed']);
$vars['search']['submit'] = drupal_render($vars['form']['submit']);
// Collect all form elements to make it easier to print the whole form.
$vars['search_form'] = implode($vars['search']);
}
?>
In yourthemename_preprocess_search_theme_form - 'yourthemename' will obviously reflect the name of your custom theme. Basically the code is self-explanatory. what with the comments and all.
So, basically thats the way it works.

Resources