Good day. My group our currently working in our final project using Laravel. I have this problem that I encounter.
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use app\database\seeders\Survey;
class SurveySeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$survey = Survey::create(['name' => 'Register Form', 'settings' => ['accept-guest-entries' => true]]);
$survey->questions()->create([
'content' => 'First Name',
]);
$survey->questions()->create([
'content' => 'Last Name',
]);
$survey->questions()->create([
'content' => 'Date of Birth (MM/DD/YYYY)',
]);
$survey->questions()->create([
'content' => 'Full Address',
]);
$survey->questions()->create([
'content' => 'Blood Group',
'type' => 'radio',
'options' => ['A', 'B', 'O', 'AB']
]);
$survey->questions()->create([
'content' => 'Phone Number',
'type' => 'number',
'rules' => ['numeric', 'min:11', 'max:11']
]);
}
}
I found some solutions but it doesn't work for me. I hope you can help me to get through this.
Where is your model Survey.php?
If in app/Models then you need to
use App\Models\Survey;
Related
I am just starting to learn Laravel and I am a little lost here. This code works without validation.
The task is to build a website with user registration Posting data to an already existing database. As I have pointed, without validation it works just fine but when i add validation it fails.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Member;
class RegController extends Controller
{
public function store(Request $request) {
Member::create([
'fname' => $request ->fname,
'lname' => $request ->lname,
'gender' => $request ->gender,
'msisdn' => $request ->msisdn,
'email' => $request ->email,
'status' => $request ->mstatus,
'no_of_children' => $request ->kids,
'occupation' => $request ->profession,
'age' => $request ->age,
'bna' => $request ->bna,
'residence' => $request ->residence,
]);
return redirect('/members/register');
}
}
But this doesn't...
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Member;
class RegController extends Controller
{
public function store(Request $request) {
$request->validate([
'fname' => 'required',
'lname' => 'required',
'gender' => 'required',
'msisdn' => 'required|unique:members_tbl',
'email' => 'required|unique:members_tbl',
'status' => 'required',
'kids' => 'required',
'profession' => 'required',
'age' => 'required',
'bna' => 'required',
'residence' => 'required',
],
[
'fname.required' => 'Please Enter your First Name',
'lname.required' => 'Please Enter your Last Name',
'gender.required' => 'Please Enter your Gender',
'msisdn.required' => 'Please Enter your Phone Number',
'msisdn.unique' => 'A user has already registered with the phone Number',
'email.unique' => 'A user has already registered with the email',
'email.required' => 'Please enter a valid email address',
'status.required' => 'Please Let us know your marital status',
'kids.required' => 'Please fill out this field',
'profession.required' => 'Please fill out this field',
'age.required' => 'Please fill out this field',
'bna.required' => 'Please fill out this field',
'residence.required' => 'Please let us know where you live',
]);
Member::create([
'fname' => $request ->fname,
'lname' => $request ->lname,
'gender' => $request ->gender,
'msisdn' => $request ->msisdn,
'email' => $request ->email,
'status' => $request ->mstatus,
'no_of_children' => $request ->kids,
'occupation' => $request ->profession,
'age' => $request ->age,
'bna' => $request ->bna,
'residence' => $request ->residence,
]);
return redirect('/members/register');
}
}
What am i missing? The code works well without the validation but just redirects back to the form when validation is added.
Here is my Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Member extends Model
{
use HasFactory;
public $timestamps = false;
protected $table="members_tbl";
protected $fillable =[
'fname',
'lname',
'gender',
'msisdn',
'email',
'status',
'no_of_children',
'occupation',
'age',
'bna',
'residence'
];
}
This is the result of var_dump($request)
public 'request' =>
object(Symfony\Component\HttpFoundation\InputBag)[44]
protected 'parameters' =>
array (size=13)
'_token' => string 'DuNeITGaDF9K7eEMmU4HwX7nVLJUYDaZ1iYGT4dw' (length=40)
'fname' => string 'Joe' (length=3)
'lname' => string 'Peski' (length=5)
'gender' => string 'male' (length=4)
'msisdn' => string '254722000001' (length=12)
'email' => string 'joetry#hotmail.com' (length=18)
'residence' => string 'New Place' (length=9)
'age' => string 'teen' (length=4)
'bna' => string 'no' (length=2)
'mstatus' => string 'single' (length=6)
'kids' => string '4' (length=1)
'profession' => string 'IT' (length=2)
'submit' => string 'Submit' (length=6)
I believe it's working as intended. If you are not repopulating the fields with the old values then it looks like the page just gets redirected. Also you need to display the validation messages on the page.
https://laravel.com/docs/8.x/validation#repopulating-forms
https://laravel.com/docs/8.x/validation#quick-displaying-the-validation-errors
Validator doesn't read your status. Make sure you have a default value for this field.
If status is not required, you can change required to nullable, then create a default value after validation.
You need to display an error message to know what the error is.
$errors = $validator->errors();
Usually, this case occurs when you use a select box, check box, or something that can't read a value or empty, null.
The solution is to add a default value or add a hidden field with a default value.
<input type="hidden" name="status" value="0">
<select name="status">
...
</select>
I'm wanting to be able to handle polymorphic relations with Backpack CRUD. I can't find any good explanations and I'm struggling to unpick its implementation in their other packages (e.g. PermissionManager). What I'm wanting to do is to be able to change the specialties Users & Clinicians are linked to - similar to how roles & permissions change in the Permission Manager.
I have a polymorphic n-n relationship with Users & Clinicians to Specialties. Each model CRUDTrait.
Specialty Model
public function user()
{
return $this->morphedByMany(User::class, 'model', 'model_has_specialties');
}
public function clinician()
{
return $this->morphedByMany(Clinician::class, 'model', 'model_has_specialties');
}
User Model
public function specialties()
{
return $this->morphToMany(Specialty::class, 'model', 'model_has_specialties');
}
Clinician Model
public function specialties()
{
return $this->morphMany(Specialty::class, 'model', 'model_has_specialties');
}
The pivot table is 'model_has_specialties' and contains:
$table->increments('id');
$table->timestamps();
$table->integer('model_id');
$table->string('model_type');
$table->integer('specialty_id');
$table->unique(['model_id', 'model_type', 'specialty_id']);
I have tried a number of different addField() configurations however I'm really struggling.
Example of addField() tried:
$this->crud->addField([
'label' => 'specialties',
'type' => 'select',
'morph' => true,
'name' => 'model_id',
'entity' => 'ModelHasSpecialties',
'attribute' => 'model_id',
'model' => 'App\Models\Clinician',
'pivot' => true,
]);
** Edit **
Here's the ClinicianCrudController which is the link between the clinician class & bootstrap.
class ClinicianCrudController extends CrudController
{
public function setup()
{
/*
|--------------------------------------------------------------------------
| CrudPanel Basic Information
|--------------------------------------------------------------------------
*/
$this->crud->setModel('App\Models\Clinician');
$this->crud->setRoute(config('backpack.base.route_prefix') . '/clinician');
$this->crud->setEntityNameStrings('clinician', 'clinicians');
$this->crud->setColumns(['surname', 'forename', 'title', 'specialties']);
$this->crud->addField([
'name' => 'surname',
'type' => 'text',
'label' => 'Surname'
]);
$this->crud->addField([
'name' => 'forename',
'type' => 'text',
'label' => 'Forename'
]);
$this->crud->addField([
'name' => 'title',
'type' => 'select_from_array',
'options' => [
'Dr' => 'Dr',
'Miss' => 'Miss',
'Mr' => 'Mr',
'Mrs' => 'Mrs',
'0Ms' => 'Ms',
'Prof' => 'Prof',
],
'label' => 'Title',
'allows_null' => false,
]);
$this->crud->addField([
'label' => 'specialties',
'type' => 'select',
'morph' => true,
'name' => 'model_id',
'entity' => 'ModelHasSpecialties',
'attribute' => 'model_id',
'model' => 'App\Models\Clinician',
'pivot' => true,
]);
/*
|--------------------------------------------------------------------------
| CrudPanel Configuration
|--------------------------------------------------------------------------
*/
// TODO: remove setFromDb() and manually define Fields and Columns
$this->crud->setFromDb();
// add asterisk for fields that are required in ClinicianRequest
$this->crud->setRequiredFields(StoreRequest::class, 'create');
$this->crud->setRequiredFields(UpdateRequest::class, 'edit');
}
I tried to validate a simple form in zend framework 2 for days now.
I checked the documentation and a lot of posts considering this topic but I found no solution!
I have a very simple form:
class AlimentForm extends Form
{
public function __construct($name = null)
{
parent::__construct('aliment');
$this->add(array(
'required'=>true,
'name' => 'year',
'type' => 'Text',
'options' => array(
'label' => 'Jahr',
),
));
$this->add(array(
'required'=>true,
'name' => 'number',
'type' => 'Text',
'options' => array(
'label' => 'Number',
),
));
$this->add(array(
'name' => 'submit',
'type' => 'Submit',
'attributes' => array(
'value' => 'Go',
'id' => 'submitbutton',
),
));
}
}
I created a custom InputFilter:
namespace Application\Form;
use Zend\InputFilter\InputFilter;
class AlimentInputFilter extends InputFilter {
public function init()
{
$this->add([
'name' => AlimentForm::year,
'required' => true,
'validators' => array(
array(
'name' => 'Between',
'options' => array(
'min' => 1900,
'max' => 3000,
),
),
),
]);
}
}
and finally in my controller I try to validate the form
public function alimentAction(){
$form = new AlimentForm();
$form->setInputFilter(new AlimentInputFilter());
$request = $this->getRequest();
if ($request->isPost()) {
$form->setData($request->getPost());
if ($form->isValid()) {
$year = $form->get('year')->getValue();
$number = $form->get('number')->getValue();
return array('result' => array(
"msg" => "In the Year ".$year." you get ".$number." Points"
));
}
}
return array('form' => $form);
}
It can't be that difficult, but from all those different ways to validate a form I found in the net, I'm a bit confused...
What am I missing?
Greetings and thanks in advance
U.H.
Ok, I solved the problem.
I created a Model for the aliment Form that has a year and a number attribute
and I defined an input filter within that model:
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;
class Aliment implements InputFilterAwareInterface
{
public $year;
public $number;
public function exchangeArray($data){
$this->year = (!empty($data['year']))?$data['year']:null;
$this->number = (!empty($data['number']))?$data['number']:null;
}
public function setInputFilter(InputFilterInterface $inputFilter)
{
throw new \Exception("Not used");
}
public function getInputFilter()
{
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
$inputFilter->add(array(
'name' => 'year',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'Between',
'options' => array(
'min' => 1900,
'max' => 3000
)
)
),
));
$inputFilter->add(array(
'name' => 'number',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'Between',
'options' => array(
'min' => 1,
'max' => 10
)
)
),
));
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
}
In the action method of the controller I was able to set the InputFilter of the model to the form and voila! It worked!
public function alimentAction(){
$form = new AlimentForm();
$request = $this->getRequest();
if ($request->isPost()) {
$aliment = new \Application\Model\Aliment;
$form->setInputFilter($aliment->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$aliment->exchangeArray($form->getData());
$year = $form->get('year')->getValue();
return array(
'result' => array(
//your result
)
);
}
}
return array('form' => $form);
}
The form is correctly validated now and returns the corresponding error messages.
I hope, it help somebody whos got similar problems with validating!
I have created a custom extension just like a customer module and I want backend just like a customer.
My extension has two tables and two models.
My modules are:
Mage::getModel('custommod/reg') - just like Mage::getModel('customer/customer'), reg saves data of registration
Mage::getModel('custommod/personal') - just like Mage::getModel('customer/address'), //personal data of a reg records.
Please check the image below:
Now I am facing the problem to show the data and edit .
In Magento customer admin section, Customer edit position has multiple tabs: Account information, Address etc.
Here, Account information tab saves data in customer/customer
and Address information tab saves data in customer/address.
I like this type of section.
After a long time work i have done it ,Here the solution
The tabs.php show left panel
<?php
class Amit_Vendor_Block_Adminhtml_List_Edit_Tabs extends Mage_Adminhtml_Block_Widget_Tabs
{
public function __construct()
{
parent::__construct();
$this->setId('vendor_tabs');
$this->setDestElementId('edit_form');
$this->setTitle(Mage::helper('vendor')->__('Manage Vendor'));
}
protected function _beforeToHtml()
{
$this->addTab('form_section', array(
'label' => Mage::helper('vendor')->__('General Information'),
'title' => Mage::helper('vendor')->__('General Information'),
'content' => $this->getLayout()->createBlock('vendor/adminhtml_list_edit_tab_form')->toHtml(),
));
$this->addTab('vendor_details',array(
'label'=>Mage::helper('vendor')->__('Vendor Store Details'),
'title'=>Mage::helper('vendor')->__('Vendor Store Details'),
'content'=>$this->getLayout()->createBlock('vendor/adminhtml_list_edit_tab_storedetails')->toHtml(),
));
return parent::_beforeToHtml();
}
}
after the form.php
<?php
class Amit_Vendor_Block_Adminhtml_List_Edit_Tab_Form extends Mage_Adminhtml_Block_Widget_Form
{
protected function _prepareForm()
{
$vendor = Mage::registry('vendor_data');
$form = new Varien_Data_Form();
$fieldset = $form->addFieldset('vendor_form', array(
'legend' => Mage::helper('vendor')->__('Vendor Registration')
));
$fieldset->addField('name', 'text', array(
'name' => 'name',
'label' => Mage::helper('vendor')->__('Name'),
'required' => true,
));
$fieldset->addField('email', 'text', array(
'name' => 'email',
'label' => Mage::helper('vendor')->__('Email'),
'required' => true,
));
$fieldset->addField('user_name', 'text', array(
'name' => 'user_name',
'label' => Mage::helper('vendor')->__('User name'),
'required' => true,
));
$fieldset->addField('password', 'password', array(
'name' => 'password',
'class' => 'required-entry',
'label' => Mage::helper('vendor')->__('Password'),
'required' => true,
));
$this->setForm($form);
$form->setValues($vendor->getData());
return parent::_prepareForm();
}
public function filter($value)
{
return number_format($value, 2);
}
}
Second form Storedetails.php
<?php
class Amit_Vendor_Block_Adminhtml_List_Edit_Tab_Storedetails extends Mage_Adminhtml_Block_Widget_Form{
protected function _prepareForm(){
$vendorStore = Mage::registry('vendor_store_details');// new registry for different module
$form = new Varien_Data_Form();
//$form->setFieldNameSuffix('vendor_store');
$fieldset = $form->addFieldset('vendor_form', array(
'legend' => Mage::helper('vendor')->__('Vendor deatsilsn')
));
$fieldset->addField('alternative_email','text',array(
'name' =>'alternative_email',
'label' => Mage::helper('vendor')->__('Alternative Email'),
'required'=> false
));
$fieldset->addField('shopname','text',array(
'name' =>'shopname',
'label' => Mage::helper('vendor')->__('Shop Name'),
'required'=> true,
'class' => 'required-entry',
));
$fieldset->addField('company', 'text', array(
'name' => 'company',
'label' => Mage::helper('vendor')->__('Company'),
'required' => true,
'class' => 'required-entry',
));
$fieldset->addField('street','text',array(
'name' =>'vendor_details[street]',
'label' => Mage::helper('vendor')->__('Street Address'),
'required'=> false
));
$this->setForm($form);
$form->addValues($vendorStore->getData());
return parent::_prepareForm();
}
}
If the first field called sendEmail has value ="Yes" the rest of the fields are to be validated...
I have this set_rules defined in the form_validation.php file in the config folder..
$config = array(
array(
'field' => 'sendEmail',
'label' => 'Send Email',
'rules' => 'required'
),
array(
'field' => 'email',
'label' => 'Email',
'rules' => 'required'
),
array(
'field' => 'first_name',
'label' => 'First Name',
'rules' => 'required'
),
array(
'field' => 'last_name',
'label' => 'Last Name',
'rules' => 'required'
)
);
but email, first_name and last_name fields are to be validated only if sendEmail has value="Yes".
Not sure how to do this, can someone please help me with this?
thanks
Do the conditions like this in your controller:
if ($this->input->post('sendEmail') == 'Yes'){
$this->form_validation->set_rules('email', 'Email', 'required');
... [etc]
}
The validation only runs when you call $this->form_validation->run(), so just write an if statement before that. Something like this:
if ($this->input->post("sendEmail") == 'Yes') {
$this->form_validation->set_rules($config);
if ($this->form_validation->run() == FALSE)
{
// failed validated
}
else
{
// passed validation
}
} else {
// never attempted validation
}