My api receives an json object posted from my React app. The object has two properties, one holding an array of objects and the other holds an id number. Because the first array cannot be validated by Symfony's form validation, I have created an custom restraint for it.
$data = json_decode($request->getContent(), true);
$custom_constraint = new Assert\blah blah;
$errors = $validator->validate($data['datas'], $custom_constraint );
if (count($errors) > 0 ) {
$errorsString = (string) $errors;
return new JsonResponse(
[
'validation failed' => $errorsString
]);
}
This validation works by itself, but I also want to add the validation for the id number
$errors = $validator->validate($data['id'], new Assert\Type('integer'));
Now I have two results in the $errors object, how do I combine them into one error object that output errors for any one of them?
You should use AssertCollection. It's demonstrate here: How to Validate Raw Values
Related
Find below the controller code:
public function domaincheck()
{
$response = file_get_contents('https://resellertest.enom.com/interface.asp?command=check&sld=unusualTVname&tld=tv&uid=resellid&pw=resellpw&responsetype=xml');
$data = simplexml_load_string($response);
$configdata = json_encode($data);
$final_data = json_decode($configdata,true);// Use true to get data in array rather than object
// dd($final_data);
$response1 = file_get_contents('http://resellertest.enom.com/interface.asp?command=GETNAMESUGGESTIONS&UID=resellid&PW=resellpw&SearchTerm=hand&MaxResults=5&ResponseType=XML');
$data1 = simplexml_load_string($response1);
$configdata1 = json_encode($data1);
$final_data1 = json_decode($configdata1,true);// Use true to get data in array rather than object
//dd($final_data1);
$response2 = file_get_contents('https://resellertest.enom.com/interface.asp?command=gettldlist&UID=resellid&PW=resellpw&responsetype=xml');
$data2 = simplexml_load_string($response2);
$configdata2 = json_encode($data2);
$final_data2 = json_decode($configdata2,true);
//dd($final_data2);
return view('clientlayout.main.test',array('final_data1' =>
$final_data1), array('final_data' => $final_data),
array('final_data2' => $final_data2));
}
Find the view code given below:
{{print_r($final_data)}}
<br><br><br>
{{print_r($final_data1)}}
<br>
{{print_r($final_data2)}}
Find the route code given below:
Route::get('/test','EnomController#domaincheck');
I need to return all the three arrays to the view page but When use the return view code giveb above I'm getting error as "Undefined variable: final_data2 " for the third array alone.If I declare only two array statements in the return view it works correctly. Suggest me a solution to solve this error.
in addition to #achraf answer if you dont want to use same variable names in your view as of your controller, you can pass data to your view like this. where final1, final2 and final3 will be the names of the variable in your view.
return view('clientlayout.main.test',['final1' =>$final_data ,'final2'=> $final_data1,'final3' => $final_data2]);
View take second param as array, your sending multiple arrays,
the solution is to create an array of arrays like this
return view('clientlayout.main.test',compact('final_data','final_data1','final_data2'));
I have a single input field (using select2 plugin) in a blog post form which allow user to insert post tags from existing tags in the table or create new ones and store them in the Tag table and also attach them to the post when they hit submit post button. I've managed to get this work by filtering the input with array_filter(), if the input is !is_numeric the input will first get stored in Tag table and then attach the id to the post.
The problem with this is that it's not working when the new tag from the input is in full numeric type, like 2017 tag. Is there a solution to get this working so the new tag is not limited to string only but also numeric type ? and if possible, I don't want to use any package for this.
The post store method :
public function store(PostsReq $request) {
$input = $request->all();
$post = Post::create($input);
//Handle the tags
$getTags = $request->input('tagspivot');
$oldTags = array_filter($getTags, 'is_numeric');
$newTags = array_filter($getTags, function($item) {
return !is_numeric($item);
});
foreach ($newTags as $newTag) {
if ($tag = Tag::create(['title' => strtolower(trim($newTag))])) {
$oldTags[] = $tag->id;
}
}
$post->tags()->attach($oldTags);
// Upload Image
if ($request->hasFile('image')) {
$input['image'] = $this->uploadImage($request, $post);
}
return redirect()->route('postindex')->with($this->postStoreSuccess);
}
Here is three lines of code would be more than enough:
$tag = Tag::firstOrCreate([
'title' => $request->input('tagspivot'),
]);
You don't need to check for !is_numeric. However, in your form don't use tag id as value. use the title.
On a Yii2 project, in a user's Edit Info form (inside a modal):
I'm currently figuring out which fields were changed using the jQuery .change() method, and I'm grabbing their value with jQuery's .val() method.
However, I want to do less with JavaScript and do more with Yii's framework.
I can see in the Yii debugger (after clicking into the AJAX POST request) that Yii is smart enough to know which fields were changed -- it's showing SQL queries that only UPDATE the fields that were changed.
What do I need to change in the controller of this action to have Yii include the name of the field changed -- including it's value -- in the AJAX response? (since my goal is to update the main view with the new values)
public function actionUpdateStudentInfo($id)
{
$model = \app\models\StudentSupportStudentInfo::findOne($id);
if ($model === null) {
throw new NotFoundHttpException('The requested page does not exist.');
}
$model->scenario = true ? "update-email" : "update-studentid";
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->renderAjax('_student_support_alert_success');
}
return $this->renderAjax("_edit_student_info",[
"model" => $model,
]);
}
I'm currently returning a static success view.
You can use $model->dirtyAttributes just after load the data to get a $attrib => $value pair array.
http://www.yiiframework.com/doc-2.0/yii-db-baseactiverecord.html#getDirtyAttributes()-detail (this docs says:)
Returns the attribute values that have been modified since they are loaded or saved most recently.
The comparison of new and old values is made for identical values using ===.
public array getDirtyAttributes ( $names = null )
(sorry for formatting, sent by mobile)
I am working under Symfony2 and Doctrine 2.1.6 and I try to setup a multi-step form.
Between each form page, I try to send the doctrine entity into $_SESSION.
According to that dotrine documentation it is possible and even the way to settle multipage forms:
http://docs.doctrine-project.org/en/2.1/cookbook/entities-in-session.html
But according to a lot of other post on stackoverflow, it is just not possible to send entities into session.
I have the following controller Action where i pretty much copied/ past the doctrine documentation.
public function indexAction(Request $request, $id)
{
$session = $request->getSession();
$em = $this->getDoctrine()->getEntityManager();
if (isset($_SESSION['propertyAdd'])) {
$property = $_SESSION['propertyAdd'];
$property = $em->merge($property);
}
else {
$property = new property;
}
$form = $this->createForm(new propertyType($this->getDoctrine()),$property);
// check form
if ($request->getMethod() == 'POST') {
$form->bindRequest($request);
if ($form->isValid()){
$em->detach($property);
$_SESSION['propertyAdd'] = $property;
// redirection to next step here
}
}
return $this->render('AddProperty:'.$id.'.html.twig', array(
'form' => $form->createView(),));
}
the line $_SESSION['propertyAdd'] = $property; give me the following error:
Fatal error: Uncaught exception 'ErrorException' with message 'Notice: Unknown: "id" returned as member variable from __sleep() but does not exist in Unknown line 0' in G:..\Symfony\vendor\symfony\src\Symfony\Component\HttpKernel\Debug\ErrorHandler.php on line 65
If I replace this line by using the Symfony2 helper
$session->set('propertyAdd', $property);
It throws the following exception:
Symfony\Bundle\FrameworkBundle\DataCollector\RequestDataCollector::serialize() must return a string or NULL
Is the doctrine example workable.
This doesn't answer your question, but why would you:
Create an entity
Serialize it
Put it in the session (I personally don't believe it's a good thing to transform an object to a string)
Get it from the session in the form's next step
Deserialize it
Add the new data to it
Serialize it
Put it again in the session
An so on...
Why don't you store the form data directly in the session, and create the entity after all the form's steps were complete?
If you're doing this to validate the entity, you can simply use forms (that aren't linked to an entity) and add the validation constraints to them.
I'm building an admin utility for adding a bulk of images to an app I'm working on. I also need to to log certain properties that are associated with the images and then store it all into the database.
So basically the script looks into a folder, compares the contents of the folder to records in the database. All of the info must be entered in order for the database record to be complete, hence the form validation.
The validation is working, when there are no values entered it prompts the entry of the missing fields. However it happens even when the fields ARE filled.
I'm doing something a bit funny which may be the reason.
Because I'm adding a bulk of images I'm creating the data within a for loop and adding the validation rules within the same for loop.
Here is the results:
http://s75151.gridserver.com/CI_staging/index.php/admin_panel/bulk_emo_update
Right now I have default test values in the form while testing validation. The submit button is way at the bottom. I'm printing POST variable for testing purposes.
Here is the code:
function bulk_emo_update() {
$img_folder_location = 'img/moodtracker/emos/';//set an image path
$emo_files = $this->mood_model->get_emo_images('*.{png,jpg,jpeg,gif}', $img_folder_location); //grab files from folder
$emo_records = $this->mood_model->get_all_emos(); //grab records from db
$i=1; //sets a counter to be referenced in the form
$temp_emo_info = array(); //temp vairable for holding emo data that will be sent to the form
//loop through all the files in the designated folder
foreach($emo_files as $file) {
$file_path = $img_folder_location.$file;//builds the path out of the flder location and the file name
//loops through all the database reocrds for the pupose of checking to see if the image file is preasent in the record
foreach($emo_records as $record) {
//compairs file paths, if they are the
if($record->picture_url != $file_path) {
//FORM VALIDATION STUFF:
$rules['segment_radio['.$i.']'] = "required";
$rules['emo_name_text_feild['.$i.']'] = "required";
//populating the temp array which will be used to construct the form
$temp_emo_info[$i]['path'] = $file_path;
$temp_emo_info[$i]['name'] = $file;
}
}
$i++;
}
//sets the reference to validation rules
$this->validation->set_rules($rules);
//checks to see if the form has all it's required fields
if ($this->validation->run() == FALSE) { //if validation fails:
print_r($_POST);
//prepairs the data array to pass into the view to build the form
$data['title'] = 'Bulk Emo Update';
$data['intro_text'] = 'fill out all fields below. hit submit when finished';
$data['emos_info'] = $temp_emo_info;
$this->load->view('admin_bulk_emo_update_view',$data);
} else { // if it succeeds:
//printing for test purposes
print_r($_POST);
$this->load->view('form_result');
}
}
I'm new to codeigniter and php in general so if anything looks outrageously weird please tell me, don't worry about my feelings I've got thick skin.
if ($this->validation->run() == FALSE)
if you are calling the run() method of the validation class every time the script is run, will it ever return TRUE and run the else? Maybe a different return?
I'm a little cornfused by what's going on. Generally, if I'm having a problem like this, I will figure out a way to force the result I'm looking for. e.g. in your code, I'd force that else to run... once I get it to run, break down what happened to make it run. Rudimentary, but it has served me well.
You use array of rules in
$this->form_validation->set_rules()
wrong.
If you want to pass the rules in array you must stick to the key names like described here http://codeigniter.com/user_guide/libraries/form_validation.html#validationrulesasarray
So instead of
$rules['input_name'] = "required"
try this:
array(
'field' => 'input_name',
'label' => 'Name that you output in error message',
'rules' => 'required'
)