Behaviors with forms in yii - php

I have a Yii behavior, that adds some custom fields with condition
_form.php
$form->attachbehavior('users', new DirectoriesBehavior);
// return part of form
echo $form->getDirectory(array('sysName' => 'users', 'useDefaultValue' => true));
// Other form parts (default for yii)
echo $form->labelEx($model, 'name');
DirectoriesBehavior::getDirectory() build HTML form part with <select> or <input> etc. fields.
But how can I send name/id of the form to my behavior?
After rendering it looks like
<form method="" id="myForm">
<!--BEHAVIORS CONTENT-->
<select>
<option value="UserId">UserName</option>
</select>
<!--Default fields of form-->
<input type="text" name="myForm[exampleField]" />
</form>
And my behaviors content should to looks like
<select name="myForm[users]">
<option>etc</option>
</select>

I resolve this problem:
We can sent $model in _form.php
$form->getDirectory(array('model' => $model));
in DirectoriesBehavior.php
public function getDirectory(array $data)
{
$this->inputName = get_class($data['model']);
}
Also ( for scripts that will be work with this form we can to send ID of the form )
_form.php
$form->id;

Related

Laravel FormRequest validation rules not working as expected

In my Laravel app, I am creating a dynamic search functionality using Eloquent and I have a customer search form which looks like this:
customers.search.blade.php Contrived Example
<form method="post" action="{{ route('customers.search') }}">
#csrf
<div class="form-group">
<label for="first_name" class="font-weight-bold">First Name</label>
<div class="input-group">
<div class="input-group-prepend">
<select name="first_name['operator']" class="custom-select">
<option value="%">%</option>
<option value="=">=</option>
<option value="!=">!=</option>
</select>
</div>
<input id="first_name" name="first_name['query']" type="text" class="form-control">
</div>
</div>
</form>
I have a SearchCustomerRequest (FormRequest) class which builds out the validation rules dynamically. I've dumped it, so you can see what the generated rules looks like:
In my CustomersController under search method, I did the following to see what the validated request array looks like:
class CustomersController extends Controller
{
// ...
public function search(SearchCustomerRequest $searchCustomerRequest)
{
dd($searchCustomerRequest->validated());
}
// ...
}
In order to test this, in the search form, I've selected the firstname['operator'] to % and typed the first_name['query'] to test and submitted the form.
I got the following response (i.e. empty array):
[]
So, I dumped the whole request object $searchCustomerRequest to see what was in the parameter bag and this is what I see:
As you can see, my request is valid and my rules also looks correct, yet the validation doesn't seem to be working as expected.
Any ideas what might be wrong here?
In your ParameterBag, the first_name properties operator and query are enclosed in single quotes. In your HTML, the name attribute should exclude the single quotes. Ex: name="first_name[query]"

Codeigniter Form post controller advice

would like some advice/help on how to connect form controller to post form method in my CI site. I want to data submitted from one viewer to another. Thank you for the help!!
Here is the controller Im using (Form.php), took if from another site:
Form.php
<?php
class Form extends CI_Controller {
public function __construct() {
parent::__construct();
}
// Show form in view page i.e view_page.php
public function form_show() {
$this->load->view("addEdit");
}
// When user submit data on view page, Then this function store data in array.
public function data_submitted() {
$data = array(
'file_name' => $this->input->post('file'),
'title' => $this->input->post('title')
);
// Show submitted data on view page again.
$this->load->view("profile", $data);
}
}
?>
Its to connect to this code:
addEdit.php
<form method="post" action="postAction.php" enctype="multipart/form-data">
<div class="form-group">
<label>Image</label>
<?php if(!empty($imgData['file_name'])){ ?>
<img src="uploads/images/<?php echo $imgData['file_name']; ?>">
<?php } ?>
<input type="file" name="image" class="form-control" >
</div>
<div class="form-group">
<label>Title</label>
<input type="text" name="title" class="form-control" placeholder="Enter title" value="<?php echo !empty($imgData['title'])?$imgData['title']:''; ?>" >
</div>
Back
<input type="hidden" name="id" value="<?php echo !empty($imgData['id'])?$imgData['id']:''; ?>">
<input type="submit" name="imgSubmit" class="btn btn-success" value="SUBMIT">
</form>
When I first tried to make it work I got this error:
404 Page Not Found
The page you requested was not found.
http://culturedkink.com/index.php/register/postAction.php(the url)
postAction.php is the form Im trying to get the data to work from
The end result is to have info submitted from addEdit.php be seen on profile.php with the help of postAction.php
make routes for it first.
config/routes.php
$route['add'] = 'Controller_name/data_submitted';
$route['edit/(:any)'] = 'Controller_name/data_submitted/$1';
where is your add/edit button put this there
for add
Add New
for edit button
$row['id'] is an example i m giving. you can get data by name and id..whatever you want.
Update
//controller
public function data_submitted($id=0) {
$data=array();
$data['dataDetails']=$this->get_profile_data_by_id($id);
$data['view'] = 'folder_name/addEdit';
if ($id > 0) {
$profileArray = [
'file_name' => $this->input->post('file'),
'title' => $this->input->post('title')
];
if ($this->User_model->editById($id, $profileArray)) {
$id = $id;
}
}
else{
$profileArray = [
'file_name' => $this->input->post('file'),
'title' => $this->input->post('title')
];
if ($this->User_model->add($id, $profileArray)) {
$id = $id;
}
}
$this->load->view("profile", $data);
}
form view page
<?php echo isset($dataDetails) ? "Update" : "Add"; ?>
First check your form method and action. Your action does not exist. First check how CI works with form. The action should have a method declared in a controller. The url looks like this,
When you submit the form the data will be submitted in this method. Whatever you need to do with this form data you can do that in this method.

Validate Laravel form in real time using laravel-jsvalidation

I am using laravel-jsvalidation to validate forms on client side but the plugin validate the form after submit.
How can I change it to a real-time validation while user is inputting data?
Calling plugin:
<script type="text/javascript" src="{{ asset('vendor/jsvalidation/js/jsvalidation.js')}}"></script>
{!! $validator->selector('#review-form') !!}
Form:
<form action="{{action('GoToTheController')}}" method="POST" id="review-form">
<div class="form-group"><input type="text" class="fullName" name="fullName">
</div>
</form>
Controller:
$validator = JsValidator::make( ['fullName'=> 'required']);
return view('create')->with('validator', $validator);
In bootstrap.php under the plugin(laravel-jsvalidation) folder I added these lines so it works fine by clicking on input elements.
onfocusout: function (element) {
if (!this.checkable(element)) {
this.element(element);
}
}
or you can make a copy of the file, add the above lines into it and use it.

Codeigniter: insert form_input into sql table

I'm trying to create a system of posts and custom fields. Ex: I create the post type "Product" and then I associate it some fields: "Name", "Image", "Price"...
When I create one of this fields I save into my db an input field, for example for Name I will insert something like this:
$data = array(
'name' => $field_key,
'id' => $field_key,
'class' => 'form-control '.$type->type_key,
'type' => $type->type_key,
'data-input-type' => $type->type_key
);
return form_input($data);
Then when I go to create my first post "Product" I want to populate a form with my custom fields.
<form method="post" action="<?php echo site_url('admin/posts/manage').'/'.$post_id; ?>">
<?php
foreach ($post_fields as $field) {
?>
<div class="form-group">
<label>
<?php
echo $field->name;
?>
</label>
<?php
// Here the field input
echo $field->meta_value;
?>
</div>
<?php
}
?>
<?php if(isset($post)){ echo $post->name;}else{echo set_value('name');} ?>
<div class="form-group">
<input type="submit" value="Save" name="save">
</div>
</form>
There's no problem since I have to create a new one. But when I have to edit my post I don't know how to load field's value for that single post, because in my form_input $data I can't put something like
$value = (isset($post)) ? $post->name : set_value($field_key);
and in the $data array
'value' => $value
Somebody have an idea on what I can do?
Thank you and sorry for my elementary english.
SOLVED. I create a model which load the correct input type. I pass post values by the controller to this model to populate input values correctly, if the action required is "edit".

Symfony2 : Two forms in a same page

I've got two forms in a same page.
My problem is when I tried to submit a form, it's like it tried to submit the second form below in the page as well.
As follow, you can find my 2 forms :
public function createSuiviForm() {
return $form = $this->createFormBuilder(null)
->add('numero', 'text', array('label' => 'N° : ',
'constraints' => array(
new Assert\NotBlank(array('message' => 'XXXX')),
new Assert\Length(array('min' => 19, 'max' => 19, 'exactMessage' => 'XXX {{ limit }} XXX')))))
->add('xxxx', 'submit')
->getForm();
}
public function createModificationForm() {
return $form = $this->createFormBuilder(null)
->add('modification', 'submit', array('label' => 'XXXXXXXXXXXXXXXXXXXX'))
->getForm();
}
My second form as only a submit button.
I passed them to my render and display them by using :
<div class="well">
<form method="post" action='' {{form_enctype(form)}} >
{{ form_widget(form) }}
<input type="submit" class="btn btn-primary"/>
</form>
<div class='errors'>
{{ form_errors(form) }}
</div>
</div>
'form' is the name of my variable to the first form
and 'update' for my second form.
When I attempted to submit my second form, I need to click twice and finally I get :
"This form should not contain extra fields."
And all non valid input for the remainding form.
I tried to add validation_group to false but to no avail.
I don't understand why I got this error because my forms are not embedded at all
I hope you will understand...
You have to treat the forms separately:
if('POST' === $request->getMethod()) {
if ($request->request->has('form1name')) {
// handle the first form
}
if ($request->request->has('form2name')) {
// handle the second form
}
}
This is perfectly explained in Symfony2 Multiple Forms: Different From Embedded Forms (temporarily unavailable - see below)
Update
As the link provided above is temporarily unavailable, you can see an archive of that resource here.
This did the trick for me in Symfony 3 (should also work for Symfony 2):
$form1 = $this->createForm(
MyFirstFormType::class
);
$form2 = $this->createForm(
MySecondFormType::class
);
if ($request->isMethod('POST')) {
$form1->handleRequest($request);
$form2->handleRequest($request);
if ($form1->isSubmitted()) {
// Handle $form1
} else if ($form2->isSubmitted()) {
// Handle $form2
}
}
The problem is that you have two nameless forms (input names like inputname instead of formname[inputname], and thus when you bind the request to your form and it gets validated it detects some extra fields (the other form) and so it is invalid.
The short-term solution is to create a named builder via the form factory, so instead of:
$form = $this->createFormBuilder(null)
you should use:
$form = $this->get("form.factory")->createNamedBuilder("my_form_name")
The long term solution would be to create your own form classes, that way you can keep your form code separate from the controller.
The two forms will be posted.
Try using:
$this->createNamedBuilder
instead of
$this->createFormBuilder
Then in your controller, locate the form by name:
if ($request->request->has("your form name") {
$form->handleRequest($request);
}
This is how I handle them on my controller :
return $this->render('SgaDemandeBundle:Demande:suivi_avancement.html.twig',
array('form' => $form->createView(),
........
'update' => $formModification->createView()));
This is the html for the second form :
<div class="well">
<form method="post">
<div id="form">
<div>
<button type="submit" id="form_modification"
name="form[modification]">Modification done
</button>
</div>
<input type="hidden" id="form__token" name="form[_token]"
value="fFjgI4ecd1-W70ehmLHmGH7ZmNEHAMqXlY1WrPICtK4">
</div>
</form>
</div>
This is my twig rendered :
<div class="well">
<form method="post" {{form_enctype(update)}} >
{{ form_widget(update) }}
</form>
</div>
<div class="well">
<form method="post" action='' {{form_enctype(form)}} >
{{ form_widget(form) }}
<input type="submit" class="btn btn-primary"/>
</form>
<div class='errors'>
{{ form_errors(form) }}
</div>
</div>
I hope this will help you.
Using Named forms is a viable solution for handling multiple forms, but it can get a little messy, particularly if you're generating forms dynamically.
Another method, as of Symfony 2.3, is to check which submit button was clicked.
For example, assuming that each form has a submit button named 'save':
if ('POST' == $Request->getMethod())
{
$form1->handleRequest($Request);
$form2->handleRequest($Request);
$form3->handleRequest($Request);
if ($form1->get('save')->isClicked() and $form1->isValid())
{
//Do stuff with form1
}
if ($form2->get('save')->isClicked() and $form2->isValid())
{
//Do stuff with form2
}
if ($form3->get('save')->isClicked() and $form3->isValid())
{
//Do stuff with form3
}
}
I believe this has a small amount of additional overhead as compared to the named builder method (due to multiple handleRequest calls), but, in certain cases, it results in cleaner code. Always good to have multiple solutions to choose from. Some of the additional overhead could be alleviated via nested if/else statements, if necessary, but, unless we're talking about dozens of forms per page, the additional overhead is negligible in any case.
Here's an alternate implementation using anonymous functions that minimizes code repetition:
$form1Action = function ($form) use (&$aVar) {
//Do stuff with form1
};
$form2Action = function ($form) use (&$anotherVar) {
//Do stuff with form2
};
$form3Action = function ($form) use (&$yetAnotherVar) {
//Do stuff with form3
};
$forms = [$form1 => $form1Action,
$form2 => $form2Action,
$form3 => $form3Action];
if ('POST' == $Request->getMethod())
{
foreach ($forms as $form => $action)
{
$form->handleRequest($Request);
if ($form->get('save')->isClicked() and $form->isValid())
{
$action($form);
}
}
}
Look at the blockprefix :
public function getBlockPrefix()
{
return 'app_x_form'.$form_id;
}

Categories