RedBeanPhP dispense doesn't fill the table, but create it - redbean

I'm creating a comment table. So RedBean create a table but doesn't fill it with information
My code
if (isset($_POST['send'])) {
$comments = R::dispense('comments');
var_dump($comments);
$comments['id'] = $_GET['id'];
$comments->firstName = $_SESSION['first_name'];
$comments->lastName = $_SESSION['last_name'];
$comments->message = $_POST['message'];
$comments->avatar = $_SESSION['avatar'];
R::store($comments);
My form
<form action="" id="commentForm" method="post">
<div class="col-md-6">
<input type="text" placeholder="Ваш комментарий" class="mb-3 mt-3 form-control" name="message" minlength="5" required>
</div>
<div class="col-md-6" style="margin-bottom: 1rem;">
<input type="submit" class="btn btn-primary" name="send">
All fields are filled, but it doesn't work how i want

//Define your mappings like this
define( 'POEM', 'tbl_poem' );
define( 'BOOK', 'tbl_book' );
define( 'AUTHOR', 'tbl_author' );
define( 'CATEGORY', 'tbl_category' );
define( 'POEMS', 'ownTblPoem' );
define( 'CATEGORIES', 'sharedTblCategory' );
//Create an extension to by-pass security check in R::dispense
R::ext('xdispense', function( $type ){
return R::getRedBean()->dispense( $type );
});
//Use tbl_book_category instead of tbl_book_tbl_category
R::renameAssociation([
'tbl_book_tbl_category' => 'tbl_book_category'
]);
//Use them like this:
$poem = R::xdispense( POEM );
$poem->title = 'Trees';
$author = R::xdispense( AUTHOR );
$author->name = 'Joyce Kilmer';
$book = R::xdispense( BOOK );
$book->title = 'Trees and other poems';
$category = R::xdispense( CATEGORY );
$category->name = 'nature';
$book->{AUTHOR} = $author;
$book->{POEMS}[] = $poem;
$book->{CATEGORIES}[] = $category;
$id = R::store( $book );
//For testing purposes let's output something:
$book = R::load( BOOK, $id );
$poem = reset( $book->{POEMS} );
$author = $book->{AUTHOR};
$category = reset( $book->{CATEGORIES} );
echo "Have you ever read '{$poem->title}' ({$book->title}) by {$author->name} ?
it's a beautiful poem about {$category->name}.";

Related

Chat using signalR in asp.net mvc

I am trying to make a chat application using SignalR wherein the user can chat with other users in a private box. Everything works fine except for the fact that the client and the user chats are displayed on the same side and work fine when refreshed.
Here's my code for the Same:
public class ChatHub : Hub
{
static List<ConnectedUser> objConnectedUserList = new List<ConnectedUser>();
MessagingDAL objMessagingDAL = new MessagingDAL();
NurseDAL objNurseDAL = new NurseDAL();
public void SendPrivateMessage(Messaging objMessaging)
{
var fromNurse = objConnectedUserList.FirstOrDefault(x => x.NurseId == objMessaging.FromNurseId);
var toNurse = objConnectedUserList.FirstOrDefault(x => x.NurseId == objMessaging.ToNurseId);
var chatObject = new { MessageThreadId = 0, Name = fromNurse.NurseName, Message = objMessaging.Message, DTStmp = DateTime.Now, frmNurseId = fromNurse.NurseId };
Result objResult = objMessagingDAL.InsertMessage(objMessaging);
if (toNurse != null)
{
Clients.Client(toNurse.ConnectionId).ReceivePrivateMessage(chatObject);
}
Clients.Caller.ReceivePrivateMessage(chatObject);
}
}
}
Here's my code for Controller:
$scope.SendPrivateMessage = function (message) {
if ($scope.Thread.MessageThreadId == null) {
UserService.showAlert('Please select a Nurse', 0);
return;
}
else {
var chatObject =
{
MessagingThreadId: $scope.Thread.MessageThreadId,
Message: message,
ToRecruiter: null,
ToRecruiterId: null,
FromRecruiter: null,
FromRecruiterId: null,
ToNurse: null,
ToNurseId: $scope.Thread.ToNurseId,
FromNurse: null,
FromNurseId: $scope.Thread.FromNurseId,
CreatedOn: new Date(),
RecivedOn: new Date(),
LastMessageOn: new Date(),
}
}
signalR.SendPrivateMessage(chatObject);
$scope.Messaging.Message = '';
$scope.Init(chatObject.Message);
}
signalR.ReceivePrivateMessage(function (chatObject) {
$scope.Messages.push(chatObject);
//$scope.Messages.push({ chatObject });
$("#autoscroll").animate({ scrollTop: $("#autoscroll")[0].scrollHeight * 2 }, 100);
$scope.$apply();
$scope.Init(chatObject.Message);
});
Following is my code for the HTML Page:
<div class="chat_container no-margin no-padding">
<div class="no-margin no-padding MsgRightPnlHdr">
<span class="chatNameRight" ng-bind="Thread.Name"></span>
<span class="chatNameDesigRight" ng-bind="Thread.Designation"></span>
</div>
<div class="userTyping">
<span class="chatNameDesigRight" ng-bind=usertyping></span>
</div>
<div class="no-margin no-padding msgDsplyPnl message-right" id="autoscroll">
<div ng-repeat="msg in Messages" ng-if="msg.Message">
<div class="no-margin no-padding imgDiv1" ng-if="msg.Type=='in'">
<img src="#baseUrl{{Thread.img}}" class="img-responsive" />
</div>
<span class="{{msg.Type=='in'?'pull-left lt-box inMsg':'pull-left rt-box outMsg'}}">{{msg.Message}}<br />
<span class="chatLstDTstmp message-time">{{msg.DTStmp | date:'dd MMM, yyyy hh:mm a'}}</span>
</span>
</div>
</div>
<div class="form-group no-margin no-padding">
<div class="no-margin no-padding">
<textarea name="Message" class="form-control txt-area" style="height:36px; margin-bottom: 10px; resize:none;"
placeholder="Type your Message here..." ng-model="Messaging.Message" ng-keypress="SkeyPress($event)"></textarea>
</div>
<div class="no-margin no-padding">
<button class="btn sendBtn ms-btn" style="width: 100%;height: 60px;border-radius: 0;" ng-click="SendPrivateMessage(Messaging.Message);" ng-disabled="!Messaging.Message">
Send
</button>
</div>
</div>
</div>
Also, the CSS is fine as once the page is refreshed, the chat goes to its respective sides.
Attached image for reference:
Error I am facing
Try this in your ReceivePrivateMessage in app.js:
chatObject.Type = ($scope.UserId == chatObject.frmNurseId ? "out" : "in");
As I've understood is that the position of the message from the other user is not correct?
You're doing the formatting based on the message type: msg.Type='in'
<span class="{{msg.Type=='in'?'pull-left lt-box inMsg':'pull-left rt-box outMsg'}}">{{msg.Message}}<br />
I do not see where do you declare the type of the message, and what does the function $scope.Init(message) actually do?
Also on the hub you do send same message to the caller and the client and what I think is wrong is that they get message with same type, which should not be the case.
What should you do there (at the Hub class) is set message type 'in' for caller, 'out' for client (or vise versa, as you prefer) and in that case the rendering should be fine.
Example:
public void SendPrivateMessage(Messaging objMessaging)
{
var fromNurse = objConnectedUserList.FirstOrDefault(x => x.NurseId == objMessaging.FromNurseId);
var toNurse = objConnectedUserList.FirstOrDefault(x => x.NurseId == objMessaging.ToNurseId);
var chatObject = new { MessageThreadId = 0, Name = fromNurse.NurseName, Message = objMessaging.Message, DTStmp = DateTime.Now, frmNurseId = fromNurse.NurseId };
Result objResult = objMessagingDAL.InsertMessage(objMessaging);
if (toNurse != null)
{
chatObject.Type = "in"; //set different type for receiver and sender
Clients.Client(toNurse.ConnectionId).ReceivePrivateMessage(chatObject);
}
chatObject.Type = "out";
Clients.Caller.ReceivePrivateMessage(chatObject);
}

knockout.js: how to make a dependent cascading dropdown unconditionally visible?

Getting started with knockout, I have been playing with the pattern found at http://knockoutjs.com/examples/cartEditor.html. I have cascading select menus where the second one's options depend on the state of the first -- no problem so far. But whatever I do, I haven't figured a way to change the out-of-the-box behavior whereby the second element is not visible -- not rendered, I would imagine -- until the first element has a true-ish value (except by taking out the optionsCaption and instead stuffing in an empty record at the top of my data -- more on that below.) The markup:
<div id="test" class="border">
<div class="form-row form-group">
<label class="col-form-label col-md-3 text-right pr-2">
language
</label>
<div class="col-md-9">
<select class="form-control" name="language"
data-bind="options: roster,
optionsText: 'language',
optionsCaption: '',
value: language">
</select>
</div>
</div>
<div class="form-row form-group">
<label class="col-form-label col-md-3 text-right pr-2">
interpreter
</label>
<div class="col-md-9" data-bind="with: language">
<select class="form-control" name="interpreter"
data-bind="options: interpreters,
optionsText : 'name',
optionsCaption: '',
value: $parent.interpreter"
</select>
</div>
</div>
</div>
Code:
function Thing() {
var self = this;
self.language = ko.observable();
self.interpreter = ko.observable();
self.language.subscribe(function() {
self.interpreter(undefined);
});
};
ko.applyBindings(new Thing());
my sample data:
roster = [
{ "language": "Spanish",
"interpreters": [
{"name" : "Paula"},
{"name" : "David"},
{"name" : "Humberto"},
{"name" : "Erika"},
{"name" : "Francisco"},
]
},
{"language":"Russian",
"interpreters":[{"name":"Yana"},{"name":"Boris"}]
},
{"language":"Foochow",
"interpreters":[{"name":"Lily"},{"name":"Patsy"}]
},
/* etc */
Now, I did figure out that I can hack around this and get the desired effect by putting
{ "language":"", "interpreters":[] }
at the front of my roster data structure, and that's what I guess I will do unless one of you cognoscenti can show me the more elegant way that I am overlooking.
After using both Knockout and Vuejs, I found Vuejs much easier to work with. Knockout is a bit out dated and no longer supported by any one or group.
Having said that, here is how I addressed your issue. The comments here refer to the link you provided not your code so I could build my own test case.
My working sample is at http://jsbin.com/gediwal/edit?js,console,output
I removed the optionsCaption from both select boxes.
Added the following item to the data (note that this has to be the first item in the arry):
{"products":{"name":"Waiting", "price":0}, "name":"Select..."},
I added the disable:isDisabled to the second selectbox cause I want it to be disabled when nothing is selected in the first selectbox.
added self.isDisabled = ko.observable(true); to the cartline model
altered the subscription to check the new value. If it is the select option the second one gets lock.
function formatCurrency(value) {
return "$" + value.toFixed(2);
}
var CartLine = function() {
var self = this;
// added this to enable/disable second select
self.isDisabled = ko.observable(true);
self.category = ko.observable();
self.product = ko.observable();
self.quantity = ko.observable(1);
self.subtotal = ko.computed(function() {
return self.product() ? self.product().price * parseInt("0" + self.quantity(), 10) : 0;
});
// Whenever the category changes, reset the product selection
// added the val argument. Its the new value whenever category lchanges.
self.category.subscribe(function(val) {
self.product(undefined);
// check to see if it should be disabled or not.
self.isDisabled("Select..." == val.name);
});
};
var Cart = function() {
// Stores an array of lines, and from these, can work out the grandTotal
var self = this;
self.lines = ko.observableArray([new CartLine()]); // Put one line in by default
self.grandTotal = ko.computed(function() {
var total = 0;
$.each(self.lines(), function() { total += this.subtotal() })
return total;
});
// Operations
self.addLine = function() { self.lines.push(new CartLine()) };
self.removeLine = function(line) { self.lines.remove(line) };
self.save = function() {
var dataToSave = $.map(self.lines(), function(line) {
return line.product() ? {
productName: line.product().name,
quantity: line.quantity()
} : undefined
});
alert("Could now send this to server: " + JSON.stringify(dataToSave));
};
};

React js find control of variable from different component class in one jsx file?

I have made an example of add/remove data in basic table in React JS. Everything is working, but now i m stuck to get row value into textboxes for edit operation.
Tried to get variable value like var cname = this.refs.cname.getDOMNode().value; from one component NewRow function handleRowSubmit and set its value in another component Company function handleRowEdit.But nothing works for me.
JSX file :
var CompanyApp = React.createClass({
getInitialState: function() {
return {
companylist : this.props.companies
};
},
handleNewRowSubmit: function(newcompany) {
this.setState( {companylist: this.state.companylist.concat([newcompany])} );
},
handleCompanyRemove: function( company ) {
var index = -1;
var clength = this.state.companylist.length;
for( var i = 0; i < clength; i++ ) {
if( this.state.companylist[i].cname === company.cname ) {
index = i;
break;
}
}
this.state.companylist.splice( index, 1 );
this.setState( {companylist: this.state.companylist} );
},
render: function() {
var tableStyle = {width: '100%'};
var leftTdStyle = {width: '50%',padding:'20px',verticalAlign: 'top'};
var rightTdStyle = {width: '50%',padding:'20px',verticalAlign: 'top'};
return (
<table style={tableStyle}>
<tr>
<td style={leftTdStyle}>
<CompanyList clist={this.state.companylist} onCompanyRemove={this.handleCompanyRemove}/>
</td>
<td style={rightTdStyle}>
<NewRow onRowSubmit={this.handleNewRowSubmit}/>
</td>
</tr>
</table>
);
}
});
var CompanyList = React.createClass({
handleCompanyRemove: function(company){
this.props.onCompanyRemove(company);
},
render: function() {
var companies = [];
var that = this;
// TODO: Needs to find out why that = this made it work; Was getting error that onCompanyDelete is not undefined
this.props.clist.forEach(function(company) {
companies.push(<Company company={company} onCompanyDelete={that.handleCompanyRemove} /> );
});
return (
<div>
<h3>List of Companies</h3>
<table className="table table-striped" id="tableId">
<thead><tr><th>Company Name</th><th>Employees</th><th>Head Office</th><th>Action</th></tr></thead>
<tbody>{companies}</tbody>
</table>
</div>
);
}
});
var Company = React.createClass({
handleRemoveCompany: function() {
this.props.onCompanyDelete( this.props.company );
return false;
},
handleRowEdit:function() {
var name = this.state.vals;
var rows = document.getElementsByTagName('tr');
var HO = '' ;
var CompName = '' ;
var noOfEmployees = '' ;
for ( var i = 1; i < rows.length; i++)
{
rows[i].i = i;
rows[i].onclick = function()
{
CompName = rows[this.i].cells[0].innerHTML;
noOfEmployees = rows[this.i].cells[1].innerHTML;
HO = rows[this.i].cells[2].innerHTML;
alert("rows---" + CompName + noOfEmployees + JSON.stringify(vals));
// here i got the selected row but don't know how to get textbox control here
};
}
},
render: function() {
return (
<tr>
<td>{this.props.company.cname}</td>
<td>{this.props.company.ecount}</td>
<td>{this.props.company.hoffice}</td>
<td><input type="button" className="btn btn-primary" value="Edit" onClick = {this.handleRowEdit} /></td>
<td><input type="button" className="btn btn-primary" value="Remove" onClick = {this.handleRemoveCompany}/></td>
</tr>
);
}
});
var NewRow = React.createClass({
handleSubmit: function(cname) {
var cname = this.refs.cname.getDOMNode().value;
var ecount = this.refs.ecount.getDOMNode().value;
var hoffice = this.refs.hoffice.getDOMNode().value;
var newrow = {cname: cname, ecount: ecount, hoffice: hoffice };
this.props.onRowSubmit(newrow);
this.refs.cname.getDOMNode().value = '';
this.refs.ecount.getDOMNode().value = '';
this.refs.hoffice.getDOMNode().value = '';
return false;
},
componentDidMount: function(){
this.refs.cname.getDOMNode().focus();
},
render: function() {
var inputStyle = {padding:'12px'}
return (
<div className="well">
<h3>Add A Company</h3>
<form onSubmit={this.handleSubmit}>
<div className="input-group input-group-lg" style={inputStyle}>
<input type="text" className="form-control col-md-8" placeholder="Company Name" ref="cname" required/>
</div>
<div className="input-group input-group-lg" style={inputStyle}>
<input type="text" className="form-control col-md-8" placeholder="Employee Count" ref="ecount" required/>
</div>
<div className="input-group input-group-lg" style={inputStyle}>
<input type="text" className="form-control col-md-8" placeholder="Headoffice" ref="hoffice" required/>
</div>
<div className="input-group input-group-lg" style={inputStyle}>
<input type="submit" className="btn btn-primary" value="Add Company" required/>
</div>
</form>
</div>
);
}
});
var defCompanies = [{cname:"Infosys Technologies",ecount:150000,hoffice:"Bangalore"},
{cname:"TCS",ecount:140000,hoffice:"Mumbai"}];
React.render( <CompanyApp companies={defCompanies} />, document.getElementById("companyApp"));
You need to pass the selected company into your new row component.
To do this create a new function, and pass the information back up your component chain, then pass it into the new row component.
handleRowEdit:function() {
var HO = this.props.company.cname;
var CompName = this.props.company.hoffice;
var noOfEmployees = this.props.company.ecount;
console.log("rows---" + CompName + noOfEmployees);
this.props.onEdit(this.props.company)
}
The below plnkr gets the information where it needs to go. I will leave you to pulling out the company info and adding them into the correct fields.
http://embed.plnkr.co/ve24aHo9MbkyhxIzaE4Z/
I have found answer for my own question!!
Just create textbox inside Row for Edit operation.
JSX file :
var CompanyApp = React.createClass({
getInitialState: function() {
return {
companylist : this.props.companies
};
},
handleNewRowSubmit: function(newcompany) {
this.setState( {companylist: this.state.companylist.concat([newcompany])} );
},
handleCompanyRemove: function( company ) {
var index = -1;
var clength = this.state.companylist.length;
for( var i = 0; i < clength; i++ ) {
if( this.state.companylist[i].cname === company.cname ) {
index = i;
break;
}
}
this.state.companylist.splice( index, 1 );
this.setState( {companylist: this.state.companylist} );
},
render: function() {
var tableStyle = {width: '100%'};
var leftTdStyle = {width: '50%',padding:'20px',verticalAlign: 'top'};
var rightTdStyle = {width: '50%',padding:'20px',verticalAlign: 'top'};
return (
<table style={tableStyle}>
<tr>
<td style={leftTdStyle}>
<CompanyList clist={this.state.companylist} onCompanyRemove={this.handleCompanyRemove} />
</td>
<td style={rightTdStyle}>
<NewRow onRowSubmit={this.handleNewRowSubmit } />
</td>
</tr>
</table>
);
}
});
var CompanyList = React.createClass({
handleCompanyRemove: function(company){
this.props.onCompanyRemove(company);
},
render: function() {
var companies = [];
var that = this;
// TODO: Needs to find out why that = this made it work; Was getting error that onCompanyDelete is not undefined
this.props.clist.forEach(function(company) {
companies.push(<Company company={company} onCompanyDelete={that.handleCompanyRemove} /> );
});
return (
<div>
<h3>List of Companies</h3>
<table className="table table-striped" id="tableId">
<thead><tr><th>Company Name</th><th>No. Of Employees</th><th>Head Office</th><th>Action</th></tr></thead>
<tbody>{companies}</tbody>
</table>
</div>
);
}
});
var Company = React.createClass({
getInitialState : function(){
return {
editing : false,
cname : this.props.company.cname,
ecount : this.props.company.ecount,
hoffice : this.props.company.hoffice,
};
},
_onchangeCname:function(event) {
this.setState({cname : event.target.value});
},
_onchangeEmpCount:function(event){
this.setState({ecount : event.target.value});
},
_onchangeCompHO:function(event){
this.setState({hoffice : event.target.value});
},
handleRemoveCompany: function() {
this.props.onCompanyDelete( this.props.company );
return false;
},
handleRowEdit:function() {
var getCName = this.state.cname.trim();
var getEmpCount = this.state.ecount;
var getCompHO = this.state.hoffice;
this.setState({
getCName : this.state.cname,
getEmpCount : this.state.ecount,
getCompHO : this.state.hoffice
})
this.setState({editing : true });
return false;
},
handleUpdateRow:function(){
var getCName = this.state.cname.trim();
var getEmpCount = this.state.ecount;
var getCompHO = this.state.hoffice;
this.setState({
getCName : this.state.cname,
getEmpCount : this.state.ecount,
getCompHO : this.state.hoffice
})
alert("updated vals "+ getCName+","+getEmpCount+","+getCompHO );
this.props.company.cname = getCName;
this.props.company.ecount = getEmpCount;
this.props.company.hoffice = getCompHO;
this.setState({editing : false });
return false;
},
handleCancelEdit : function(){
this.setState({editing : false });
return false;
},
render: function() {
var inputStyle = {padding:'-3px'};
var EditBtn = <input type ="button" className ="btn btn-primary"
value ="Edit" onClick ={this.handleRowEdit} />;
var UpdateBtn = <input type ="button" className ="btn btn-primary"
value ="Update" onClick ={this.handleUpdateRow} />;
var RemoveBtn = <input type ="button" className ="btn btn-primary"
value ="Remove" onClick ={this.handleRemoveCompany}/>;
var CancelEditBtn = <input type ="button" className ="btn btn-primary"
value ="Cancel" onClick = {this.handleCancelEdit}/>;
return(
<tr>
<td>{this.state.editing ? <input type="text" style={inputStyle} ref="CompName"
value={this.state.cname} onChange={this._onchangeCname} />
: this.props.company.cname}</td>
<td>{this.state.editing ? <input type="text" style={inputStyle} ref="EmpCount"
value={this.state.ecount} onChange={this._onchangeEmpCount} />
: this.props.company.ecount}</td>
<td>{this.state.editing ? <input type="text" style={inputStyle} ref="CompHO"
value={this.state.hoffice} onChange={this._onchangeCompHO}/>
: this.props.company.hoffice}</td>
<td>{this.state.editing ? UpdateBtn : EditBtn }</td>
<td>{this.state.editing ? CancelEditBtn : RemoveBtn}</td>
</tr>
)
}
});
var NewRow = React.createClass({
handleSubmit: function() {
var cname = this.refs.cname.getDOMNode().value;
var ecount = this.refs.ecount.getDOMNode().value;
var hoffice = this.refs.hoffice.getDOMNode().value;
var newrow = {cname: cname, ecount: ecount, hoffice: hoffice };
this.props.onRowSubmit(newrow);
this.refs.cname.getDOMNode().value = '';
this.refs.ecount.getDOMNode().value = '';
this.refs.hoffice.getDOMNode().value = '';
return false;
},
componentDidMount: function(){
this.refs.cname.getDOMNode().focus();
},
render: function() {
var inputStyle = {padding:'12px'}
return (
<div className="well">
<h3>Add A Company</h3>
<form onSubmit={this.handleSubmit} >
<div className="input-group input-group-lg" style={inputStyle}>
<input type="text" className="form-control col-md-8" placeholder="Company Name"
name="cname" ref="cname" required/>
</div>
<div className="input-group input-group-lg" style={inputStyle}>
<input type="text" className="form-control col-md-8" placeholder="Employee Count"
ref="ecount" required/>
</div>
<div className="input-group input-group-lg" style={inputStyle}>
<input type="text" className="form-control col-md-8" placeholder="Headoffice"
ref="hoffice" required/>
</div>
<div className="input-group input-group-lg" style={inputStyle}>
<input type="submit" className="btn btn-primary" value="Add Company" />
</div>
</form>
</div>
);
}
});
var defCompanies = [{cname:"Infosys Technologies",ecount:150000,hoffice:"Bangalore"},
{cname:"TCS",ecount:140000,hoffice:"Mumbai"}];
React.render(<CompanyApp companies={defCompanies} />, document.getElementById("companyApp"));
Now its working all operations :)
http://embed.plnkr.co/N25QauVLvbABmSDIBU9o/

laravel Undefined variable: :

i get this error i don't no why
the line between section id and books
Undefined variable: section (View: C:\xampp\htdocs\lib\resources\views\books\create_book.blade.php)
the link New Book
my create_book.blade.php
{!! Form::open(['url'=>'admin_book/store','method'=>'POST','files'=>'true']) !!}
{!! Form::hidden('section_id',$section->id) !!}
<div class="form-group ">
{!! Form::label('Book Title', 'Enter the Title of Book:') !!}
{!! Form::text("book_title",'',['class'=>'form-control']) !!}
</div>
<div class="form-group ">
{!! Form::label('Book Edition', 'Enter the Edition of Book:') !!}
{!! Form::text("book_edition",'',['class'=>'form-control']) !!}
</div>
<div class="form-group ">
{!! Form::label('Book Description', 'Enter the Description of Book:') !!}
{!! Form::textarea("book_description",'',['class'=>'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('upload', 'Upload an Image:') !!}
{!! Form::file('image','',['class'=>'form-control']) !!}
</div>
<br>
<div class="form-group">
{!! Form::submit('Create',['class'=>'btn btn-info btn-block']) !!}
</div>
{!! Form::close() !!}
and my booksControllers
public function create()
{
return view('books.create_book');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$book_title = $request ->input('book_title');
$book_edition = $request ->input('book_edition');
$book_description = $request ->input('book_description');
$file = $request ->file('image');
$destinationPath = 'images';
$filename = $file ->getClientOriginalName();
$file ->move($destinationPath,$filename);
$section_id = $request -> section_id;
$new_book = new Book;
$new_book ->book_title = $book_title;
$new_book ->book_edition = $book_edition;
$new_book ->book_description = $book_description;
$new_book ->image_name = $filename;
$new_book ->section_id = $section_id;
$new_book ->save();
return redirect('admin_book/'.$section_id);
}
and my route
Route::get('admin_book/createbook','BooksController#create');
You didn't pass the $section variable to your view. You have to retrieve the variable from the database and pass it to the view like this:
public function create() {
//Retrieve from database
$section = Section::all();
//Pass the collection to the view
return view('books.create_book')->with('section', $section);
}
As Tim Lewis has pointed out, you haven't passed in the $section variable when you have created the view.
Your create method, should look like this:
public function create()
{
//Logic that gets the section goes here
//Stored in the $section variable
return view('books.create_book', ['section' => $section]);
}
This will solve your error as Undefined variable: section is telling you that within your view, a variable named section does not exist. Simply pass it through and it will.

Jquery Mobile val() returns undefined after changePage

I have 2 pages that I'm working with: first being the page where the values are being fetched from php server and populating the selects/inputs and the second page being a dialog box that fetches the value from the hidden inputs in the first page. The first transition opens the dialog box and fetches the values properly. After which I save the values in php session and reload the first page. After this process when I open the dialog box again the jquery is not able to fetch val() and shows undefined. I'm not sure if this is due to some reloading of the page issue or something else. If I refresh the page then it will work fine again.
<div data-role="page" id="page1">
<div data-theme="a" data-role="header">
.....
<div data-role="navbar" data-iconpos="top">
.....
</div>
<div data-theme="c" id="cashtab" data-role="content">
<div style="display:none" id="proddata" data=""></div>
<div style="display:none" id="prodstock" data=""></div>
<form id="mainsubmit" action="form.php" method="post" data-ajax="false">
<input id="formproduct" type="hidden" name="product" value=""/>
<div id="productsearch" style="width:48%; float:left; margin-right:2%;">
<label for="search">Search Product:</label><br/><br/>
<ul id="productautocomplete" data-role="listview" data-inset="true" data-filter="true" data-filter-placeholder="Select a product... (type at least 3 letters)" data-filter-theme="d"></ul>
</div>
<div id="packingselect" style=" width:23%; float:left; margin-right:2%;">
<label for="packing">Select Packing:</label>
<select name="packing" id="packing" data-iconpos="left">
</select>
</div>
<div id="qtyenter" style=" width:23%; float:left; margin-right:2%;">
<label for="quantity">Select Qty:</label>
<input type="number" data-clear-btn="true" name="quantity" id="qty" value=""/>
</div><br/><br/><br/><br/><br/><br/><br/><br/>
<div style="display:inline-block; width:33%; margin-left:33%; margin-right:33%;">
<a href="#page3" data-rel="dialog" data-role="button" >ADD</a>
</div>
</form>
</div>
</div>
<div data-role="page" id="page3" data-url="dialog.html" data-close-btn="right">
<div data-role="header">
<h1>Batch Selection</h1>
</div>
<div data-role="content">
<div style="overflow:auto;">
<table id="batchsel" style="border:1px;">
<thead>
<tr>
<th></th>
<th>Batch No</th>
<th>Exp Date</th>
<th>Brate</th>
<th>Srate</th>
<th>Packing</th>
<th>Stock</th>
<th>Supplier</th>
<th>ST%</th>
<th>Bill Date</th>
<th>Bill No</th>
<th>btax</th>
</tr>
</thead>
<!--data populated from server once the values from first page is read properly.
<!-- currently not loading the second time as unable to fetch val() -- >
<tbody>
</tbody>
</table>
</div>
<div id="remainingdata">
<p1 id="changeable_requirements"></p1>
<!-- function the send the checked checkboxes relavent info to store in session -->
<button id="saveprod" onclick="addProduct(); return false;">Add Product</button>
</div>
</div>
</div>
<script>
$( document ).on( "pageinit", "#page1", function() {
//for product select autopopulate -- working //
$("#productautocomplete").live( "listviewbeforefilter", function ( e, data ) {
var $ul = $( this ),$input = $( data.input ),value = $input.val(),html = "";
$ul.html( "" );
if ( value && value.length > 2 ) {
$ul.html( "<li><div class='ui-loader'><span class='ui-icon ui-icon-loading'></span></div></li>" );
$ul.listview( "refresh" );
$.getJSON('ajax/getProductList.php', {term:$input.val()}, function(data) {
var items = [];
var str = "";
for (var key in data) {
if (data.hasOwnProperty(key)) {
var value = data[key].value;
var label = data[key].label;
var stock = data[key].stock;
var proddata = data[key].data;
str += '<li code="'+value+'" name="'+label+'" stock="'+stock+'" data="'+proddata+'">';
str += '<a data-ajax="false" rel="external">'+label+' [ '+stock+' ]</a>';
str += '</li>';
}
}
$ul.html( str );
$ul.listview( "refresh" );
$ul.trigger( "updatelayout" );
});
}
});
//end search
//on click set hidden input fields to be used in dialog box. -- working
$('#productautocomplete li').live('click', function(e) {
//--------------------fetch data ------------------------
var id = $(this).attr('code');
var name = $(this).attr('name');
var data = $(this).attr('data');
var stock = $(this).attr('stock');
//add packaging type and unit info to div data
$('#proddata').attr('data',data);
//add currstock info to div
$('#prodstock').attr('data',stock);
//----------------------hide list
$('#productautocomplete li').hide();
//----------------------place name in visible input box
$('#productsearch input').attr('value',name);
//----------------------place id in hidden input box for the actual form.
$('#formproduct').val(id);
//----------------------fill options for package + show select package div
var filteroptions = data.split(",");
$('#packing option').remove();
for (var x=0; x<3 ; x++) {
var eachoption = filteroptions[x].split(":");
//if unit wise option is less than that of stock show as option.
if (eachoption[0]!="0" && eachoption[0] <= stock.valueOf()) {
$('#packing').append($('<option>', {
value: eachoption[0]+':'+eachoption[1],
text : eachoption[1]+' [ '+eachoption[0]+' ] '
}));
}
}
});
});
//this is where the problem lies ..
//have tried with pageinit.. but that only calls it once.
$( document ).on( "pageshow", "#page3", function() {
$('#batchsel tbody').empty();
// !!!!!!!!!!!!!!!!!!!!!!! // !!!!!!!!!!!!!!!!!!!!!!! //
//doesnt fetch any of 4 following values after pageChange back to page1.
//not sure if this is due to how i'm reloading the page1.
//see function addProduct below.
var prodcode = $('#formproduct').val(); //
var prodstock = $('#prodstock').attr('data');
var prodqty = $('#qty').val();
var packing = $('#packing').find(":selected").val();
//returns undefined
alert(prodcode); alert(packing); alert(prodqty);
//always ends here when dialog opens second time.
if (!prodcode || !packing || !prodqty) {
alert("Please give all required information");
//does not close also when opens the second time.
$('#page3').dialog('close');
}
var packinginfo = packing.split(":");
var totalrequired = prodqty * packinginfo[0];
//alert(packinginfo[1]);alert(totalrequired);
if (totalrequired > prodstock ) {
alert("Not enough Stock");
$('#page3').dialog('close');
} else {
//------------------------------ Getting Batch Info ---------------------------------------------------
var rows = '';
$.getJSON('ajax/getBatchDetails.php', {code:prodcode,pack:packinginfo[1],qty:totalrequired}, function(data) {
for (var key in data) {
if (data.hasOwnProperty(key)) {
//alert (data[key].Batch);
rows += '<tr><td><input type="checkbox" class="batchcheckbox" id="batchcheckbox_'+data[key].BatchId+'" value="'+data[key].BatchId+':'+data[key].Stock+'" onchange="resetRemainingQty(this.value);""/></td><td>' + data[key].Batch + '</td><td>' + data[key].ExDt +'</td><td>' + data[key].BRate + '</td><td>' + data[key].SRate + '</td><td>' + data[key].Pack + '</td><td>' + data[key].Stock + '</td><td>' + data[key].Supname + '</td><td>' + data[key].Stax + '</td><td>' + data[key].BillDt + '</td><td>' + data[key].BillNo + '</td><td>' + data[key].btax + '</td><tr>';
}
}
$('#batchsel tbody').append(rows);
//add remaining amount in the data field of p1.
$('#remainingdata p1').attr('data',totalrequired);
$('#remainingdata p2').attr('data',totalrequired);
$('#remainingdata p1').html("<h4>Remaining Amount : "+totalrequired+"</h4>");
});
//---------------------------------------------end batch info display: -----------------------------------
}
});
function addProduct() {
//--------code info---------
var prodcode = $("#formproduct").val(); // to send
//--------packing info---------------
var packing = $('#packing').find(":selected").val();
var packinginfo = packing.split(":");
//-----------qty req ---------------------
var prodqty = $('#qty').val();
var totalrequired = prodqty * packinginfo[0]; // to send
//-------------batch info -----------
var allbatchids = "";
$('.batchcheckbox').each(function() {
if($(this).is(':checked')){
var data = $(this).val();
var datasplit = data.split(":");
var batchid = datasplit[0];
allbatchids += batchid+":";
}
});
allbatchids = allbatchids.substring(0, allbatchids.length - 1); // to send
alert(prodcode+",,"+packinginfo[1]+",,"+totalrequired+",,"+allbatchids);
//-------------- send to server to save to session ---------
$.getJSON('ajax/saveProductSession.php', {code:prodcode,pack:packinginfo[1],qty:totalrequired,batch:allbatchids}, function(data) {
if (data.error == "1") {
alert(data.message);
} else {
/// !!!!!!!! !!!!!!!!!!!!!!! !!!!!!!!!!!!!!!
///
/// the loads the page1. but jquery doesnt take val() after this.
///tried multiple variations of this but to no effect.
///removed all options.. redirect to main.php.. reloadpage:false.. etc.
///Any other way to reload the page so that the dialog once open again can
///get the values from the page1 again.
$.mobile.changePage("#page1", { reloadPage: true , dataUrl : "page1", reverse : true, changeHash: true } );
}
});
//
// $.ajax({
// type: "POST",
// url: "ajax/saveProductSession.php",
// data: { code:prodcode,pack:packinginfo[1],qty:totalrequired,batch:allbatchids }
// }).done(function() {});
}
</script>
Ok ! I got it to work ! thanks anyway #Gajotres. Steps :
1a. Send out the variables from main.php through changePage :
var prodcode = $('#formproduct').val();
var prodstock = $('#prodstock').attr('data');
var prodqty = $('#qty').val();
var packing = $('#packing').find(":selected").val();
$.mobile.changePage('batch.php', {
role: 'dialog',
data: {'prodcode': prodcode,'prodstock': prodstock, 'prodqty' : prodqty , 'packing' : packing},
type: 'get'
});
2a. Moved the entire div id 'page3' to a new php page named 'batch.php' where I get the variables from php and set it to the html divs.
<?php
extract($_GET);
if (!$prodcode && !$prodstock && !$packing && !$prodqty) {
header('Location: '.DEF_SITEURL."main.php");
exit;
}
?>
<div data-role="page" id="batchpage" data-url="batch.php" data-close-btn="right">
<div data-role="header">
<h1>Batch Selection</h1>
</div>
<div data-role="content">
<div style="display:none;" id="batchprodcode" data="<?php echo $prodcode; ?>"></div>
<div style="display:none;" id="batchprodstock" data="<?php echo $prodstock; ?>"></div>
<div style="display:none;" id="batchpacking" data="<?php echo $packing; ?>"></div>
<div style="display:none;" id="batchqty" data="<?php echo $prodqty; ?>"></div>
<div style="overflow:auto;">
<table id="batchsel" style="border:1px;">
<thead>
<tr>
<th></th>
<th>Batch No</th>
<th>Exp Date</th>
<th>Brate</th>
<th>Srate</th>
<th>Packing</th>
<th>Stock</th>
<th>Supplier</th>
<th>ST%</th>
<th>Bill Date</th>
<th>Bill No</th>
<th>btax</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<div id="remainingdata">
<p1 id="changeable_requirements"></p1>
<button id="saveprod" onclick="addProduct(); return false;">Add Product</button>
</div>
</div>
</div>
3a. Then I just change the pageshow that i was using for page3 to the new div that is created on batch.php. The script still runs on main.php.
$( document ).on( "pageshow", "#batchpage", function() {
$('#batchsel tbody').empty();
var prodcode = $('#batchprodcode').attr('data');
var prodstock = $('#batchprodstock').attr('data');
var prodqty = $('#batchqty').attr('data');
var packing = $('#batchpacking').attr('data');
...
});

Resources