I'm currently developing a system with Laravel framework. Though, I'm not very familiar with MVC architecture yet.
When I'm developing the system, I come across a problem which relates with this bootstrap modal that has a form in it. I'd like to put functions in it so that it could be submitted to the database.
I have followed several tutorials, but didn't come up with a solution because they're all using pages instead of modals.
So, here is the HTML of the modal:
<div class="modal hide fade" id="linkSettings">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3>Add New Link</h3>
</div>
<div class="modal-body">
<div class="control-group">
<label class="control-label" for="focusedInput">Add A Link:</label>
<div class="controls">
<textarea class="autogrow"></textarea>
</div>
</div>
</div>
<div class="modal-footer">
Close
Save changes
</div>
</div>
Here is the Javascript of the above modal:
$('.btn-settingLink').click(function(e){
e.preventDefault();
$('#linkSettings').modal('show');
});
Now, how do I put the function in the Controller so that whenever a user presses Save Changes button, it will store the value in <textarea> into the database? Is there anything to do with the Javascript code? and Do I need to use {{Form::open('main/addLink','POST')}} at the form to pass its values to the controller and model?
Basically, all I ever wanted was to have the CRUD functions by using modal.
First you need to create a form with a route....
<form method="post" action="{{URL::to('Link/addlink')}}>
Or like you showed above, with your Blade {{Form}} ...either way
Then your textarea needs an id and name
<textarea id="mytext" name="mytext"></textarea>
So your HTML becomes...
<form method="post" action="{{URL::to('Link/addlink')}}>
<div class="modal-body">
<div class="control-group">
<label class="control-label" for="focusedInput">Add A Link:</label>
<div class="controls">
<textarea id="mytext" name="mytext" class="autogrow"></textarea>
</div>
</div>
</div>
<div class="modal-footer">
Close
<input type="submit" id="submit" name="submit" class="btn btn-primary">Save changes</input>
</div>
</form>
Then in your Link controller...or wherever you're actually sending this form..no idea what your controllers are named :)
public function addlink(){
$input = Input::all();
//whatever validation you wanna do, with error handling etc...not gonna provide that, thats up to you
$yourmodel = New Model;
$yourmodel->text = $input['mytext'];
$yourmodel->save();
Return Redirect::back();
}
EDIT (for Ajax)
Add this script at the bottom of your page...
<script>
$(document).ready(function(){
$('input#submit').click(function(e){
e.preventDefault();
var text = $('#mytext').val();
var url = 'your url' //we were using Link/addlink in the other example
$.ajax({
type: "POST",
url: url,
data: { mytext: text },
success: function(){
//Probably add the code to close your modal box here if successful
$('#linkSettings').hide();
},
});
});
});
</script>
PS Completely untested....you will need some tweaking, plus the fact that your controller has the Redirect will probably make it not work since this will just be expecting an echoed Json string
But these are the nuts and bolts, and the foundation is there for you to continue on your own I would think...
Related
hello I am working on laravel project that am using relations between 2 tables i add a page that has many notes, so i am making a web page that allows me to add many pages and it shows the title of each page and inside every page, i can add many notes, I have problem in adding notes, am not sure if it is a problem in the route file or the blade file
i tried to add many variables in add note section in blade file but most of them gave me the msg of undefined even if am using the same variable i already have defined in the function inside the controller
showonepage.blade.php
<div class="row list-group-item-info page-title">
<div class="col-xs-12">
{{$id_show_single->title}}
</div>
</div>
#foreach($id_show_single->notes as $note )
<div class="row list-group-item">
<div class="col-xs-8">
{{$note->text}}
</div>
<div class="col-xs-4">
<button type="button" class="btn btn-danger pull-right">Delete</button>
<button type="button" class="btn btn-default pull-right">Edit</button>
</div>
</div>
#endforeach
<div class="row list-group-item">
<form method="POST" action="showdatapage/{{$id_page->id}}/notestore">
{{csrf_field()}}
<div class="input-group">
<input type="text" name="note_text" class="form-control" placeholder="Add Note . . .">
<span class="input-group-btn">
<button class="btn btn-default" type="submit">Add</button>
</span>
</div>
</form>
</div>
Route::get('showdatapage/{id_show_single}','PageController#ViewSinglePage');
Route::post('showdatapage/{id_page}/addnote','NoteController#PostGeneralNote');
class NoteController extends Controller
{
public function PostGeneralNote(Request $NoteReq, Page $id_page) {
$note = new note;
$note->text = $NoteReq->note_text;
$id_page->pages()->save($note);
return back();
}
}
Pagecontroller
public function ViewSinglePage(page $id_show_single) {
return view('showdatapdgone',compact('id_show_single'));
}
the final result when i type the id of page it gives me the page title and the note belongs to it but when i try to add new not it gave me not found page and i noticed in url for ex: http://127.0.0.1:8000/showdatapage/1 after adding new not it becomes http://127.0.0.1:8000/showdatapage/showdatapage/1 it doubled the url address
my project has 2 tables one for pages and one for notes , each page has title i connect each title in database with auto increment id the same id that i use to show single page, single page with single title from table "pages" can contain many notes, in notes table i have text column which is connect to auto increment id and there is a foreign key page_id i use to in making relation between 2 tables, the project is working good, except the add of notes in single page which has single title n single page id
i have a laravel page which contains a reserve form i redirect my user after selecting date now for number of people and counting the price i use vuejs but i want to pass the data to the laravel form and submit that from laravel with all the other data so here is a part of my code :
your final price
<input type="number" style=" background-color:#fff; border:none" v-model="finalPrice" disabled/>
and here is js part i cuted out code for better reading :
<script>
this.epic_price = this.sum_price + (this.total_price * this.sum_day)
this.$emit('input', this.epic_price)
</script>
although this form is not complete yet but i want to use it here in this page so i just paste it consider the form is not complete at all :
<form class="m-form m-form--fit m-form--label-align-right m-form--group-seperator-dashed"
action="/properties/savereserve/" method="post">
<div class="row">
#foreach($price as $key => $prices)
<div class="col-lg-2 text-center">
{{$date[$key]}}
<hr>
{{$prices}}
</div>
#endforeach
</div>
</form>
//exacly on the same page i use my vue component so they are on the same page
<reserve
:sum_price="{{$sumprice}}"
:sum_day="{{$sumday}}"
:base_price="{{$property->base_price}}"
:property_id="{{$property->id}}"
:user_id="{{Auth::user()->id}}"
></reserve>
I have a list of users on my web page echoed using a PHP loop. The names are links look like this.
{$user['username']}
So, when I click on each user, I am taken to user.php page.
user.php displays each user's information based on the query parameter $user['id'] in the URL. Using $_GET['id'] method.
So, that's the current situation I have.
What I now want to do is, display user's information in a Bootstrap Model
So, how could I get that query parameter into the Bootstrap model. And do the same PHP processes to get the same functionality ?
If you have google this you can get number of results related to it.
Here is code seems to be referred from one of this question passing-data-to-a-bootstrap-modal
HTML
<a data-toggle="modal" data-id="ISBN564541" title="Add this item" class="open-AddBookDialog btn btn-primary" href="#addBookDialog">test</a>
<div class="modal hide" id="addBookDialog">
<div class="modal-header">
<button class="close" data-dismiss="modal">×</button>
<h3>Modal header</h3>
</div>
<div class="modal-body">
<p>some content</p>
<input type="text" name="bookId" id="bookId" value=""/>
</div>
</div>
Javascript
$(document).ready(function () {
$(".open-AddBookDialog").click(function () {
$('#bookId').val($(this).data('id'));
$('#addBookDialog').modal('show');
});
});
I am trying to create a simple form that allows a user to upload a profile picture. To avoid having to deal with too much symfony code, I am using picEdit and I embedded the form directly to the appropriate twig template (which links to both picEdit .css and .js files, and jquery). This form is inside a boostrap modal dialog as seen below:
<div class="modal-dialog">
<div class="modal-content animated fadeIn">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<i class="fa fa-upload modal-icon"></i>
<h4 class="modal-title">Profile picture</h4>
<small>Use the options below to upload and edit your profile picture.</small>
</div>
<div class="modal-body" style="text-align: center">
<form action="upload.php" method="post" id="avatarUploadForm" name="avatarUploadForm" enctype="multipart/form-data">
<input type="file" name="avatarImage" id="avatarImage">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-white" data-dismiss="modal">Close</button>
<button type="submit" id="uploadButton" name="uploadButton" class="btn btn-primary">Upload Picture</button>
</form>
</div>
</div>
I also added the following java script function to the template:
<script type="text/javascript">
$(function() {
$('#avatarImage').picEdit();
});
</script>
The form action points to upload.php, shown below (in its simplistic form) and stored in web/upload.php:
<?php
if (isset($_POST['uploadButton'])){
$file = $_FILES['avatarImage']['name'];
move_uploaded_file($file,"/avatars/$file");
}
?>
When I hit the Upload Picture button, I get a success notification as seen below, but the file does not show up in the directory to where it is being sent, and I suspect the upload.php script never really gets triggered. Any suggestions on what I may be doing incorrectly?? *Disclaimer: I'm very new to php/symfony/java script
You are using the wrong key to move. Change upload.php to:
if (isset($_POST['uploadButton'])){
$file = $_FILES['avatarImage']['tmp_name'];
$fileName = $_FILES['avatarImage']['name'];
if(move_uploaded_file($file,"/assets/img/$fileName")){
header('Content-Type','application/json');
echo json_encode(array(
'status' => 'success'
));
}
else{
header('Content-Type','application/json');
echo json_encode(array(
'status' => 'failed'
));
}
}
http://php.net/manual/en/function.move-uploaded-file.php
You should also not rely on the file name of the uploaded file, its a potential for injection. Use some other naming schema or run the name through a scrubber.
Using this particular plugin im also not sure how you plan to tie the image back to the user entity. This plugin seems to only handle upload.
Make sure that you are not getting errors when uploading the file:
$('#image').picEdit({
formSubmitted: function(response){
console.log(response);
}
});
Symfony Approach
Use a form and controller. This will give you access to a lot more and save you a step in updating the users profile image.
We are going to make a few assumptions. First that only the logged in user will be changing their profile. Second that all directories have the proper permissions. And lastly that you are using annotations for routing
//ProfileController
...
/**
* #Route('/upload-profile-image', name="upload_profile_image")
* #Method({"POST"})
*/
public function uploadProfilePictureAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('UserBundle:User')->findOneById($this->getUser()->getId());
$form = $this->createFormBuilder($user)
->add('avatarImage','file')
->getForm();
$form->handleRequest($request);
if($form->isValid()){
$user->upload();
$em->flush();
return new JsonResponse(array(
'status'=>'success'
));
}
return new JsonResponse(array(
'status' => 'failed',
'message' => $form->getErrors(true)
));
}
Then make sure that you have your user entity setup with the proper functions described here: http://symfony.com/doc/current/cookbook/doctrine/file_uploads.html
Then just change your form to:
<form action="{{ path('upload_profile_image') }}" ...>
I've just started on using Symfony (version 2.2.1) and have ran into a little problem.
I have a plain HTML form (non-Symfony) in IntraController->indexAction and I want it to post to AuthController->loginAction. When I want to check in loginAction to see if the POST is getting passed to it, it just shows me an empty object.
My HTML form is as follows:
<form class="form-signin" action="auth/login" method="post">
<h2 class="form-signin-heading">Admin Access</h2>
<div class="input-prepend">
<span class="add-on" style="padding: 7px 9px;"><i class="icon-user"></i></span>
<input type="text" name="a_username" class="input-block-level" placeholder="Username...">
</div>
<div class="input-prepend">
<span class="add-on" style="padding: 7px 9px;"><i class="icon-lock"></i></span>
<input type="password" name="a_password" class="input-block-level" placeholder="Password...">
</div>
<button class="btn btn-success" name="post_auth" type="submit">Authenticate</button>
<a class="btn" href="../">Return to Homepage</a>
</form>
And this is how I'm trying to get the POST request in loginAction:
public function loginAction(){
return new Response(serialize($this->getRequest()->request->all()));
}
I've also tried getting a single POST item using:
return new Response(serialize($this->getRequest()->request->get('a_username')));
Sadly I'm getting an empty POST so I'm guessing that it gets emptied when it goes to auth/login. How could I preserve the POST data so it doesn't get emptied?
You are missing the CSRF key. You won't be able to use static forms like this unless you explicitly disable CSRF protection.