I want to use checkbox with symfony2. I want to update a field value in a table (0/1) dynamically using the checkbox value.
Here is my wrong code :
index.html.twig :
<div class="slider demo" id="slider-1">
{% if plate.share == true %}
<input type="checkbox" value="1" checked>
{% else %}
<input type="checkbox" value="1">
{% endif %}
</div>
<script type="text/javascript">
$("input[type='checkbox']").on('click', function(){
var checked = $(this).attr('checked');
if (checked) {
var value = $(this).val();
$.post("{{ path('plate_share', { 'id': plate.id }) }}", { value:value }, function(data){
if (data == 1) {
alert('the sharing state was changed!');
};
});
};
});
</script>
routing.yml
plate_share:
pattern: /{id}/share
defaults: { _controller: "WTLPlateBundle:Plate:share" }
PlateController.php:
public function shareAction($id)
{
if($_POST && isset($_POST['value'])) {
$link = mysql_connect('127.0.0.1', 'admin', 'wtlunchdbpass');
if (!$link) {
print(0);
}
mysql_select_db('wtlunch');
$value = mysql_real_escape_string($POST['value']);
$sql = "INSERT INTO table (value) VALUES ('$value')";
if (mysql_query($sql, $link)) {
print(1);
}
else {
print(0);
}
}
}
But this solution is wrong and not working.
Is it possible to create a form and submit it with only a checkbox?
Is there an idea? Thanks.
This for example the edit form action in the controller :
public function editAction($id)
{
$user = $this->container->get('security.context')->getToken()->getUser();
if (!is_object($user) || !$user instanceof UserInterface) {
throw new AccessDeniedException('This user does not have access to this section.');
}
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('WTLPlateBundle:Plate')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Plate entity.');
}
$editForm = $this->createEditForm($entity);
$deleteForm = $this->createDeleteForm($id);
return $this->render('WTLPlateBundle:Plate:edit.html.twig', array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}
Related
With this function I can correct delete single record:
` //delete order
public function delete_order($id)
{
$id = clean_number($id);
$order = $this->get_order($id);
if (!empty($order)) {
//delete order products
$order_products = $this->get_order_products($id);
if (!empty($order_products)) {
foreach ($order_products as $order_product) {
$this->db->where('id', $order_product->id);
$this->db->delete('order_products');
}
}
//delete invoice
$this->db->where('order_id', $order->id)->delete('invoices');
//delete order
$this->db->where('id', $id);
return $this->db->delete('orders');
}
return false;
}`
Now I try prepare function for delete multiple records.
In header table I add:
` <th scope="col" style="width: 25px;">
<div class="form-check">
<input class="form-check-input fs-15" type="checkbox" id="checkAll">
</div>
</th>`
and in foreach:
` <th scope="row">
<div class="form-check">
<input class="form-check-input fs-15" name="checkbox-table" type="checkbox" name="checkAll" value="<?php echo $item->id; ?>">
</div>
</th>`
Now I created action:
`<a class="dropdown-item" onclick="delete_selected_orders('<?php echo trans("confirm_products"); ?>');"><?php echo trans('delete'); ?></a>`
.js script
`<script>
//delete selected orders
function delete_selected_orders(message) {
swal({
text: message,
icon: "warning",
buttons: true,
buttons: [sweetalert_cancel, sweetalert_ok],
dangerMode: true,
}).then(function (willDelete) {
if (willDelete) {
var order_ids = [];
$("input[name='checkbox-table']:checked").each(function () {
order_ids.push(this.value);
});
var data = {
'order_ids': order_ids,
};
data[csfr_token_name] = $.cookie(csfr_cookie_name);
$.ajax({
type: "POST",
url: base_url + "order_admin_controller/delete_selected_orders",
data: data,
success: function (response) {
location.reload();
}
});
}
});
};
</script>`
order_admin_controller/delete_selected_orders
` /**
* Delete Selected Orders
*/
public function delete_selected_orders()
{
$order_ids = $this->input->post('order_ids', true);
$this->order_admin_model->delete_multi_orders($order_ids);
//reset cache
reset_cache_data_on_change();
}`
model
//delete multi order
public function delete_multi_orders($order_ids)
{
if (!empty($order_ids)) {
foreach ($order_ids as $id) {
$this->delete_order($id);
}
}
}`
When I check all and post delete multiple action then I see sweatalert to confirm delete, when I confirm I not see any error in console browser. But When I select multiple records and post then page refresh and orders not deleted.
I think function controller/model is correct. But im not sure with this in .js order_ids and in view table if I post order_ids correct.
From my console output, I can see that the success message has been displayed from the controller method that ajax called, but i have no idea why the value in db is not changing according to the value.
this is my html code
#foreach($system_functions as $function)
<input type="hidden" id="id" value="{{$function->id}}" />
#if($function->group_id == 1)
<tr>
<td>{!! $function->name !!}</td>
<td><input class="toggle_status" type="checkbox" #if($function->is_active) checked #endif id="is_active" name="is_active" data-on="启用" data-off="禁用" value="on" data-toggle="toggle"></td>
</tr>
#endif
#endforeach
my ajax in the same file
#section('script')
<script type="text/javascript">
$(document).ready(function() {
$('.toggle_status').change(function (e) {
e.preventDefault();
var is_active = 0
if ($(this).is(':checked')) {
is_active = 1;
}
$.ajax({
type: 'POST',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: '/admin/system-functions',
async: true,
data: {
is_active: is_active,
id: {{ $function->id }}
},
success: function (data) {
$.confirm({
title:'edit?',
content:'confirm to edit?',
buttons:{
confirm: {
text: 'edit',
btnClass: 'btn-danger',
action: function () {
}
},
cancel: {
text: 'cancel',
btnClass: 'btn-default',
action: function () {
}
}
}
});
}
});
});
});
</script>
#endsection
this is my method in controller
public function update(Request $request)
{
$id = Input::get('id');
$function=SystemFunction::where('id',$id)->first();
if($request->get('is_active')==='on'){
$is_active=1;
} else{
$is_active=0;
}
$function->update([
'is_active' => $is_active
]); return response()->json(['success' => 'successful']);
}
this is my route
Route::post('/system-functions', 'SystemFunctionController#update');
this is my modal class
class SystemFunction extends Model
{
protected $fillable=['name','group_id','is_active'];
static function isFunctionActive($function_name){
$function=SystemFunction::whereName($function_name)->first();
if(!$function){
return false;
}
return $function->is_active==true;
}
}
try this :
public function update(Request $request) {
$id = Input::get('id');
if($request->get('is_active')==='on'){
$is_active=1;
} else {
$is_active=0;
}
$function=SystemFunction::where('id',$id)->update([
'is_active' => $is_active
]);
return response()->json(['success' => 'successful']);
}
hopefully that can help
Try this, if DB doesn't get updated then you can track it through error messages:
try {
$id = Input::get('id');
$is_active = empty(Input::get('is_active')) ? 0 : 1;
$function = SystemFunction::findOrFail($id)->update(['is_active' => $is_active]);
if ($function) {
return response()->json(['success' => 'successful'], 200);
}
$error = ['errors' => ['message' => 'no data']];
return response()->json($error, 204);
} catch (Exceptoin $e) {
$error = ['errors' => ['message' => $e->getMessage()]];
return response()->json($error, 200);
}
I'm trying to create a dynamic 2-step form using Jquery where in "step 1", I want to submit the form data without refreshing my page so that I can hide my html division containing my form and show the other representing my step 2 using Jquery.
The problem is that I'm using a collection of forms in my controller action like this:
public function indexAction(Request $request)
{
$user = $this->getUser();
$em = $this->getDoctrine()->getManager();
$repository = $em->getRepository('ATPlatformBundle:NoteDeFrais');
$form = $this->get('form.factory')->createBuilder(FormType::class)
->add('ndf', CollectionType::class,array(
'entry_type' => NoteDeFraisType::class,
'label' => false,
'allow_add' => true,
'allow_delete' => true,
))
->getForm();
And I'm getting the forms data submitted from like this:
if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()
&& isset($_POST['next_button'])) {
$notesDeFrais = $form['ndf']->getData();
foreach ($notesDeFrais as $ndf) {
$ndf->setUser($user);
$em->persist($ndf);
}
$em->flush();
}
elseif (isset($_POST['validate_button'])) {
foreach ($listNdf as $ndf) {
$ndf->setSubmitted(true);
}
$em->flush();
}
So what I wanted to know is how to send my data via an ajax request and how to get them from my action. So far I tried to proceed like this but it (logically) doesn't work.
$("div#bloc_validation").css("display", "none");
$("#next_button").click(function(){
$(".form_ndf").each(function(){
$.post("{{ path('platform_homepage') }}",
{ndf: $(this).serialize()}, //My issue is here
function(){
alert('SUCCESS!');
}
);
});
$("div#form_bloc ").css("display", "none");
$("div#bloc_validation").css("display", "block");
});
Do you have any ideas ? Thanks in advance
The most basic approach is this:
add a javascripts block in your twig file with the content as below.
Change appbundle_blog in the first line inside the .ready() function in the name of your form. (Inspect your html to find it).
{% extends 'base.html.twig' %}
{% block body %}
{{ form_start(edit_form) }}
{{ form_widget(edit_form) }}
<input type="submit" value="Save Changes" />
{{ form_end(edit_form) }}
{% endblock %}
{% block javascripts %}
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous">
</script>
<script>
$(document).ready( function() {
var form = $('form[name=appbundle_blog]');
form.submit( function(e) {
e.preventDefault();
$.ajax( {
type: "POST",
url: form.attr( 'action' ),
data: form.serialize(),
success: function( response ) {
console.log( response );
}
});
});
});
</script>
{% endblock %}
If the form has been submitted you have to answer to an AJAX request. Therefore you could render another template..
/**
* Displays a form to edit an existing blog entity.
*
* #Route("/{id}/edit", name="blog_edit")
* #Method({"GET", "POST"})
*/
public function editAction(Request $request, Blog $blog)
{
$editForm = $this->createForm('AppBundle\Form\BlogType', $blog);
$editForm->handleRequest($request);
if ($editForm->isSubmitted() && $editForm->isValid()) {
$this->getDoctrine()->getManager()->flush();
/* render some new content */
return $this->render('blog/ajax.html.twig', array(
'blog' => $blog,
));
}
return $this->render('blog/edit.html.twig', array(
'blog' => $blog,
'edit_form' => $editForm->createView(),
));
Or answer in JSON:
use Symfony\Component\HttpFoundation\JsonResponse;
/**
* Displays a form to edit an existing blog entity.
*
* #Route("/{id}/edit", name="blog_edit")
* #Method({"GET", "POST"})
*/
public function editAction(Request $request, Blog $blog)
{
$editForm = $this->createForm('AppBundle\Form\BlogType', $blog);
$editForm->handleRequest($request);
if ($editForm->isSubmitted() && $editForm->isValid()) {
$this->getDoctrine()->getManager()->flush();
return new JsonResponse(array(
'status' => 'success',
// ...
));
}
return $this->render('blog/edit.html.twig', array(
'blog' => $blog,
'edit_form' => $editForm->createView(),
));
}
If you want you can even test if the request is an AJAX request or not:
if($request->isXmlHttpRequest()) {
// yes it is AJAX
}
I have my category page. I need when i click Create category button it add new category. But when I click on the submit button nothing happend and it shows no error message. Where the problem is? Please Help
My Category blade template is
#extends('layouts.admin-master')
#section('styles')
<link rel="stylesheet" type="text/css" href="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
{!! Html::style('src/css/categories.css') !!}
#endsection
#section('content')
<div class="container">
<section id="category-admin">
<form action="" method="post">
<div class="input-group">
<label for="Category">Category Name</label>
<input type="text" name="name" id="name">
<button type="submit" class="btn">Create Category</button>
</div>
</form>
</section>
<section class="list">
#foreach($categories as $category)
<article>
<div class="category-info" data-id="{{ $category->id }}">
<h3>{{ $category->name }}</h3>
</div>
<div class="edit">
<nav>
<ul>
<li class="category-edit"><input type="text" name=""></li>
<li>Edit</li>
<li>Delete</li>
</ul>
</nav>
</div>
</article>
#endforeach
</section>
#if($categories->lastPage() > 1)
<section class="pagination">
#if($categories->currentPage() !== 1)
<i class="fa fa-caret-left"></i>
#endif
#if($categories->currentPage() !== $categories->lastPage())
<i class="fa fa-caret-right"></i>
#endif
</section>
#endif
</div>
#endsection
#section('scripts')
<script type="text/javascript">
var token = "{{ Session::token() }}";
</script>
{!! Html::script('src/js/categories.js') !!}
#endsection
My categories.js file is
var docReady = setInterval(function() {
if(document.readyState !== "complete") {
return;
}
clearInterval(docReady);
document.getElementsByClassName('btn')[0].addEventListener('click',createNewCategory);
}, 100);
function createNewCategory(event) {
event.preventDefault();
var name = event.target.previousElementsSibling.value;
if(name.length === 0) {
alert("Please create A valid Category");
return;
}
ajax("POST", "/admin/blog/category/create", "name=" + name, newCategoryCreated, [name]);
}
function newCategoryCreated(params, success, responseObj) {
location.reload();
}
function ajax(method, url, params, callback, callbackParams) {
var http;
if(window.XMLHttpRequest) {
http = new XMLHttpRequest();
} else {
http = new ActiveXObject("Microsoft.XMLHTTP");
}
http.onreadystatechange = function() {
if (http.readyState == XMLHttpRequest.DONE) {
if (http.status == 200) {
var obj = JSON.parse(http.responseText);
callback(callbackParams, true, obj);
} else if (http.status == 400) {
alert("Category could not be saved. Please Try Again");
callback(callbackParams, false);
} else {
var obj = JSON.parse(http.responseText);
if (obj.message) {
alert(obj.message);
} else {
alert("please Check the name");
}
}
}
}
http.open(method, baseUrl + url, true);
http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
http.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
http.send(params + "&_token=" + token);
}
my route file is
Route::get('/blog/categories', [
'uses' => 'CategoryController#getCategoryIndex',
'as' => 'admin.blog.categories'
]);
Route::post('/blog/category/create', [
'uses' => 'CategoryController#postCreateCategory',
'as' => 'admin.blog.category.create'
]);
And my Category controller is
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Category;
use Illuminate\Support\Facades\Response;
class CategoryController extends Controller
{
public function getCategoryIndex() {
$categories = Category::orderBy('created_at','desc')->paginate(5);
return view('admin.blog.categories',['categories' => $categories]);
}
public function postCreateCategory(Request $request) {
$this->validate($request, [
'name' => 'required|unique:categories'
]);
$category = new Category();
$category->name = $request['name'];
if($category->save()) {
return Response::json(['message' => 'Category Created'], 200);
}
return Response::json(['message' => 'Error during Creation'], 404);
}
}
Send the token either in the headers or as a parameter to the server. More information here:
https://laravel.com/docs/5.2/routing#csrf-protection
Ok, so I'm stuck again. I'm doing an todo-list application, using Laravel and Angular. I can fetch data from the database via the Laravel- and Angular controllers but when I try do write data, I can't get it working.
So I have a form, whing uses ng-submit to post the data. When I - in the Angular controller - log the data to the console, the data from the form is correct. But when I try to pass it on to the Laravel Controller, I get stuck.
I can't find out whats wrong and browing the web for answers hasn't helped me.
Laravel routes:
<?php
Route::get('/', function () {
return view('index');
});
Route::get('/notes', 'NoteController#index');
Route::delete('/notes', 'NoteController#destroy');
Route::post('/notes', 'NoteController#store');
//Route::post('/notes', 'NoteController#update');
Route::get('/projects', 'ProjectController#index');
Route::get('/users', 'UserController#index');
Route::group(['middleware' => ['web']], function () {
//
});
?>
Laravel controllers:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Note;
use App\User;
use App\Project;
use Input;
use Response;
use Redirect;
class NoteController extends Controller
{
public function index()
{
try {
$statusCode = 200;
$notes = Note::where('removed', 0)->get()->toArray();
$response = [];
foreach ($notes as $note) {
$user = User::find($note['user_id']);
$project = Project::find($note['project_id']);
$this_row = array(
'id' => $note['id'],
'user' => $user['uname'],
'project' => $project['pname'],
'content' => $note['content'],
'completed' => $note['completed'],
'removed' => $note['removed'],
'created' => $note['time_created'],
'deadline' => $note['time_deadline']
);
$response[] = $this_row;
}
} catch (Exception $e) {
$statusCode = 400;
} finally {
return Response::json($response, $statusCode);
}
}
public function store()
{
$note = Input::json()->get()->toArray();
var_dump($note);
/*
$note->user_id = $note['user'];
$note->project_id = $note['project'];
$note->content = $note['content'];
$note->time_deadline = $note['deadline'];
$note->save();*/
}
}
class ProjectController extends Controller
{
public function index()
{
try {
$statusCode = 200;
$projects = Project::orderBy('pname', 'asc')->get()->toArray();
$response = [];
foreach ($projects as $project) {
$this_row = array(
'id' => $project['id'],
'name' => $project['pname'],
);
$response[] = $this_row;
}
} catch (Exception $e) {
$statusCode = 400;
} finally {
return Response::json($response, $statusCode);
}
}
}
class UserController extends Controller
{
public function index()
{
try {
$statusCode = 200;
$users = User::orderBy('uname', 'asc')->get()->toArray();
$response = [];
foreach ($users as $user) {
$this_row = array(
'id' => $user['id'],
'name' => $user['uname'],
);
$response[] = $this_row;
}
} catch (Exception $e) {
$statusCode = 400;
} finally {
return Response::json($response, $statusCode);
}
}
}
Angular controller:
angular.module('todoApp', []).controller('MainController', function($scope, $http) {
var thisApp = this;
$http({method : 'GET', url : 'http://localhost:8000/notes'})
.then (function(response) {
thisApp.todos = response.data;
}, function() {
alert("Error getting todo notes");
});
$http({method : 'GET',url : 'http://localhost:8000/users'})
.then(function(response) {
thisApp.users = response.data;
}, function() {
alert("Error getting users");
});
$http({method : 'GET', url : 'http://localhost:8000/projects'})
.then(function(response) {
thisApp.projects = response.data;
}, function() {
alert("Error getting projects");
});
thisApp.addTodo = function(note) {
console.log($scope.note);
$http({
method : 'POST',
url : 'http://localhost:8000/notes',
data : $.param($scope.note),
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
});
};
});
HTML:
<!doctype html>
<html ng-app="todoApp">
<head>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="/js/MainController.js"></script>
</head>
<body ng-controller="MainController as myControl">
<h2>Todo</h2>
<div>
<table>
<tr>
<th>Note:</th>
<th>Author:</th>
<th>Project:</th>
<th>Created:</th>
<th>Deadline:</th>
</tr>
<tr ng-repeat="todo in myControl.todos">
<td> {{ todo.content }} </td>
<td> {{ todo.user }} </td>
<td> {{ todo.project }} </td>
<td> {{ todo.created }} </td>
<td> {{ todo.deadline }} </td>
<td><button>Update</button></td>
<td><button>Delete</button></td>
</tr>
</table>
</div>
<h2>Add new:</h2>
<div>
<form ng-submit="myControl.addTodo()">
User:<br/>
<select ng-model="note.user">
<option ng-repeat="user in myControl.users" value="{{ user.id }}">{{ user.name }}</option>
</select><br/>
Project:<br/>
<select ng-model="note.project">
<option ng-repeat="project in myControl.projects" value="{{ project.id }}">{{ project.name }}</option>
</select><br/>
Note:<br/>
<textarea rows="5" cols="30" ng-model="note.content"></textarea><br/>
Deadline (format YYYY-MM-DD HH:MM):<br/>
<input type="text" ng-model="note.deadline" /><br/>
<input type="submit" value="Add" />
</form>
</div>
</body>
</html>
The result can be seen in this image: http://imgur.com/60hIzSb
I have no idea what I'm doing wrong. I guess my problem is in the Angular controller in the addTodo function, but I really don't know. Any suggestions?
I also wonder if anyone knows if I have to do anything else than change method : 'POST' to method : 'PUT' if I want to use the PUT method for creating new notes?
I feel like it has something to do with this:
$note = Input::json()->get()->toArray();
var_dump($note);
In angular you are sending form encoded data not json. And I believe Laravel automatically decodes received json anyway, so this should work:
$note = Input::all();
var_dump($note);
If it is the CSRF token then inject the CSRF TOKEN to your view
angular.module("todoApp").constant("CSRF_TOKEN", '{!! csrf_token() !!}');
and to your addTodo function in the headers pass the token....
thisApp.addTodo = function(note) {
console.log($scope.note);
$http({
method : 'POST',
url : 'http://localhost:8000/notes',
data : $.param($scope.note),
headers : {'Content-Type': 'application/x-www-form-urlencoded',
'x-csrf-token': CSRF_TOKEN}
});