Apigility file upload multipart/form-data - multipartform-data

I've got a problem with the file upload, too.
I get the following JSON Response from API after submitting the form below. I'm using multipart/form-data.
{validation_messages: {file_attachment: []},…}
detail: "Failed Validation"
status: 422
title: "Unprocessable Entity"
type: "http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html"
validation_messages: {file_attachment: []}
file_attachment: []
Apigility Validators:
0 => array(
'required' => true,
'validators' => array(),
'filters' => array(
0 => array(
'name' => 'Zend\\Filter\\File\\RenameUpload',
'options' => array(
'target' => 'data/',
'randomize' => true,
),
),
),
'name' => 'file_attachment',
'type' => 'Zend\\InputFilter\\FileInput',
'allow_empty' => false,
'continue_if_empty' => false,
),
1 => array(
'required' => false,
'validators' => array(),
'filters' => array(),
'name' => 'title',
),
This is my Form:
<form id="avataruploadform" class="form-horizontal">
<fieldset>
<!-- Form Name -->
<legend>Form Name</legend>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="title">Title</label>
<div class="col-md-4">
<input id="title" name="title" type="text" placeholder="Some title for your sample file"
class="form-control input-md" required=""> <span
class="help-block">Sample field (title)</span>
</div>
</div>
<!-- File Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="file_attachment"> (PDF)</label>
<div class="col-md-4">
<input id="file_attachment" name="pdf" class="input-file" type="file">
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="submit">Submit</label>
<div class="col-md-4">
<button id="submit" name="submit" class="btn btn-primary">Submit AJAX upload with file</button>
</div>
</div>
</fieldset>
</form>
jQuery (AJAX Request):
<script type="application/javascript">
jQuery(document).ready(function() {
jQuery('#avataruploadform').submit(function(e) {
e.preventDefault();
// Note: if you observe 422 responses, check what's assembled into fd amd
// that it looks correct.
var fd = new FormData();
fd.append('file_attachment', $('#file_attachment')[0].files[0]);
jQuery.ajax({
url : 'http://localhost:8080/api/upload/avatar', // Specify the path to your API service
type : 'POST', // Assuming creation of an entity
contentType : false, // To force multipart/form-data
data : fd,
processData : false,
success : function(data) {
// Handle the response on success
// alert(JSON.stringify(data));
}
});
});
});
</script>
This is the response:
Remote Address:127.0.0.1:8080
Request URL:http://localhost:8080/api/upload/avatar
Request Method:POST
Status Code:422 Unprocessable Entity
Response Headers
view source
Access-Control-Allow-Origin:*
Access-Control-Expose-Headers:
Cache-Control:no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection:Keep-Alive
Content-Length:202
Content-Type:application/problem+json
Date:Sun, 13 Sep 2015 15:14:27 GMT
Expires:Thu, 19 Nov 1981 08:52:00 GMT
Keep-Alive:timeout=5, max=94
Pragma:no-cache
Server:Apache/2.2.22 (Ubuntu)
Set-Cookie:apigility_oauth2_doctrine_skeleton=lcgemufh1sag5ive1o5smh51e3; path=/
X-Powered-By:PHP/5.4.45-1+deb.sury.org~precise+1
Request Headers
view source
Accept:*/*
Accept-Encoding:gzip, deflate
Accept-Language:de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4
Connection:keep-alive
Content-Length:355592
Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryaXrmYN1JAB3ShBJa
Host:localhost:8080
Origin:http://localhost:3000
Referer:http://localhost:3000/inserate
User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36
X-FirePHP-Version:0.0.6
Request Payload
------WebKitFormBoundaryaXrmYN1JAB3ShBJa
Content-Disposition: form-data; name="title"
test
------WebKitFormBoundaryaXrmYN1JAB3ShBJa
Content-Disposition: form-data; name="file_attachment"; filename="_DSC2288.jpg"
Content-Type: image/jpeg
------WebKitFormBoundaryaXrmYN1JAB3ShBJa
Content-Disposition: form-data; name="submit"
------WebKitFormBoundaryaXrmYN1JAB3ShBJa--

Add enctype="multipart/form-data" to your form tag.
Ensure your "data/" folder is writable.
Also, check if your PHP error log has a warning message to the effect "Invalid boundary..."
I also had the same issue with the same example. Finally got it working with the POST and PUT methods but now I am having same issues with the PUT with X-HTTP-Method-Override. it just isn't working and looks like a bug in the apigility code.

Related

Not able to Fetch data from Front end to the Backend in order to update my mongoDB by using Express

My .hbs is this running on localhost:8001/docconfirm (using hadlebars/Template Engine)
<form id="login" method="GET" action="#">
<div class="form-group">
<label>Doctor's Email<span class="req">*</span> </label>
<input type="email" name="das" class="form-control" id="email" required data-validation-required-message="Please enter your email address." autocomplete="off">
<p class="help-block text-danger"></p>
</div>
<br>
<div>
<h5 style="color:rgba(0, 255, 255, 0.588);">Choose an Updation Field:</h5>
<select name="egyarah" class="form-control" id="Practice" >
<option value="First_Name">First-Name</option>
<option value="Last_Name">Last-Name</option>
<option value="Image">Image</option>
<option value="Email">Email</option>
<option value="Description">Job-Description</option>
</select>
</div>
<br>
<div class="form-group">
<label> Enter the detail to be updated<span class="req">*</span> </label>
<textarea name="baarah" class="form-control" style="color:rgb(255, 255, 255);" required data-validation-required-message="Please enter meet-up address."></textarea>
<p class="help-block text-danger"></p>
</div>
<div class="mrgn-30-top">
<button type="submit" class="btn btn-larger btn-block"/>
Update Profile
</button>
</div>
</form>
My Backend Express Code is:
app.put("/docconfirm/:das", (req, res) => {
console.log("heyyy");
Handles.findOneAndUpdate(
{Email:req.params.das},//trying to fetch the data got in URL and search it on my DB
{Description: String("mm")},// trying to update it after when the search is done
{new: true},//helps me printing the updated values
function(err,doc){
console.log(doc)// :( Not Working please help :)
})
});
--> I want to Fetch the data from the Front end and I want to update my database through the input given in Front End but it is not working somehow
my Schema is this - Using MongoDB(Mongoose)
const mongoose =require("mongoose");
mongoose.connect("mongodb://localhost:27017/Youraid",{useNewUrlParser: true,useUnifiedTopology:true}).then(()=>console.log("got connected from confirmdoc")).catch((err)=>console.log(err));
//creating schema for the database that has been connected by using the above code
const expSchema=new mongoose.Schema({
First_Name:{
type: String,
//required: true
},
Last_Name:{
type: String,
//required: true
},
Email:{
type: String,
unique: true,
//required: true
},
Image:{
type: String,
//required: true
},
Description:{
type: String,
//required: true
}
})
const Datass= new mongoose.model("docconfirm",expSchema);
module.exports = Datass;
Submitting your <form> produces a request like GET http://localhost:8001/docconfirm?das=x.y#z.com&egyarah=Email&baarah=meetup-address#. To process this on your server, you need something like
app.get("/docconfirm", function(req, res) { // get, not put, no :das parameter
Handles.findOneAndUpdate(
{Email:req.query.das}, // req.query, not req.params
{Description: String("mm")},
{new: true},
function(err, doc) {...});
});

Insert form information in Database. Magento 1.9

I have some form.
<form action="<?php echo Mage::getUrl('siteblocks/test/test', array('_current' => true,'_use_rewrite' => true))?>" method="post">
<h3>Enter your information</h3>
<p>
<label for="name" class="name" >Customer Name</label>
<input id="customer_name" name="customer_name" required="required" type="text"/>
</p>
<p>
<label for="phone" class="phone" >Customer Phone</label>
<input id="customer_phone" name="customer_phone" required="required" type="text"/>
</p>
<p>
<label for="calltime" class="ctime" >Call Time</label>
<input id="calltime" name="call_time" required="required" type="text"/>
</p>
</form>
Information comes from the form to the controller
class Test_Test_Controller extends Mage_Core_Controller_Front_Action {
public function testAction()
{
$this->getRequest()->getPost();
Mage::getModel('siteblocks/callEntity')->setData($this->getRequest()->getPost())
->save();
}
}
config.xml
<config>
<modules>
<Test_Test>
<version>0.1.0</version>
</Test_Test>
</modules>
<global>
<models>
<siteblocks>
<class>Test_Test_Model</class>
<resourceModel>siteblocks_resource</resourceModel>
</siteblocks>
<siteblocks_resource>
<class>Test_Test_Resourse</class>
<entities>
<block>
<table>fast_call</table>
</block>
</entities>
</siteblocks_resource>
</models>
<resources>
<siteblocks_setup>
<setup>
<module>Test_Test</module>
</setup>
</siteblocks_setup>
</resources>
<helpers>
<siteblocks>
<class>Test_Test_Helper</class>
</siteblocks>
</helpers>
</global>
<frontend>
<routers>
<siteblocks>
<use>standard</use>
<args>
<module>Test_Test</module>
<frontName>siteblocks</frontName>
</args>
</siteblocks>
</routers>
<translate>
<modules>
<Test_Test>
<files>
<defaul>Test_Test.scv</defaul>
</files>
</Test_Test>
</modules>
</translate>
<layout>
<updates>
<mymodule>
<file>test_catalog.xml</file>
</mymodule>
</updates>
</layout>
</frontend>
<admin>
<routers>
<adminhtml>
<args>
<modules>
<siteblocks before="Mage_Adminhtml">Test_Test_Adminhtml</siteblocks>
</modules>
</args>
</adminhtml>
</routers>
</admin>
<default>
<web>
<routers>
<siteblocks_callentity>
<area>frontend</area>
<class>Test_Test_Controller_Router</class>
</siteblocks_callentity>
</routers>
</web>
</default>
</config>
The problem is that data is not sent in base
<?php
$installer = $this;
$installer->startSetup();
$table = $installer->getConnection()->newTable($installer->getTable('fast_call'))
->addColumn('id', Varien_Db_Ddl_Table::TYPE_INTEGER, array(
'unsigned' => true,
'nullable' => false,
'primary' => true,
'identity' => true,
), 'id')
->addColumn('customer_name', Varien_Db_Ddl_Table::TYPE_VARCHAR, 255, array(
'nullable' => false,
'default' => '',
), 'customer_name')
->addColumn('customer_phone', Varien_Db_Ddl_Table::TYPE_VARCHAR, 255, array(
'nullable' => false,
'default' => '',
), 'customer_phone')
->addColumn('call_time', Varien_Db_Ddl_Table::TYPE_VARCHAR, 255, array(
'nullable' => true,
'default' => '',
), 'call_time')
->setComment('fast_call');
$installer->getConnection()->createTable($table);
$installer->endSetup();
When information is sent form the controller receives it and seemingly must enter it into the database. But this is not happening. Debug gave nothing. Maybe someone will find a mistake
In your controller, change setData to addData

Can we use angular js validation in symfony2 forms?

I am working on a registration form in symfony2 with angular js.
My doubt is can we do angular js validations in a symfony2 form?
because i cannot validate the form and also i dont know how to post form values to symfony controller..
please help..
I am stuck in project..
please check my registration.html.twig code..
<body ng-app="LoginApp">
<div id="register" class="animate form" ng-controller="RegisterController as registerCtrl">
{{ form_start(form, {'attr': {'name':'registerFrm', 'id':'registerFrmId','novalidate': '', 'ng-submit':'registerCtrl.registerFrm()'}}) }}
Your username
{{ form_row(form.username) }}
<span class="error" ng-show="submitted && registerFrm.adminuser[username].$error.required">Username is required!</span>
Your email
{{ form_row(form.email) }}
<span class="error" ng-show="submitted && registerFrm.adminuser[email].$invalid">Invalid email</span>
Your password
{{ form_row(form.plainPassword.first) }}
<span class="error" ng-show="submitted && registerFrm.adminuser[plainPassword][first].$error.required">Password is required!</span>
Please confirm your password
{{ form_row(form.plainPassword.second) }}
<span class="error" ng-show="submitted && registerFrm.adminuser[plainPassword][second].$error.required">Password is required!</span>
<p class="signin button">
<input type="submit" name="signup" ng-model="signup" ng-click="submitted=true" value="Sign up" />
</p>
{{ form_end(form) }}
</div>
<script>
var App = angular.module('LoginApp',[]);
App.controller('RegisterController', ['$scope',function($scope) {
}]);
</script>
</body>
My symfony form builder
$builder
->add('username', TextType::class , array(
'label' => false,
'attr' => array(
'ng-model' => 'formData.username',
'id' => 'usernamesignup',
'placeholder' => 'myusername690',
'required' => false)
))
->add('email', TextType::class , array(
'label' => false,
'attr' => array(
'ng-model' => 'formData.email',
'id' => 'emailsignup',
'placeholder' => 'mymail#mail.com',
'ng-pattern' => '/^([0-9a-zA-Z]([-\.\w]*[0-9a-zA-Z])*#([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$/',
'required' => false)
))
->add('plainPassword', RepeatedType::class, array(
'type' => PasswordType::class,
'first_options' => array(
'label' => false,
'attr' => array(
'ng-model' => 'formData.password',
'id' => 'passwordsignup',
'placeholder' => 'eg. X8df!90EO',
'required' => false)
),
'second_options' => array('label' => false,
'attr' => array(
'ng-model' => 'formData.confirm_password',
'id' => 'passwordsignup_confirm',
'placeholder' => 'eg. X8df!90EO',
'required' => false)
),
)
);
registration form image
Hey Dmitry Grachikov,
Please change your code
<span class="error" ng-show="submitted && registerFrm.adminuser[username].$error.required">Username is required!</span>
to
<span class="error" ng-show="submitted && registerFrm['adminuser[username]'].$error.required">Username is required!</span>
Your code having syntactic JS error.
If you want to reference a property named adminuser[username], you should do it like this:
registerFrm['adminuser[username]'].$error
registerFrm.adminuser[username] is incorrectly interpreted as (registerFrm.adminuser)[username]
The easiest ways there is to render your form in twig just to get html of a form with field names. Afterwards you have to use exactly the same field names in form submit request and symfony forms component will handle it.

AngularJS http action executes multiple foreign event

I made a simple function to handle update actions for user. A simple form that look like this
<div class="com-md-12 col-sm-12 no-pad no-margine" ng-controller="ProfileCtrl" ng-init="getProfile('{{$safeID}}')">
{!! Form::open(array('class' => 'form-horizontal signup-form', 'ng-submit' => 'updateProfile($event)')) !!}
<div class="form-group">
<div class="col-md-6 col-sm-6">
{!! Form::text('first_name', old('first_name'), array('class' => 'form-control', 'placeholder' => 'First Name*', 'ng-model' => 'uProfile.first_name')); !!}
{!! MessagerService::setInlineError($errors->first('first_name')) !!}
</div>
<div class="col-md-6 col-sm-6">
{!! Form::text('last_name', old('last_name'), array('class' => 'form-control', 'placeholder' => 'Last Name*', 'ng-model' => 'uProfile.last_name')); !!}
{!! MessagerService::setInlineError($errors->first('last_name')) !!}
</div>
</div>
<div class="form-group">
<div class="col-md-12 col-sm-12">
{!! Form::text('username', old('username'), array('class' => 'form-control', 'placeholder' => 'Screen Name*', 'ng-model' => 'uProfile.username')); !!}
{!! MessagerService::setInlineError($errors->first('username')) !!}
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-sm-6">
{!! Form::text('dob', old('dob'), array('class' => 'form-control', 'id' => 'dob', 'placeholder' => 'Date of Birth*', 'ng-model' => 'uProfile.dob')); !!}
{!! MessagerService::setInlineError($errors->first('dob')) !!}
</div>
<div class="col-md-6 col-sm-6">
{!! Form::select('gender', ['' => '------ Gender ------', 'male' => 'Male', 'female' => 'Female'], old('gender'),
array('class' => 'form-control', 'ng-model' => 'uProfile.gender')) !!}
{!! MessagerService::setInlineError($errors->first('gender')) !!}
</div>
</div>
<div class="form-group">
<div class="col-md-12 col-sm-12">
<div class="input-group">
<span class="input-group-addon" id="p_url_pretext">example.com/</span>
{!! Form::text('profile_url', old('profile_url'), array('class' => 'form-control', 'placeholder' => 'Profile URL*', 'ng-model' => 'uProfile.profile_url')); !!}
</div>
{!! MessagerService::setInlineError($errors->first('profile_url')) !!}
</div>
</div>
<div class="form-group">
<div class="col-md-12 col-sm-12">
<button type="submit" class="btn btn-default cbtn-login" style="float: right;">Save updates</button>
</div>
</div>
{!! Form::close() !!}
</div>
with angular script that look like this
$scope.updateProfile = function(event){
event.preventDefault();
$http({
method : 'POST',
url : svrid('www') + '/ws/profile/update',
data : $.param($scope.uProfile), // pass in data as strings
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
}).success(function(data) {
console.log(data);
}).error(function(data) {
console.log(data);
});
};
Everything worked as i expected but I have noticed 1 weird behavior. Why are there so many unrecognized requests before my final POST action is being executed?
I noticed that supposed my action route is http://www.example.com:8000/ws/profile/update it somehow keeps on calling http://www.example.com:8000/ws/profile with 3 different requests POST, GET, and DELETE before it finally reaches the intended request as shown in image below
Anyone have any idea what causes such behavior to happen or have I coded something wrong in anywhere that leads to such incident?
Update 1: Here is the Plunkr file. Noted that i could not re-simulate the error because the site is currently at localhost
Update 2: I have narrowed down that the ng-init="getProfile('{{$safeID}}') might have been causing this problem. I tried removing that line and give it a constant value and the errors do not appear. What's with such behavior?
I have found out the problem that causes such behavior. It is mainly because of the jQuery's $.param function. What really happens is the $.param operation will run through all properties of you object. Using $.param as the object will not automatically convert to a url encoded string (though I think it should).
So what I as a workaround to this problem is create a manual serialization function like such
function serializeData( data ) {
// If this is not an object, defer to native stringification.
if ( ! angular.isObject( data ) ) {
return( ( data == null ) ? "" : data.toString() );
}
var buffer = [];
// Serialize each key in the object.
for ( var name in data ) {
if ( ! data.hasOwnProperty( name ) ) {
continue;
}
var value = data[ name ];
buffer.push(
encodeURIComponent( name ) + "=" + encodeURIComponent( ( value == null ) ? "" : value )
);
}
// Serialize the buffer and clean it up for transportation.
var source = buffer.join( "&" ).replace( /%20/g, "+" );
return( source );
}
pass the form payload to the serialization function then append it into angular's #http
$http({
method : 'POST',
url : svrid('www') + '/ws/profile/update',
data : serializeData($scope.uProfile), // pass in data as strings
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
}).success(function(data) {
$scope.uError = null;
}).error(function(data) {
$scope.uError = data;
console.log(data);
});
and everything works like a charm.

Set the options for the Field of Type Radio button in Form Helper in Cakephp

I am using a Form helper in CakePHP. like
echo $form->input('field', array(
'type' => 'radio','legend'=>$r['Attribute']['label'],
// 'after' => '--after--',
// 'between' => '--between---',
'separator' => '--separator--',
'options' => array('1', '2')
));
which generates me as
<div class="input radio">
<fieldset>
<legend>Gender</legend>
<input type="hidden" value="" id="field_" name="data[field]"/>
<input type="radio" value="0" id="Field0" name="data[field]"/>
<label for="Field0">1</label>--separator--
<input type="radio" value="1" id="Field1" name="data[field]"/>
<label for="Field1">2</label>
</fieldset>
</div>
Is there any way to keep my options that i have received from my Database instead of 1,2
where i tried it with receving my options using
<?php foreach ($viewfields as $r): ?>
<script type="text/javascript">
jQuery.noConflict();
jQuery(document).ready(function($){
$("#"+<?=$r['Attribute']['id'];?>).each(function() {
type= "<?=$r['Attribute']['type'];?>";
if(type=="radio")
{
var ht = $.ajax({
type: "GET",
url: "http://localhost/FormBuilder/index.php/forms/viewChoices/"+attribute_id,
async: false
}).responseText;
var myObject = eval('(' + ht + ')');
var data = myObject;var j=0;
$.map(data.choices, function(i){ j++;
alert(i.choice);//which alerts as male and female correctly.
return i.choice;});
}
});//each
});
alert(i.choice); alerts the options correctly ..
How to keep these options in the array() of the Form Helper so that to get these options male and female instead of default 1,2
Please suggest me..
Place the options in a key => value array - as shown here : Cake Options
echo $form->input('field', array(
'type' => 'radio',
'legend' => $r['Attribute']['label'],
'separator' => '--separator--',
'options' => array('Male' => 'male', 'Female' => 'female')
));
See how you go.

Resources