I'm working with Symfony 2 and I need to insert some data in a MySQL table. I know how to do it using a form:
$m=new table();
$form=$this->container->get('form.factory')->create(new tableType(),$m);
$request=$this->getRequest();
if($request->getMethod()=='POST')
{
$form->bind($request);
if ($form->isValid())
{
$rm=$this->container->get('doctrine')->getEntityManager();
$rm->persist($m);
$rm->flush();
}
that works but I dont want to use a pre-defined form because I need complex control on my input. I need to generate the value with jQuery.
So how can I proceed to insert the values of my input into my table?
Generally you can pass the whole request to the action as following
use Symfony\Component\HttpFoundation\Request;
// <...>
public function fooAction(Request $request)
{
$foo = $request->query->get('foo', 'default_value_for_foo'); // get the foo param from request query string (GET params)
$bar = $request->query->get('bar', 'default_value_for_bar'); // get the bar param from request POST params
}
Also you might be interested in collection form types which can allow you to generate multiple rows or entities for form (not fixed)
That's actually easier than using forms :D
<?php
// ...
// fetch your params
$m = new table();
$m->setWhatever($request->get('whatever'));
// persist
$em = $this->get('doctrine.orm.entity_manager');
$em->persist($m);
Note:
use camel-case PHP-class names: e.g. Table, NiceTable
$form->bind is deprecated I think, use $form->handleRequest
anyway if you need to validate your input, I recommend using validators and forms anyway. Setting up a model and validate it is quite smart. You don't need to create the view createView() of it of course, but the validation component in Symfony is very mighty :).
Related
What do you use to get the checksum of a table in Laravel? Is there something already abstracted for this or you have to use raw commands?
You have to use raw commands, but it is pretty easy, just add this method to your model:
public static function checksum()
{
$tableName = with(new static)->getTable();
$query = sprintf('CHECKSUM TABLE %s', $tableName);
return \DB::select(\DB::raw($query))[0]->Checksum;
}
You can now call this method statically to get the checksum.
I have a model instance for which I set the attributes from a post request using $my_instance->fill($request_json) and after saving using $my_instance->save() the instance as a record in the database, I want to receive the saved object back with all its attributes using return response()->json($my_instance). Now this works fine as long as I provide all the attributes I set in the protected $fillable = [] on the model class inside the post request body. But when I want to send only part of the attributes in the post request, what happens is that inside tinker I see the skipped attributes are set to null. This is fine. But the problem is when I return using return response()->json($my_instance) I don't see the skipped attributes and I want them to be returned even with them being null in my databse. Is there a way to instruct laravel to do so?
A possible implementation to your question COULD be to:
Allow all possible fields that are getting nulled out to be fillable in your model.
Then, use a middleware with collections to do:
$form_stuff = $request->all();
$form_stuff = collect($form_stuff);
$things_you_want = $form_stuff->only('wanted_field_1','wanted_field_2');
$things_that_should_be_null = $form_stuff->only('nulled_field_1','nulled_field_2');
$keys = array_keys($thins_that_should_be_null);
$values = array_fill(0, count($keys), null);
$new_array_of_nulled_things = array_combine($keys, $values);
var_dump($things_you_want);
var_dump($new_array_of_nulled_things);
die();
WARNING: Since there was no code posted, this is just concept mostly and has not been tested so you will have to play with it to get it work the way you want.
I receive the following URL
/articles?difficulty=1,2
Inside the framework I want to receive an array from that - [1,2]. Is there any method in the framework to convert params like that into an array automatically? Can the framework do that? I can do like that explode(',', $params['difficulty']) - but I'm wondering whether this can be handled by the framework.
I don't want to pass params like that:
/articles?difficulty[]=1&difficulty[]=2
There is no helper in framework Request component for converting such values, it can be easily achieved with native PHP explode function. Use:
$array = explode(',', $string);
as you suggested.
But the wrapper of explode exists - \yii\helpers\StringHelper::explode(), it has additional options for trimming and skipping empty elements, you can use it too. But most of the times using regular explode should be enough.
try this
Use the Request class.
http://www.yiiframework.com/doc-2.0/yii-web-request.html
print_r(Yii::$app->request->get()); returns all get variables in an array. It's like doing print_r($_GET); in straight php.
If you want a specific $_GET variable you access it as follows:
Yii::$app->request->get('difficulty');
In your case it would be:
$success = Yii::$app->request->get('success');
$token = Yii::$app->request->get('token');
Then after that explode it with comma, so it will get converted into array.
$array = explode(',', $success );
I am using Play 2.2.x with Slick 2.0 (with MYSQL backend) to write a REST API. I have a User model with bunch of fields like age, name, gender etc. I want to create a route PATCH /users/:id which takes in partial user object (i.e. a subset of the fields of a full user model) in the body and updates the user's info. I am confused how I can achieve this:
How do I use PATCH verb in Play 2.2.x?
What is a generic way to parse the partial user object into an update query to execute in Slick 2.0?I am expecting to execute a single SQL statement e.g. update users set age=?, dob=? where id=?
Disclaimer: I haven't used Slick, so am just going by their documentation about Plain SQL Queries for this.
To answer your first question:
PATCH is just-another HTTP verb in your routes file, so for your example:
PATCH /users/:id controllers.UserController.patchById(id)
Your UserController could then be something like this:
val possibleUserFields = Seq("firstName", "middleName", "lastName", "age")
def patchById(id:String) = Action(parse.json) { request =>
def addClause(fieldName:String) = {
(request.body \ fieldName).asOpt[String].map { fieldValue =>
s"$fieldName=$fieldValue"
}
}
val clauses = possibleUserFields.flatMap ( addClause )
val updateStatement = "update users set " + clauses.mkString(",") + s" where id = $id"
// TODO: Actually make the Slick call, possibly using the 'sqlu' interpolator (see docs)
Ok(s"$updateStatement")
}
What this does:
Defines the list of JSON field names that might be present in the PATCH JSON
Defines an Action that will parse the incoming body as JSON
Iterates over all of the possible field names, testing whether they exist in the incoming JSON
If so, adds a clause of the form fieldname=<newValue> to a list
Builds an SQL update statement, comma-separating each of these clauses as required
I don't know if this is generic enough for you, there's probably a way to get the field names (i.e. the Slick column names) out of Slick, but like I said, I'm not even a Slick user, let alone an expert :-)
I am using Linq-to-SQL.
Currently I am binding gridview through linq which query written in business logic call. I have extract record through query in business logic class and I want to bind that particular data to gridview and return data.
How to return data which type is array?
The code is here:
CMSBusiness.DataClasses1DataContext db = new DataClasses1DataContext();
var cate =
from p in db.categoryTables
select new
{
categoryId=p.categoryId,
categoryName=p.categoryName,
categoryDesc=p.categoryDesc
};
How to return value and bind gridview?
Try gridView.DataSource = cate;, this should work.
We also recommend you to take a look at this article.