不能同时禁用实体字段并保留其值 [英] Cannot both disable entity field and retain its value

查看:27
本文介绍了不能同时禁用实体字段并保留其值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在表单事件中,设置字段 'attr' =>array('readonly' => 'readonly') 呈现为 "disabled" = "1".这不是想要的效果.禁用的选择字段在提交时保留空值.只读字段应保留并保留显示的值.或者我是这么想的.那么如何让值保持不变、不可更改呢?

In a form event, setting a field 'attr' => array('readonly' => 'readonly') is rendered as "disabled" = "1". This is not the desired effect. A disabled select field persists a null value on submit. A readonly field should retain and persist the displayed value. Or so I thought. So how to get the value to remain unchanged and unchangeable?

编辑;

隐藏字段不起作用.choice_attr 也无济于事.

A hidden field does not do the trick. choice_attr does not help either.

我投票结束这个问题.我还没有发现任何显示禁用实体字段并保留该值的方法.如果你对如何做到这一点有任何想法......

I'm voting to close this question. I've not discovered any method for displaying a disabled entity field and also retain the value. If you've got any idea on how that's done...

一个例子(在 Symfony 2.8.3 中):Household 实体有六个属性,每个属性都是与 Household 存在一对多关系的实体.(该应用程序具有其他具有类似属性的实体.)Housing 实体/属性 Household 有两个属性:housing 和 enabled.如果应用程序的客户端不再打算跟踪该属性,则可以将其设置为 enabled = no.

An example (in Symfony 2.8.3): The Household entity has six attributes, each of which is an entity in a OneToMany relationship to Household. (The application has other entities which have similar attributes.) The Housing entity/attribute of Household has two properties: housing and enabled. The application's client can set a property to enabled = no if they no longer intend to track that property.

如果将属性设置为 enabled = no,则可以通过在实体字段的查询构建器中包含 where 子句,轻松消除其在新的或编辑的 Household 表单中的可用性,例如 ->where("h.enabled=1").但是,这样做会导致禁用属性设置为 null.因此需要以某种方式保留价值.

If a property is set to enabled = no its availability in a new or edit Household form is readily eliminated by including a where clause in the entity field's query builder, e.g., ->where("h.enabled=1"). However, doing so causes the disabled property to be set to null. Thus the need for retaining the value somehow.

理想的解决方案是为这些属性实体字段提供服务,该服务将显示值并在启用时保留为否.

The ideal solution would be a service for these attribute entity fields that would both display values and retain if enabled is no.

我尝试使用事件侦听器、隐藏字段、choice_attr,修改表单模板和表单主题都无济于事.例如,当需要实体字段时,隐藏字段是文本.这并不是说做不到,只是我没有找到正确的方法.

I have tried using an event listener, a hidden field, choice_attr, modifying the form template and the form theme all to no avail. For example, a hidden field is text when an entity field is required. This doesn't mean it can't be done, only that I haven't stumbled on the proper method.

推荐答案

最终解决方案:使用 Doctrine 元数据获取禁用的实体字段、表单类修改以及对于多对多关系的一些 jquery 和不可见模板条目的服务.

The eventual solution: a service using Doctrine metadata to get disabled entity fields, form class modifications, and, for ManyToMany relationships, some jquery and invisible template entry.

服务功能:

/**
 * Create array of disabled fields of an entity object
 * 
 * @param type $object
 * @return array
 */
public function getDisabledOptions($object) {
    $values = [];
    $className = get_class($object);
    $metaData = $this->em->getClassMetadata($className);
    foreach ($metaData->associationMappings as $field => $mapping) {
        if (8 > $mapping['type']) {
            $fieldName = ucfirst($field);
            $method = 'get' . $fieldName;
            if (method_exists($object->$method(), 'getEnabled') && false === $object->$method()->getEnabled()) {
                $values[] = $fieldName;
            }
        }
    }
    $manyToMany = json_decode($this->getMetaData($object), true);
    foreach(array_keys($manyToMany) as $key) {
        $values[] = $key;
    }

    return $values;
}

/**
 * Get array of disabled ManyToMany options
 *
 * @param Object $object
 * @return array
 */
public function getMetaData($object) {
    $data = array();
    $className = get_class($object);
    $metaData = $this->em->getClassMetadata($className);
    foreach ($metaData->associationMappings as $field => $mapping) {
        if (8 === $mapping['type']) {
            $data[$field] = $this->extractOptions($object, $field);
        }
    }

    return json_encode($data);
}

控制器使用服务:

    $searches = $this->get('mana.searches');
    $disabledOptions = $searches->getDisabledOptions($household);
    $metadata = $searches->getMetadata($household);
    ...
    $form = $this->createForm(HouseholdType::class, $household, $formOptions);
    ...
    return $this->render('Household/edit.html.twig',
            array(
            'form' => $form->createView(),
            ....
            'metadata' => $metadata,
    ));

表单类字段示例:

        ->add('housing', EntityType::class,
            array(
            'class' => 'TruckeeProjectmanaBundle:Housing',
            'choice_label' => 'housing',
            'placeholder' => '',
            'attr' => (in_array('Housing', $options['disabledOptions']) ? ['disabled' => 'disabled'] : []),
            'label' => 'Housing: ',
            'query_builder' => function (EntityRepository $er) use ($options) {
            if (false === in_array('Housing', $options['disabledOptions'])) {
                return $er->createQueryBuilder('alias')
                    ->orderBy('alias.housing', 'ASC')
                    ->where('alias.enabled=1');
            } else {
                return $er->createQueryBuilder('alias')
                    ->orderBy('alias.housing', 'ASC');
            }
        },
        ))
        ...

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'Truckee\ProjectmanaBundle\Entity\Household',
        'required' => false,
        'disabledOptions' => [],
    ));
}

Jquery 删除禁用属性:

Jquery to remove disabled attribute:

$("input[type=Submit]").click(function () {
    $("input").removeAttr("disabled");
    $("select").removeAttr("disabled");
});

模板示例 &多对多关系的jQuery:

Example of template & jquery for ManyToMany relationship:

<div id="household_options" style="display:none;">{{ metadata }}</div>

jquery:

if (0 < $("#household_options").length) {
    var house_options = JSON.parse($("#household_options").text());
    $.each(house_options, function (index, item) {
        $.each(item, function (k, v) {
            var formAttr = 'household_' + index + '_' + v.id;
            $("#" + formAttr).attr('disabled', 'disabled');
        });
    });
}

这篇关于不能同时禁用实体字段并保留其值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆