Livewire auto change content html to text wire:id - laravel-livewire

Component A (Search)
component class:
namespace App\Http\Livewire\Admin\Shared;
use Livewire\Component;
class Search extends Component
{
public $searchString = '';
public function updated()
{
$this->emitUp('searchForm', $this->searchString);
}
public function searchData()
{
$this->emitUp('searchForm', $this->searchString);
}
public function render()
{
return view('livewire.admin.shared.search');
}
}
component view:
<form wire:submit.prevent='searchData' class="d-none d-sm-inline-block">
<div class="input-group">
<input wire:model.lazy='searchString' id="textSearch" name="textSearch" type="text"
class="form-control bg-white border border-primary small" placeholder="Tìm kiếm...">
<div class="input-group-append">
<button class="btn btn-primary" type="submit">
<i class="fas fa-search fa-sm"></i>
</button>
</div>
</div>
</form>
Component B (List)
component class:
public $searchString = '';
protected $listeners = ['searchForm'];
public function searchForm($searchStringEmit)
{
$this->searchString = $searchStringEmit;
}
public function getListSupplier()
{
$data = Supplier::where('active', true)
->where('name', 'like', '%' . $this->searchString . '%')
->orderByDesc('id')
->paginate(2);
return $data;
}
public function render()
{
return view('livewire.admin.supplier.list', [
'ListSupplier' => $this->getListSupplier()
]);
}
I have problem with blade front-end. After I click button-search, component-search auto change component view show text wire:id<####>, instead of component-search view.
Example image:
enter image description here

It should have been <div wire:id="xxx"> that's how Livewire marks it's components. Make sure you don't have javascript doing some DOM manipulation. Check your template for more information

Related

Undefined array key "video"

create component
<?php
namespace App\Http\Livewire\Teacher\Lesson;
use App\Models\Course;
use App\Models\Lesson;
use Illuminate\Support\Facades\Lang;
use Livewire\Component;
use Livewire\WithFileUploads;
class Create extends Component
{
use WithFileUploads;
public $new_row;
public $authUser;
protected $listeners = ['store'];
public function updatedNewRowImage()
{
$this->validate([
'new_row.video' => 'required|file|max:3000|mimes:mp4',
]);
}
public function mount() {
$this->authUser = \Auth::user();
}
public function rules()
{
return [
'new_row.name.ar' => "required|min:3",
'new_row.name.en' => "required|min:3",
'new_row.content.ar' => "required|min:3",
'new_row.content.en' => "required|min:3",
'new_row.course_id' => 'required|exists:courses,id',
'new_row.video' => 'nullable|file',
'new_row.status' => 'required',
'new_row.duration' => 'required|numeric',
];
}
public function store()
{
$this->validate();
$video_name = $this->new_row['video']->store('video/lessons', 'public');
$this->new_row['video'] = basename(parse_url($video_name, PHP_URL_PATH));
$this->new_row['teacher_id'] = $this->authUser['id'];
Lesson::create($this->new_row);
$this->emit('alert', ['type' => 'success', 'message' => Lang::get('message.success_response_message')]);
return redirect()->route('teacher.lessons.index');
}
//
public function render()
{
$courses = Course::all();
return view('livewire.teacher.lesson.create', compact('courses'));
}
}
Lesson Model
<?php
namespace App\Models;
use App\Traits\FilterScopeModelTrait;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Spatie\Translatable\HasTranslations;
class Lesson extends Model
{
use HasFactory, FilterScopeModelTrait,HasTranslations;
public $translatable = ['name','content'];
protected $guarded = [];
protected function video(): Attribute
{
return Attribute::make(
get: fn($value) => ($this->attributes['video'] ?? false) ? asset('storage/videos/lessons/' . $this->attributes['video']) : '',
);
}
}
blade file
<div class="form-group col-md-6 mb-2">
<label class="col-sm-6 col-form-label" for="inputAdsVideo">#lang('teacher.video')</label>
<div class="col-sm-10 col-lg-10 col-md-2">
<input type="file" name="new_row.video" wire:model="new_row.video " id="Video"
class="form-control is-invalid"
>
</div>
#error('new_row.video')
<small class=" text text-danger" role="alert">
<strong>{{ $message }}</strong>
</small>
#enderror
</div>
migration
Schema::create('lessons', function (Blueprint $table) {
$table->id();
$table->json('name')->nullable();
$table->json('content')->nullable();
$table->foreignId('teacher_id')->nullable()->constrained();
$table->foreignId('course_id')->nullable()->constrained();
$table->float('duration')->nullable();
$table->text('video')->nullable();
$table->enum('status',['pending','publish']);
$table->timestamps();
});
crude of lessons to insert data in data base
when i try to insert data in data base this me undefined key
of video
pleas help to solve and try to upload video all data uploaded with me except video

Problem getting value for livewire component's public property

I am working on livewire in my project and I encounter a problem.
I have livewire model and blade file as below:
LivewireCounter.php
class LivewireCounter extends Component
{
public $count;
public function render()
{
return view(Constant::LIVEWIRE_COUNTER_BLADE);
}
public function mount($count = 0)
{
$this->count = $count + 1;
}
public function increment()
{
if($this->count >= Constant::LIVEWIRE_COUNTER_MAX)
{
$this->count = Constant::LIVEWIRE_COUNTER_MAX;
} else {
$this->count++;
}
}
public function decrement()
{
if($this->count <= Constant::LIVEWIRE_COUNTER_MIN)
{
$this->count = Constant::LIVEWIRE_COUNTER_MIN;
} else {
$this->count--;
}
}
}
livewire-counter.blade.php
<div>
<div class="flex inline-block relative w-64">
<button class="px-1" wire:click="decrement">-</button>
<h1>{{ $count }}</h1>
<button class="px-1" wire:click="increment">+</button>
</div>
</div>
I have a coupon blade file which uses livewire to track the coupon ordered by user.
coupon-show.blade.php
#extends(Constant::LAYOUTS_APP)
#section(Constant::LAYOUTS_CONTENT)
<div class="container">
<div>
<p class="text-4xl text-extrabold text-gray-900">{{ $CouponSetting->name }}</p>
#livewire('livewire-counter', ['count' => 9])
</div>
{{$count}}
</div>
</div>
#endsection
The problem I am having is I am unable to retrieve the $count value in the coupon-show.blade.php file. I thought the public property of the livewire component should be able to be accessed by blade view?
ErrorException
Undefined variable: count (View: /Applications/MAMP/htdocs/XXX/resources/views/layouts/coupons/coupon-show.blade.php)
Any idea why?

How to render element depends on selected option?

i'm newbie in react js , and i want to have a form with select options
i want that when user click on each option , each option render different elements
class Resepy extends Component {
state = {
Resepy : 'default'
}
render() {
return = (
<div className="Resepy">
<form>
<select id="id_field1" name="field1" onChange={(e) => this.state.Resepy = "Burger"}>
<option value="default">Food type not selected</option>
<option value="burger" onClick={(e) => this.setState({ Resepy: 'Burger' })}>Burger</option>
<option value="pizza" onClick={(e) => this.setState({ Resepy: 'Pizza' })}>Pizza</option>
</select>
<div className="food">
{ this.state.Resepy === "burger" ? <div className="burger"></div> //can return any html
: <div className="default">default</div>
}
<div className="pizza"></div>
<div className="food-detail"></div>
</div>
<button type="submit">Add to tray</button>
</form>
</div>
);
}
}
export default Resepy;
General ternary operator used for more readable code.
Like this:
<form>//can be any element
{ codition == true ? <div>It is true</div> //can return any html
: <div>It is false</div>
}
</form>
Tested, working. Problem was with onClick method option cannot invoke that event.
class Resepy extends React.Component {
constructor(props){
super(props);
this.state = {
selected : 'default'
};
}
setSelected = (event) => {
let select = document.getElementById("id_field1");
this.setState({selected: select.value});
//document.getElementById("test").innerHTML = select.value;
}
render() {
return (
<div className="Resepy">
<h1>Something</h1>
<form>
<select id="id_field1" name="field1" onChange={this.setSelected}>
<option value="default">Food type not selected</option>
<option value="burger">Burger</option>
<option value="pizza">Pizza</option>
</select>
<div id="test"></div>
<div className="food">{
(this.state.selected === "default") ?
<div className="default">Default</div>
: (this.state.selected === "burger") ?
<div className="burger">Burger</div>
: <div className="pizza">Pizza</div>
}</div>
<button type="submit">Add to tray</button>
</form>
</div>
);
}
}
I have a hard time understanding you, but the most likely thing you could be trying to achieve with the following code from your original question:
<div className="burger" Resepy={this.state.Resepy === 'burger'}></div>
is:
<div className="food">
<div className={this.state.Resepy} />
</div>
Working example (but I am using Hooks instead of a class component):
const App = () => {
const [selected, setSelected] = React.useState('default')
const handleChange = (event) => {
setSelected(event.target.value)
}
return (
<div>
<select value={selected} onChange={handleChange}>
<option>default</option>
<option>burger</option>
<option>pizza</option>
</select>
<div className="food">
<div className={selected}>{selected}</div>
</div>
</div>
)
}
ReactDOM.render(<App />, document.getElementById('root'))
.default { color: gray; }
.burger { color: orange; }
.pizza { color: red; }
<script crossorigin src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<div id="root"></div>
Now i want to render html elements depends on values , i tried this but it shows just [Object Object]
setSelected = (event) => {
let select = document.getElementById("id_field1");
document.getElementById("food").innerHTML =
select.value == "default" ?
<div className="default">Default</div>
: select.value == "Burger" ?
<div className="burger">Burger</div>
: <div className="pizza">Pizza</div>
}

My Bootstrap Modal is Not hiding after Successful Login,Got Stuck

I got stuck at this javascript code,why it is not working ,I used a static backdrop bootstrap model for login,after successful login ,i want to hide the model in success callback function but the model is not hiding,the Page is still there,don't know what i am doing wrong
enter image description here
Myjs File
$(document).ready(function () {
$('#myModal').modal({
backdrop: 'static',
});
});
function Login() {
var dataobject = { Social_Security_Number: $('#Social_Security_Number').val(), Lumik_Id: $('#Lumik_Id').val() };
// var dataobject = { Social_Security_Number:"123456789", Lumik_Id: "sgupta8" };
$.ajax({
url: '/User/Login',
type: "POST",
data: dataobject,
dataType: "json",
success: function (result) {
if (result.toString == "Success") {
$('#myModal').modal('hide');
//redirecttoPage()
}
},
error: function (result) {
alert('Error');
}
})
}
UserController
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using login.Models;
namespace login.Controllers
{
public class UserController : Controller
{
UserBusinessLogic obj = new UserBusinessLogic();
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(User user)
{
string message = "";
if (ModelState.IsValid)
{
if (obj.checkuserlogin(user) > 0)
{
message = "Success";
}
else
{
message = "Username or Password is wrong";
}
}
else {
message = "ALL FIELDS ARE REQUIRED";
}
if (Request.IsAjaxRequest())
{
return Json(message, JsonRequestBehavior.AllowGet);
// return RedirectToAction("Profile", "User", new { #name = result });
}
else
{
return RedirectToAction("Index", "Home");
}
}
public ActionResult Profile(string name)
{
return View();
}
}
}
Layout.cshtml
<!DOCTYPE html>
<html>
<head>
<title>#ViewBag.Title</title>
</head>
#*<script src="../../Scripts/jquery-1.9.1.js"></script>*#
<script src="../../Scripts/jquery-1.9.1.min.js"></script>
<script src="../../Scripts/Myfile.js"></script>
<link href="../../Scripts/bootstrap.min.css" rel="stylesheet" />
<script src="../../Scripts/bootstrap.min.js"></script>
<body>
#RenderBody()
</body>
Login.cshtml
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<form class="form-horizontal">
<div class="modal-header">
</div>
<br />
<div class="form-group">
<label for ="Social_Security_Number" class="col-lg-3 control-label"></label>
<input class="form-control" id="Social_Security_Number" placeholder="Social Security Number" type="text" />
</div>
<div class="form-group">
<label for="Lumik_Id" class="col-lg-3 control-label"></label>
<input class="form-control" id="Lumik_Id" placeholder="Lumik Id" type="text" />
</div>
<div class="modal-footer">
<input type="button" value="Login" class="btn btn-primary" onclick="Login()" />
</div>
</form>
</div>
</div>
</div>
<style>
.modal-dialog {
max-width:480px;
}
.modal-dialog {
transform:translate(0,58%) !important;
-as-transform:translate(0,58%) !important;
-webkit-transform:translate(0,58%) !important;
}
.RbtnMargin {
margin-left:90px;
}
</style>
Could you try : $(document).find('#myModal').modal('hide'); instead of $('#myModal').modal('hide');
Reason is : your data added dynamically.
Let me know.

{{bindAttr }} {{action}} [Object] Has no method replace

when ember.js tries to render my template containing the following bindAttr. the following exception is thrown in handlebars.js
Uncaught TypeError: Object [object Object] has no method 'replace' handlebars.js:848
bind attr tag:
<div class="postWrapper" {{bindAttr style="display:none"}}>
Update
this also happens when i use the action helper
<div {{action Toggle}} class="btn pull-right">
<i class="postToggler icon-chevron-down " ></i>
</div>
Update Full Code
Template
<script type="text/x-handlebars" data-template-name="Composer">
<div class="postWrapper">
<div class="postContentWrapper" {{bindAttr style="controller.display"}}>
<div class="row-fluid">
<div class="pull-left span10">
To :
<input id="test2" type="text" style="margin-top: 7px;width:90%" />
</div>
<div {{action Toggle}} class="btn pull-right">
<i class="postToggler icon-chevron-down " ></i>
</div>
</div>
<div class="row-fluid" style="height:100%" >
<div id="wmd-button-bar" style="width:48%;display:inline-block" ></div>
<div class="pull-right">
<a>Hide preview</a>
</div>
<div class="wmdWrapper" style="height:80%">
<div class="wmd-panel" style="vertical-align: top;">
<textarea class="wmd-input" id="wmd-input" style="height: 100%;"></textarea>
</div>
<div id="wmd-preview" class="wmd-preview pull-right"></div>
</div>
<br />
</div>
<div class="row-fluid">
<div class="span6 ">
<p>
Tags :
<input id="test" type="text" style="width:80%"/>
</p>
</div>
<div class="span2 pull-right">
<button id="btnSubmitPost" class="btn btn-success pull-right">{{controller.buttonText}}</button>
<button id="btnCanelPost" class="btn btn-warning pull-right">Cancel</button>
</div>
</div>
<div class="row-fluid">
</div>
</div>
</div>
</script>
View and render
/*
MODES
NEW
REPLY
*/
Thoughts.ComposerController = Ember.Object.extend({
mode: 2,
visible: false,
messageContent: "",
buttonText: function () {
switch (this.get("mode")) {
case 1: return "Post";
case 2: return "Reply";
}
}.property(),
display: function () {
if (this.get("visible")) {
return 'display:block';
} else
return 'display:none';
}.property(),
Toggle: function(){
console.log('Helllo');
}
});
Thoughts.ComposerController = Thoughts.ComposerController.create();
Error Information
object dump
string: "data-ember-action="1""
__proto__: Object
constructor: function (string) {
toString: function () {
__proto__: Object
Crashes on the replace method, because the method replace is undefined
Handlebars.Utils = {
escapeExpression: function (string) {
// don't escape SafeStrings, since they're already safe
if (string instanceof Handlebars.SafeString) {
return string.toString();
} else if (string == null || string === false) {
return "";
}
if (!possible.test(string)) { return string; }
----> return string.replace(badChars, escapeChar);
},
So first of all you need to define only need to define the controller. You don't have to create an instance. Ember will do it for you when application initialize.
If you define a property that is observing another in other words its value depends on another, you need this to specify as parameter to property helper.
Thoughts.ComposerController = Ember.Controller.extend({
mode: 2,
visible: false,
messageContent: "",
buttonText: function () {
switch (this.get("mode")) {
case 1: return "Post";
case 2: return "Reply";
}
}.property('mode'),
display: function () {
return 'display:' + this.get('visible') ? 'block' : 'none';
}.property('visible'),
Toggle: function () {
this.toggleProperty('visible');
this.set('mode', this.get('mode') == 2 ? 1 : 2);
}
});
Template itself seems valid.
You can get this working by creating a composer route like this:
this.route('composer');
or by rendering it in another template like this:
{{render 'composer'}}
That should be answer to your question. BUT
Wouldn't be better to use {{if}} helper for showing some content inside of template based on a condition?
i finally found some time to work on this again.
all i did was replace the ember and handlebars js files, and the code is working fine now thanks