How can I display TRUE/FALSE instead of 1/0 on laravel8 and Eloquent? - eloquent

Hi § I am creating a form using Laravel 8 and Eloquent.
Here is my form :
<div class="mt-2">
<label for="is-active"></label>
<input type="checkbox" id="is-active" name='is_active">
</div>
My migration file looks like :
public function up()
{
Schema::table('newspapers', function (Blueprint $table) {
$table->boolean('is_active')->default(0);
});
}
In my Model, I have added this :
protected $casts = [
'is_active' => 'boolean',
];
In my Controller :
$offer->is_active=$request->has('is_active');
Thanks for your help !

if you mean display in the views, you can simply do this in your blade file:
{{ $offer->is_active ? 'TRUE' : 'FALSE' }}

Related

How to display the componentProperties options by the selected option in the dropdown?

I'm sure this is very simple but it's proving just a bit beyond me at the moment.
I have made a plugin that I would like to use for displaying galleries which is working fine. However, trying to add the options of the galleries that I have created in my component is proving to be difficult.
When I add the component to a page, I have now got the option to choose all the galleries that I created but displaying the gallery based upon which one I selected is what I have been unsuccessful in doing.
Any help would be greatly appreciated!
I'm sure this is very simple but it's proving just a bit beyond me at the moment.
I have made a plugin that I would like to use for displaying galleries which is working fine. However, trying to add the options of the galleries that I have created in my component is proving to be difficult.
When I add the component to a page, I have now got the option to choose all the galleries that I created but displaying the gallery based upon which one I selected is what I have been unsuccessful in doing.
Any help would be greatly appreciated!
Components/Gallery.php:
use Cms\Classes\ComponentBase;
use MartinSmith\Gallerys\Models\Gallery as GalleryModel;
class gallerys extends ComponentBase
{
public $gallery;
public function componentDetails(){
return [
'name' => 'Frontend Gallery',
'description' => 'A gallery for you webpage'
];
}
public function defineProperties() {
$lists = $this->getLists();
return [
'galleryName' => [
'title' => 'Gallery',
'type' => 'dropdown',
'placeholder' => 'Select Gallery',
'options' => $lists
]
];
}
public function getLists() {
$agreements = GalleryModel::all()->pluck('name', 'id');
return $agreements->toArray();
}
public function getList() {
$agreement = GalleryModel::where('id', $this->property('galleryName'))->get();
return $agreement->first();
}
}
Components/gallery/default.htm:
{% set gallerys = __SELF__.gallery %}
{% for gallery in gallerys %}
<div class="container-fluid px-0">
<div class="gallery">
<div class="row">
{% for image in gallery.fullImage %}
<div class="col-md-4 px-0 home-galleryImg">
<a href="{{ image.path }}">
<div class="gallery-imgOverlay">
<p>{{ image.title }}</p>
<h5>{{ image.description }}</h5>
</div>
<img class="img-fluid" src="{{ image.thumb(650,auto) }}" alt="{{ thumbnail.description }}">
</a>
</div>
{% endfor %}
</div>
</div>
</div>
{% endfor %}
See screenshot
I solved this for myself by creating a function that returns the "name" and indexed by the 'id' using the laravel pluck method. pluck('name', 'id') The first argument selects the column to use as the value and the second argument selects the column to use as a key. Note* the toArray() method I don't think the options field can take collections.
public function getLists() {
$agreements = Agreements::all()->pluck('agrnum', 'id');
return $agreements->toArray();
}
//returns
array:3 [▼
2 => "DLE-2"
4 => "DLE-1"
5 => "DLE-3"
]
Now in my properties area I call the function $list = $this->getList();
public function defineProperties() {
$lists = $this->getLists();
return [
'getList' => [
'title' => 'List',
'type' => 'dropdown',
'placeholder' => 'Select List',
'options' => $lists
]
];
}
After that you can proceed to do a Lists::where('id', $this->property('getList')); or something of that sort in a function to show the selected list or in your case gallery.
My results:
The CMS Page Backend from component
public function defineProperties() {
$lists = $this->getLists();
return [
'getList' => [
'title' => 'List',
'type' => 'dropdown',
'placeholder' => 'Select List',
'options' => $lists
]
];
}
public function getLists() {
$agreements = Agreements::all()->pluck('agrnum', 'id');
return $agreements->toArray();
}
public function getList() {
$agreement = Agreements::where('id', $this->property('getList'))->get();
return $agreement->first();
}
The Webpage from default.htm in the component template folder
{{ d(__SELF__.getList) }}
Also if I do {{ d(__SELF__.property('getList')) }} it shows me the value is "5".

Form using dropdown doesn't work on Phalcon

I'm using the framework Phalcon. I'm trying to create a form to get a value (an ID called "idcliente") from a table (in mysql) called cliente, which has 2 columns: "idcliente" and "nombre". With this value I want to update a field (also "idcliente") on another table called Users.
My form is this:
class AsignarclienteForm extends Form{
public function initialize($entity = null, $options = null){
$idcliente = new Select('idcliente',[
Cliente::find(),
"useEmpty" => true,
"emptyText" => "Please select...",
"using" => ["idcliente", "nombre"],
]);
$idcliente->setLabel('ID Cliente');
$idcliente->addValidators(array(
new PresenceOf(array(
'message' => 'idcliente is required'
))
));
$this->add($idcliente);
}
}
And my controller:
public function asignarclienteAction(){
$auth = $this->session->get('auth');
$permiso = $auth['active'];
$id = $auth['id'];
if($permiso!='A'){return $this->forward('servicios/index');}
$form = new AsignarclienteForm;
if ($this->request->isPost()) {
$idcliente = $this->request->getPost('idcliente');
$sql = "UPDATE Users SET idcliente = ?0 WHERE id = ?1";
$this->modelsManager->executeQuery($sql, array(0 => $idcliente, 1 => $id));
return $this->forward('admin/usuarios');
}
$this->view->form = $form;
}
And my view:
<div class="panel-body">
{{ form('admin/asignarcliente/', 'id': 'asignarclienteForm', 'onbeforesubmit': 'return false') }}
<fieldset>
<div class="control-group">
{{ form.label('idcliente', ['class': 'control-label']) }}
<div class="controls">
{{ form.render('idcliente', ['class': 'form-control']) }}
</div>
</div>
<div class="form-actions">
{{ submit_button('Asignar', 'class': 'btn btn-primary', 'onclick': 'return SignUp.validate();') }}
</div>
</fieldset>
</form>
</div>
I got the following error in the web site:
ID Cliente
Catchable fatal error: Object of class Phalcon\Mvc\Model\Resultset\Simple could not be converted to string in C:\xampp\htdocs\OpinionZoom\cache\volt\c%%%%xampp%%htdocs%%opinionzoom%%app%%views%%admin%%asignarcliente.volt.php on line 31
Where line 31 is {{ form.render('idcliente', ['class': 'form-control']) }}
on my view
I haven't found enough documentation of how to create a form with select, despite I have created a lot of forms.
If someone could help me I would appreciate it a lot. Thanks.
Your element definition in your form Asignarclienteform is incorrect.
The first parameter of Select must be a string (the name of your element).
The second parameter takes the options of your select element.
// Select construct parameters
Select(string $name, [object | array $options], [array $attributes])
I moved idcliente out of the array into the first parameter position:
$idcliente = new Select('idcliente', Cliente::find(), [
"useEmpty" => true,
"emptyText" => "Please select...",
"using" => ["idcliente", "nombre"],
]);

Symfony - Add text in generated form

I'd like to do something quite simple, but I can't figure out how to manage it. I have a form:
{{ form_start(form) }}
{{ form_widget(form) }}
{{ form_end(form) }}
There are several text field in it. I'd like to "insert" some text (like <p>my Text</p>) between two text fields (let's say between name text field and description text field). Form are generated with form builder tool. I've tried something like:
$builder
->add('stuffName') // works well (text field 1)
->add('addedText', 'text', array('label' => 'my Text')) // Trouble here!
->add('stuffDescription'); // works well (text field 2)
But it generates a text field (and not a simple text). I don't care if the text is set in the form builder or directly in twig template... As long as it is between my two text fields. Any idea?
Thanks a lot!
Symfony forms contain only form fields. Any additional content you want has to be added by the template.
This means you'll have to output the form field-by-field. Your form, for example might look like this:
{{ form_start(form) }}
{{ form_row(form.stuffName) }}
<p>Your Text</p>
{{ form_row(form.stuffDescription) }}
{{ form_end(form) }}
For more more information on how you can customize form rendering, please see the forms chapter in the Symfony documentation.
The keyword in this question is generated.
Let's assume, that you build a form generator in Symfony. You have entities like Form, Fields and Fields Items (it's options for select box or buttons for radio button field).
So you have this entities and you create a service to create a form from the data. In the service you build the form ($this->buildedForm - generated form, $page->getFormData() - put the data to the constructed form):
$this->buildedForm = $this->formFactory->create(
'form',
$page->getFormData(),
['action' => '/page/formview/' . $task->getId()]
);
foreach($fields as $field) {
$fieldBuilderMethod = 'construct' . ucfirst($field->getType()) . 'Field';
if (method_exists($this, $fieldBuilderMethod)) {
$this->$fieldBuilderMethod($field);
}
}
return $this->buildedForm;
And you have methods for each type like (examples for Symfony 2):
private function constructInputField(FormField $field)
{
$this->buildedForm->add(
$field->getFieldName(),
'text',
[
'label' => $field->getName(),
]
);
}
private function constructTextareaField(FormField $field)
{
$this->buildedForm->add(
$field->getFieldName(),
'textarea',
[
'label' => $field->getName(),
]
);
}
You can now create your custom form type to paste a text in the generated form (it could be placed in the form folder of your bundle and retrieved with namespace "use"):
private function constructSimpletextField(FormField $field)
{
$this->buildedForm->add(
$field->getFieldName(),
new SimpletextType(),
[
'label' => $field->getName(),
'data' => $field->getPlaceholder(),
]
);
}
What in this custom field?
namespace Myproject\MyBundle\Form\TaskTypes;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;
class SimpletextType extends AbstractType
{
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'disabled' => true,
'required' => false,
'mapped' => false,
]);
}
public function getParent()
{
return 'text';
}
public function getName()
{
return 'simpletext';
}
}
And the whole magic comes out in the template. For your custom form type you need to make a custom theme (see https://symfony.com/doc/2.7/form/form_customization.html#form-customization-form-themes). And there:
{% block simpletext_label %}{% endblock %}
{% block simpletext_widget %}
<p>{{ form.vars.data }}</p>
{% endblock %}
{% block simpletext_errors %}{% endblock %}
See, no label, no errors (it just a text) and only text in the field widget. Very handy for generated forms with dynamic template.
EDIT - Symfony 5
In Symfony 5, this solution became simplier. The form customization doesn't changes, and the php code became like this:
namespace Myproject\MyBundle\Form\TaskTypes;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;
class SimpletextType extends AbstractType
{
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'disabled' => true,
'required' => false,
'mapped' => false,
]);
}
public function getBlockPrefix(): string
{
return 'simpletext';
}
}
It's used like this :
public function buildForm(FormBuilderInterface $builder, array $options): void {
/* … */
$builder->add('anykey', SimpleTextType::class, [
'data' => "Type your text here",
]);
/* … */
}
Here a sample code which would be self explain
{{ form_start(form, { 'attr': { 'class': 'form-horizontal form-bordered'} }) }}
<div class="form-group">
<div class="col-md-3 ">
{{ form_label(form.User, 'Label text', { 'attr': {'class': 'control-label'} }) }}
</div>
<p>You are free to add whatever you want here</p>
<div class="col-md-9">
{{ form_widget(form.User, { 'attr': {'class': 'form-control'} }) }}
</div>
</div>
{{ form_rest(form) }}
{{ form_end(form) }}
In any case, the symfony documentation is pretty clear and well-explain about this point.

Use same form on two different pages (URLs) in Symfony 2

I am using the FOSUserBundle with Symfony 2.5.
I have overridden the default registration form and defined a new URL for it.
fos_user_registration_register:
path: /user/new.html
defaults: { _controller: FOSUserBundle:Registration:register }
and this is the form
class RegistrationFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->remove('plainPassword');
$builder->remove('username');
$builder->remove("email");
$builder->add('terms', 'checkbox', array('required' => true,
'mapped' => false,
'constraints' => new True(array('message' => 'Required!'))));
$builder->add("email", "email", array("required" => true, "mapped" => true, "constraints" => new MailBlacklist()));
}
public function getParent()
{
return 'fos_user_registration';
}
public function getName()
{
return 'my_user_registration';
}
}
finally I registered it as a service.
When I show the form on the URL /user/new.html and submit it, it works: validation errors are shown and if everything is fine with the data, the user is created.
But when I show exactly the same form on a different URL (the root) and submit the form, no validation is done and the user is not saved. Instead, I get redirected to /user/new.html and see an empty form.
I create the form like this
$form = $this->createForm('my_user_registration')->createView();
Why isn't this working? Is FOSUserBundle checking the referer or something?
My template
<form action="{{ path('fos_user_registration_register') }}" {{ form_enctype(form) }} method="POST">
{{ form_widget(form) }}
<div>
<input type="submit" value="Registrieren" />
</div>
</form>
Would be great if someone could help my with this "little" problem :)
Problem was the name of my form. If I use the FOSUserBundle form factory instead of createForm(), it works and the name is the right one

How can I show a form with the old values so that you can edit?

in controller I find the id
$oggetto = $this->getDoctrine()
->getRepository('AcmeTryBundle:Try')
->find($id);
after I passed this $values into form(just?)
$form = $this->createForm(new TryType(), $oggetto);
and in FormType? what I put?
public function buildForm(FormBuilder $builder, array $options)
{
$builder->add('name','text') ?
Your approach is good.
1) Get your $oggetto object in DB
2) Pass it to your FormType $form = $this->createForm(new TryType(), $oggetto);
3) Add the fields you want in your form type
4) Send your form to your view 'form' => $form->createView()
5) In your view, call your form
<form action="{{ path('task_new') }}" method="post" {{ form_enctype(form) }}>
{{ form_widget(form) }}
<input type="submit" />
</form>
Your fields (you defined in 3) ) will be automaticaly populated by your object data. You can then change them and edit them.
See the doc for more info: http://symfony.com/doc/current/book/forms.html
Your Form seems fine
class TryFormType extends AbstractType {
public function buildForm(FormBuilder $builder, array $options)
{
$builder->add('name','text') ;
}
public function getName() {
return 'tryform';
}
}
The function getName gives the form a name, which in this case is tryform.
In the controller you can add a return statement like this.
return $this->render('AcmeTryBundle:Default:TryForm.html.twig', array(
'TryForm' => $form->createView()
));
And in twig file access it as follows.
{{ form_widget(TryForm.name) }}
The value will automatically be passed there. You can then edit it
For example in Symfony 4.2.3, you filled and submitted a form and some form values are invalid.
<input type="text" name="name" value="{{ form.vars.value.name }}">
In this way, you will be set old form input as a default value if the value is valid.