I am trying to make a registration form in laravel 5 and it gives me this error:
Whoops, looks like something went wrong.
1/1
TokenMismatchException in compiled.php line 2440:
This is my views/register.blade.php:
<form class="form-horizontal" action = "inregistrare_process" method = "POST">
.....
</form>
This is in my app/Register.php
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Register extends Eloquent {
protected $guarded = array();
protected $table = 'users';
public $timestamps = 'false' ;
public static function saveFormData($data)
{
DB::table('users')->insert($data);
}
}
This is my Controllers/RegisterController.php
<?php namespace App\Http\Controllers;
use App\Register;
class RegisterController extends Controller {
public function store()
{
Register::saveFormData(Input::except(array('_token')));
}
}
And this is in my routes.php
Route::get('inregistrare',function(){
return view('register');
});
Route::post('inregistrare_process', function()
{
$obj = new RegisterController() ;
return $obj->store();
});
Can someone help me make this work or give me another alternative on how to make the registration page work ?
First of all you need a hidden input type with csrf_token in form
insert below line after your form declaration
<input type="hidden" name="_token" value="{{ csrf_token() }}">
Do you have write permission for your session file. By default session is stored in /storage/framework/sessions/
check that you have write permission on that directory.
If you are using an Ajax request than add the tokenMatch() method to app/Http/Middleware/VerifyCsrfToken.php.
protected function tokensMatch($request)
{
$token = $request->ajax() ? $request->header('X-CSRF-Token') : $request->input('_token');
return $request->session()->token() == $token;
}
and add this in your js file
$.ajaxSetup(
{
headers:
{
'X-CSRF-Token': $('input[name="_token"]').val()
}
});
Related
I have create one custom object. Using a LWC component, I try to create one record but when try to save it from apex, only ID is getting printed not the Name.
I am not getting why only Id is getting printed not the name.
Could anybody please help me ? Would be Appreciable.
LWC Component
import { LightningElement, track, api } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import insertDe from '#salesforce/apex/insertEvent.insertDe';
import Detail_OBJECT from '#salesforce/schema/Detail__c';
export default class insertEvent extends LightningElement {
// #api childName;
#track conRecord = Detail_OBJECT;
handleChildNameChange(event) {
this.conRecord.childName = event.target.value;
}
createRec() {
insertDe({
de: this.conRecord
})
.then(result => {
// Clear the user enter values
this.conRecord = {};
// Show success messsage
this.dispatchEvent(new ShowToastEvent({
title: 'Success!!',
message: 'Contact Created Successfully!!',
variant: 'success'
}), );
})
.catch(error => {
this.error = error.message;
});
}
}
<template>
<lightning-card title="Create Contact Record">
<template if:true={conRecord}>
<div class="slds-m-around--xx-large">
<div class="container-fluid">
<div class="form-group">
<lightning-input
label="Child Name"
name="childName"
type="text"
value={conRecord.childName}
onchange={handleChildNameChange}
></lightning-input>
</div>
</div>
<br />
<lightning-button label="Submit" onclick={createRec} variant="brand"></lightning-button>
</div>
</template>
</lightning-card>
</template>
Apex code
public with sharing class insertEvent {
#AuraEnabled
public static void insertDe(Detail__c de) {
try {
insert de;
} catch (Exception e) {
System.debug('--->'+e);
}
}
}
If you're using an LWC component then I suggest to also use Lightning Data Service.
To answer your specific issue, after an insert DML, only the Id field is returned. If you need other fields, then you need to run a query. This is because trigger / workflow / process builder can change some field value.
My suggestion if you want insert record directly from LWC component, you should use Lightning Data Service. But you need to execute some custom code or insert record from apex method, then you should pass only the data LWC component and create object in apex method then insert it.
public static void insertDe(String name) {
Detail__c obj = new Detail__c();
obj.childName = name;
try {
insert obj;
} catch (Exception e) {
System.debug('--->'+e);
}
}
Only pass the name from lwc component according to your posting code.
// iam trying to load array with input and checking the input then save the data
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Slider{
public $ci;
public $ci2;
protected $CI;
function __construct() {
// reference to the CodeIgniter super object
$this->CI =& get_instance();
$this->ci =&get_instance();
$this->ci->load->model('Slider_Model');
$this->CI->load->library('form_validation');
}
//load array with input and checking the input then save the dataenter image description here
function AddSlide($Data){
$this->CI->load->library('form_validation');
$this->CI->form_validation->set_error_delimiters('<p style="color: red">', '</p>');
$this->CI->form_validation->set_rules($Data['Title'],$Data['Title'],'min_length[5]|max_length[20]');
$this->CI->form_validation->set_rules($Data['Description'],$Data['Description'],'min_length[10]|max_length[100]');
$this->CI->form_validation->set_rules($Data['Status'],$Data['Status'],'in_list[1,2]');
if ($this->CI->form_validation->run() == FALSE)
{
echo FALSE;
}
else
{
$this->ci->Slider_Model->AddNewSlid($Data);
}
}
}
please check that your form_validation library is loaded or not
You should need to change this condition
if ($this->CI->form_validation->run() === FALSE)
to this if ($this->CI->form_validation->run() == FALSE)
function AddSlide($Data)
{
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<p style="color: red">', '</p>');
$this->CI->form_validation->set_rules($Data['Title'],'sasass','min_length[5]|max_length[20]');
$this->CI->form_validation->set_rules($Data['decription'],$Data['decription'],'min_length[10]|max_length[100]');
$this->CI->form_validation->set_rules($Data['status'],$Data['status'],'in_list[1,2]');
if ($this->CI->form_validation->run() == FALSE)
{
echo FALSE;
}
else
{
$this->ci->Slider_Model->AddNewSlid($Data);
}
}
I would change my Return form
I create form with a loop inside my twig, and I would like to change the name and id fields
eg
<input type="text" id="foo_1" name="foo_1[title]" maxlength="255">
I want to add an index like I did for the id of the form {{loop.index}}
I might have to pass something to the constructor of my form, but I have not found anything that has helped me
For Now i do It:
My controller
foreach($fotos as $key => $foto){
$array_fotos[] = array(
"form" => $this->createForm(new \My\FotoBundle\Form\FotoType($key), $fotos[$key])->createView(),
);
}
In My FormType i do this
class FotoType extends AbstractType
{
protected $key;
public function __construct($chiave) {
$this->key = $chiave;
}
.....
public function getName()
{
return 'form_gestione_foto_'.$this->key;
}
}
I want the Security Component turned on.
BUT when you load a CakePHP app inside a Facebook tab, FB posts $_REQUEST['signed_request'] to my form - the problem with this is that the Security Component "reacts" to this "post" and gives me validation errors, black-hole, etc.
How do I go around this?
I could not find anything on the documentation to go around this problem.
What I wanted was to somehow run the Security Component "manually" so that it only "reacts" when I actually submit my form and not when Facebook posts the $_REQUEST['signed_request'] to my form.
UPDATE:
<?php
App::uses('CakeEmail', 'Network/Email');
class PagesController extends AppController {
public $helpers = array('Html','Form');
public $components = array('RequestHandler');
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('*');
$this->Security->validatePost = true;
$this->Security->csrfCheck = true;
$this->Security->unlockedFields[] = 'signed_request';
}
public function home() {
$this->loadModel('Memberx');
if($this->request->is('post') && isset($this->request->data['Memberx']['name'])) {
//...save here, etc. ...
}
}
FYI: I get a "black hole" error.
FINAL UPDATE (After #tigrang's answer):
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('*');
$this->set('hasLiked', false);
if(isset($this->request->data['signed_request'])){
$this->set('hasLiked', $this->hasLiked($this->request->data['signed_request']));
}
if(isset($this->request->data['Memberx']['signed_request'])) {
$this->set('hasLiked', $this->hasLiked($this->request->data['Memberx']['signed_request']));
}
/*
To go around Facebook's post $_REQUEST['signed_request'],
we unset the $_REQUEST['signed_request'] and disable the csrfCheck
ONLY after we have set the hasLiked view variable
*/
unset($this->request->data['signed_request']);
if (empty($this->request->data)) {
$this->Security->csrfCheck = false;
}
}
Then, I do something like below in my views:
<?php
if($hasLiked) {
?>
You have liked this page!
<?php
}
?>
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('*');
$this->_validateFbRequest();
}
protected function _valdiateFbRequest() {
if (!isset($this->request->data['signed_request'])) {
// not a valid request from fb
// throw exception or handle however you want
return;
}
$signedRequest = $this->request->data['signed_request'];
unset($this->request->data['signed_request']);
if (empty($this->request->data)) {
$this->Security->csrfCheck = false;
}
// validate the request
}
Zend's JSON-RPC server doesn't seem to like sessions, and I can't seem to attach a session even by passing Zend_Session::getId() in to my RPC method and revive it with Zend_Session::setId($session_id) as I might expect.
To illustrate what does NOT work:
<?php
$server = new Zend_Json_Server();
$server->setClass('MyRPC');
?>
<script>
$(document).ready(function() {
myrpc = jQuery.Zend.jsonrpc({
url : <?=json_encode($this->baseUrl('/ajax'))?>
, smd : <?=$server->getServiceMap()?>
, async : true
});
myrpc.getIdentity(<?=json_encode(Zend_Session::getId())?>, {
success : function(data) {
alert(data.user_id);
}
});
});
// see: http://www.tanabi.com/projects/jsonrpc
</script>
and in my RPC class:
<?php
class MyRPC {
/**
* #param string
* #return array
*/
public function getIdentity($session_id) {
\Zend_Session::setId($session_id);
\Zend_Session::start();
// returns NULL
return \Zend_Auth::getInstance()->getIdentity();
}
}
It looks like this is unimplemented.